blob: 40dc6bfa3b0e917eaf398ffddece401e368768dd [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 Benyei21f18c42013-02-07 10:55:47 +0000200 case BuiltinType::OCLSampler:
Guy Benyeie6b9d802013-01-20 12:31:11 +0000201 case BuiltinType::OCLEvent:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000202 return true;
203
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!");
210
211 case BuiltinType::ObjCId:
212 case BuiltinType::ObjCClass:
213 case BuiltinType::ObjCSel:
214 llvm_unreachable("FIXME: Objective-C types are unsupported!");
215 }
216
217 llvm_unreachable("Invalid BuiltinType Kind!");
218}
219
220static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
221 QualType PointeeTy = PointerTy->getPointeeType();
222 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
223 if (!BuiltinTy)
224 return false;
225
226 // Check the qualifiers.
227 Qualifiers Quals = PointeeTy.getQualifiers();
228 Quals.removeConst();
229
230 if (!Quals.empty())
231 return false;
232
233 return TypeInfoIsInStandardLibrary(BuiltinTy);
234}
235
236/// IsStandardLibraryRTTIDescriptor - Returns whether the type
237/// information for the given type exists in the standard library.
238static 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);
242
243 // Type info for some pointer types to builtin types is defined in the
244 // standard library.
245 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
246 return TypeInfoIsInStandardLibrary(PointerTy);
247
248 return false;
249}
250
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.
John McCalld5617ee2013-01-25 22:31:03 +0000255static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
256 QualType Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000257 ASTContext &Context = CGM.getContext();
258
John McCalld5617ee2013-01-25 22:31:03 +0000259 // If RTTI is disabled, assume it might be disabled in the
260 // translation unit that defines any potential key function, too.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000261 if (!Context.getLangOpts().RTTI) return false;
262
263 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
264 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
265 if (!RD->hasDefinition())
266 return false;
267
268 if (!RD->isDynamicClass())
269 return false;
270
John McCalld5617ee2013-01-25 22:31:03 +0000271 // FIXME: this may need to be reconsidered if the key function
272 // changes.
273 return CGM.getVTables().isVTableExternal(RD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000274 }
275
276 return false;
277}
278
279/// IsIncompleteClassType - Returns whether the given record type is incomplete.
280static bool IsIncompleteClassType(const RecordType *RecordTy) {
281 return !RecordTy->getDecl()->isCompleteDefinition();
282}
283
284/// ContainsIncompleteClassType - Returns whether the given type contains an
285/// incomplete class type. This is true if
286///
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
291/// class type.
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.
295static bool ContainsIncompleteClassType(QualType Ty) {
296 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
297 if (IsIncompleteClassType(RecordTy))
298 return true;
299 }
300
301 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
302 return ContainsIncompleteClassType(PointerTy->getPointeeType());
303
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))
309 return true;
310
311 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
312 }
313
314 return false;
315}
316
317/// getTypeInfoLinkage - Return the linkage that the type info and type info
318/// name constants should have for the given type.
319static llvm::GlobalVariable::LinkageTypes
320getTypeInfoLinkage(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;
332
333 switch (Ty->getLinkage()) {
334 case NoLinkage:
335 case InternalLinkage:
336 case UniqueExternalLinkage:
337 return llvm::GlobalValue::InternalLinkage;
338
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;
344 }
345
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);
352 }
353
354 return llvm::GlobalValue::LinkOnceODRLinkage;
355 }
356
357 llvm_unreachable("Invalid linkage!");
358}
359
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.
363static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
364 // Check the number of bases.
365 if (RD->getNumBases() != 1)
366 return false;
367
368 // Get the base.
369 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
370
371 // Check that the base is not virtual.
372 if (Base->isVirtual())
373 return false;
374
375 // Check that the base is public.
376 if (Base->getAccessSpecifier() != AS_public)
377 return false;
378
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())
384 return false;
385
386 return true;
387}
388
389void 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";
399
400 const char *VTableName = 0;
401
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");
410
411 case Type::LValueReference:
412 case Type::RValueReference:
413 llvm_unreachable("References shouldn't get here");
414
Richard Smithdc7a4f52013-04-30 13:56:41 +0000415 case Type::Auto:
416 llvm_unreachable("Undeduced auto type shouldn't get here");
417
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000418 case Type::Builtin:
419 // GCC treats vector and complex types as fundamental types.
420 case Type::Vector:
421 case Type::ExtVector:
422 case Type::Complex:
423 case Type::Atomic:
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";
428 break;
429
430 case Type::ConstantArray:
431 case Type::IncompleteArray:
432 case Type::VariableArray:
433 // abi::__array_type_info.
434 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
435 break;
436
437 case Type::FunctionNoProto:
438 case Type::FunctionProto:
439 // abi::__function_type_info.
440 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
441 break;
442
443 case Type::Enum:
444 // abi::__enum_type_info.
445 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
446 break;
447
448 case Type::Record: {
449 const CXXRecordDecl *RD =
450 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
451
452 if (!RD->hasDefinition() || !RD->getNumBases()) {
453 VTableName = ClassTypeInfo;
454 } else if (CanUseSingleInheritance(RD)) {
455 VTableName = SIClassTypeInfo;
456 } else {
457 VTableName = VMIClassTypeInfo;
458 }
459
460 break;
461 }
462
463 case Type::ObjCObject:
464 // Ignore protocol qualifiers.
465 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
466
467 // Handle id and Class.
468 if (isa<BuiltinType>(Ty)) {
469 VTableName = ClassTypeInfo;
470 break;
471 }
472
473 assert(isa<ObjCInterfaceType>(Ty));
474 // Fall through.
475
476 case Type::ObjCInterface:
477 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
478 VTableName = SIClassTypeInfo;
479 } else {
480 VTableName = ClassTypeInfo;
481 }
482 break;
483
484 case Type::ObjCObjectPointer:
485 case Type::Pointer:
486 // abi::__pointer_type_info.
487 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
488 break;
489
490 case Type::MemberPointer:
491 // abi::__pointer_to_member_type_info.
492 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
493 break;
494 }
495
496 llvm::Constant *VTable =
497 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
498
499 llvm::Type *PtrDiffTy =
500 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
501
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);
506
507 Fields.push_back(VTable);
508}
509
510// maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
511// from available_externally to the correct linkage if necessary. An example of
512// this is:
513//
514// struct A {
515// virtual void f();
516// };
517//
518// const std::type_info &g() {
519// return typeid(A);
520// }
521//
522// void A::f() { }
523//
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.
530static void
531maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
532 QualType Ty) {
533 // We're only interested in globals with available_externally linkage.
534 if (!GV->hasAvailableExternallyLinkage())
535 return;
536
537 // Get the real linkage for the type.
538 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
539
540 // If variable is supposed to have available_externally linkage, we don't
541 // need to do anything.
542 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
543 return;
544
545 // Update the typeinfo linkage.
546 GV->setLinkage(Linkage);
547
548 // Get the typename global.
549 SmallString<256> OutName;
550 llvm::raw_svector_ostream Out(OutName);
551 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
552 Out.flush();
553 StringRef Name = OutName.str();
554
555 llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
556
557 assert(TypeNameGV->hasAvailableExternallyLinkage() &&
558 "Type name has different linkage from type info!");
559
560 // And update its linkage.
561 TypeNameGV->setLinkage(Linkage);
562}
563
564llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
565 // We want to operate on the canonical type.
566 Ty = CGM.getContext().getCanonicalType(Ty);
567
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);
572 Out.flush();
573 StringRef Name = OutName.str();
574
575 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
576 if (OldGV && !OldGV->isDeclaration()) {
577 maybeUpdateRTTILinkage(CGM, OldGV, Ty);
578
579 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
580 }
581
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);
586
587 // Emit the standard library with external linkage.
588 llvm::GlobalVariable::LinkageTypes Linkage;
589 if (IsStdLib)
590 Linkage = llvm::GlobalValue::ExternalLinkage;
591 else
592 Linkage = getTypeInfoLinkage(CGM, Ty);
593
594 // Add the vtable pointer.
595 BuildVTablePointer(cast<Type>(Ty));
596
597 // And the name.
598 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
599
600 Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
601
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");
610
611 // GCC treats vector types as fundamental types.
612 case Type::Builtin:
613 case Type::Vector:
614 case Type::ExtVector:
615 case Type::Complex:
616 case Type::BlockPointer:
617 // Itanium C++ ABI 2.9.5p4:
618 // abi::__fundamental_type_info adds no data members to std::type_info.
619 break;
620
621 case Type::LValueReference:
622 case Type::RValueReference:
623 llvm_unreachable("References shouldn't get here");
624
Richard Smithdc7a4f52013-04-30 13:56:41 +0000625 case Type::Auto:
626 llvm_unreachable("Undeduced auto type shouldn't get here");
627
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000628 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.
633 break;
634
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.
639 break;
640
641 case Type::Enum:
642 // Itanium C++ ABI 2.9.5p5:
643 // abi::__enum_type_info adds no data members to std::type_info.
644 break;
645
646 case Type::Record: {
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.
651 break;
652 }
653
654 if (CanUseSingleInheritance(RD))
655 BuildSIClassTypeInfo(RD);
656 else
657 BuildVMIClassTypeInfo(RD);
658
659 break;
660 }
661
662 case Type::ObjCObject:
663 case Type::ObjCInterface:
664 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
665 break;
666
667 case Type::ObjCObjectPointer:
668 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
669 break;
670
671 case Type::Pointer:
672 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
673 break;
674
675 case Type::MemberPointer:
676 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
677 break;
678
679 case Type::Atomic:
680 // No fields, at least for the moment.
681 break;
682 }
683
684 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
685
686 llvm::GlobalVariable *GV =
687 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
688 /*Constant=*/true, Linkage, Init, Name);
689
690 // If there's already an old global variable, replace it with the new one.
691 if (OldGV) {
692 GV->takeName(OldGV);
693 llvm::Constant *NewPtr =
694 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
695 OldGV->replaceAllUsesWith(NewPtr);
696 OldGV->eraseFromParent();
697 }
698
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
702 // compatibility.
703 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
704 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
705
706 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
707 CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
708 } else {
709 Visibility TypeInfoVisibility = DefaultVisibility;
710 if (CGM.getCodeGenOpts().HiddenWeakVTables &&
711 Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
712 TypeInfoVisibility = HiddenVisibility;
713
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));
718
719 TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
720 GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
721 }
722
723 GV->setUnnamedAddr(true);
724
725 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
726}
727
728/// ComputeQualifierFlags - Compute the pointer type info flags from the
729/// given qualifier.
730static unsigned ComputeQualifierFlags(Qualifiers Quals) {
731 unsigned Flags = 0;
732
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;
739
740 return Flags;
741}
742
743/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
744/// for the given Objective-C object type.
745void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
746 // Drop qualifiers.
747 const Type *T = OT->getBaseType().getTypePtr();
748 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
749
750 // The builtin types are abi::__class_type_infos and don't require
751 // extra fields.
752 if (isa<BuiltinType>(T)) return;
753
754 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
755 ObjCInterfaceDecl *Super = Class->getSuperClass();
756
757 // Root classes are also __class_type_info.
758 if (!Super) return;
759
760 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
761
762 // Everything else is single inheritance.
763 llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
764 Fields.push_back(BaseTypeInfo);
765}
766
767/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
768/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
769void 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);
776}
777
778namespace {
779 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
780 /// a class hierarchy.
781 struct SeenBases {
782 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
783 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
784 };
785}
786
787/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
788/// abi::__vmi_class_type_info.
789///
790static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
791 SeenBases &Bases) {
792
793 unsigned Flags = 0;
794
795 const CXXRecordDecl *BaseDecl =
796 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
797
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
802 // shaped.
803 Flags |= RTTIBuilder::VMI_DiamondShaped;
804 } else {
805 if (Bases.NonVirtualBases.count(BaseDecl))
806 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
807 }
808 } else {
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;
814 } else {
815 if (Bases.VirtualBases.count(BaseDecl))
816 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
817 }
818 }
819
820 // Walk all bases.
821 for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
822 E = BaseDecl->bases_end(); I != E; ++I)
823 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
824
825 return Flags;
826}
827
828static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
829 unsigned Flags = 0;
830 SeenBases Bases;
831
832 // Walk all bases.
833 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
834 E = RD->bases_end(); I != E; ++I)
835 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
836
837 return Flags;
838}
839
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.
843void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
844 llvm::Type *UnsignedIntLTy =
845 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
846
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));
853
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()));
858
859 if (!RD->getNumBases())
860 return;
861
862 llvm::Type *LongLTy =
863 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
864
865 // Now add the base class descriptions.
866
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:
870 //
871 // struct abi::__base_class_type_info {
872 // public:
873 // const __class_type_info *__base_type;
874 // long __offset_flags;
875 //
876 // enum __offset_flags_masks {
877 // __virtual_mask = 0x1,
878 // __public_mask = 0x2,
879 // __offset_shift = 8
880 // };
881 // };
882 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
883 E = RD->bases_end(); I != E; ++I) {
884 const CXXBaseSpecifier *Base = I;
885
886 // The __base_type member points to the RTTI for the base type.
887 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
888
889 const CXXRecordDecl *BaseDecl =
890 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
891
892 int64_t OffsetFlags = 0;
893
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).
898 CharUnits Offset;
899 if (Base->isVirtual())
900 Offset =
901 CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
902 else {
903 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
904 Offset = Layout.getBaseClassOffset(BaseDecl);
905 };
906
907 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
908
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;
915
916 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
917 }
918}
919
920/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
921/// used for pointer types.
922void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
923 Qualifiers Quals;
924 QualType UnqualifiedPointeeTy =
925 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
926
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);
931
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;
937
938 llvm::Type *UnsignedIntLTy =
939 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
940 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
941
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);
948}
949
950/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
951/// struct, used for member pointer types.
952void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
953 QualType PointeeTy = Ty->getPointeeType();
954
955 Qualifiers Quals;
956 QualType UnqualifiedPointeeTy =
957 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
958
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);
963
964 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
965
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;
971
972 if (IsIncompleteClassType(ClassType))
973 Flags |= PTI_ContainingClassIncomplete;
974
975 llvm::Type *UnsignedIntLTy =
976 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
977 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
978
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);
985
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)));
991}
992
993llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
994 bool ForEH) {
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);
1000
1001 if (ForEH && Ty->isObjCObjectPointerType() &&
1002 LangOpts.ObjCRuntime.isGNUFamily())
1003 return ObjCRuntime->GetEHType(Ty);
1004
1005 return RTTIBuilder(*this).BuildTypeInfo(Ty);
1006}
1007
1008void 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);
1014}
1015
1016void 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]);
1029}