blob: c33f088f3c84f13bd8a27f96dc218e7d2348fe1c [file] [log] [blame]
Guy Benyei11169dd2012-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 Benyeid8a08ea2012-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 Benyei61054192013-02-07 10:55:47 +0000200 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000201 case BuiltinType::OCLEvent:
Guy Benyei11169dd2012-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 McCall6bd2a892013-01-25 22:31:03 +0000255static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
256 QualType Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000257 ASTContext &Context = CGM.getContext();
258
John McCall6bd2a892013-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 Benyei11169dd2012-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 McCall6bd2a892013-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 Benyei11169dd2012-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
John McCalle54d92b2014-03-10 22:27:33 +0000339 case VisibleNoLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +0000340 case ExternalLinkage:
341 if (!CGM.getLangOpts().RTTI) {
342 // RTTI is not enabled, which means that this type info struct is going
343 // to be used for exception handling. Give it linkonce_odr linkage.
344 return llvm::GlobalValue::LinkOnceODRLinkage;
345 }
346
347 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
348 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
349 if (RD->hasAttr<WeakAttr>())
350 return llvm::GlobalValue::WeakODRLinkage;
351 if (RD->isDynamicClass())
352 return CGM.getVTableLinkage(RD);
353 }
354
355 return llvm::GlobalValue::LinkOnceODRLinkage;
356 }
357
358 llvm_unreachable("Invalid linkage!");
359}
360
361// CanUseSingleInheritance - Return whether the given record decl has a "single,
362// public, non-virtual base at offset zero (i.e. the derived class is dynamic
363// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
364static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
365 // Check the number of bases.
366 if (RD->getNumBases() != 1)
367 return false;
368
369 // Get the base.
370 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
371
372 // Check that the base is not virtual.
373 if (Base->isVirtual())
374 return false;
375
376 // Check that the base is public.
377 if (Base->getAccessSpecifier() != AS_public)
378 return false;
379
380 // Check that the class is dynamic iff the base is.
381 const CXXRecordDecl *BaseDecl =
382 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
383 if (!BaseDecl->isEmpty() &&
384 BaseDecl->isDynamicClass() != RD->isDynamicClass())
385 return false;
386
387 return true;
388}
389
390void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
391 // abi::__class_type_info.
392 static const char * const ClassTypeInfo =
393 "_ZTVN10__cxxabiv117__class_type_infoE";
394 // abi::__si_class_type_info.
395 static const char * const SIClassTypeInfo =
396 "_ZTVN10__cxxabiv120__si_class_type_infoE";
397 // abi::__vmi_class_type_info.
398 static const char * const VMIClassTypeInfo =
399 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
400
401 const char *VTableName = 0;
402
403 switch (Ty->getTypeClass()) {
404#define TYPE(Class, Base)
405#define ABSTRACT_TYPE(Class, Base)
406#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
407#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
408#define DEPENDENT_TYPE(Class, Base) case Type::Class:
409#include "clang/AST/TypeNodes.def"
410 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
411
412 case Type::LValueReference:
413 case Type::RValueReference:
414 llvm_unreachable("References shouldn't get here");
415
Richard Smith27d807c2013-04-30 13:56:41 +0000416 case Type::Auto:
417 llvm_unreachable("Undeduced auto type shouldn't get here");
418
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 case Type::Builtin:
420 // GCC treats vector and complex types as fundamental types.
421 case Type::Vector:
422 case Type::ExtVector:
423 case Type::Complex:
424 case Type::Atomic:
425 // FIXME: GCC treats block pointers as fundamental types?!
426 case Type::BlockPointer:
427 // abi::__fundamental_type_info.
428 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
429 break;
430
431 case Type::ConstantArray:
432 case Type::IncompleteArray:
433 case Type::VariableArray:
434 // abi::__array_type_info.
435 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
436 break;
437
438 case Type::FunctionNoProto:
439 case Type::FunctionProto:
440 // abi::__function_type_info.
441 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
442 break;
443
444 case Type::Enum:
445 // abi::__enum_type_info.
446 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
447 break;
448
449 case Type::Record: {
450 const CXXRecordDecl *RD =
451 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
452
453 if (!RD->hasDefinition() || !RD->getNumBases()) {
454 VTableName = ClassTypeInfo;
455 } else if (CanUseSingleInheritance(RD)) {
456 VTableName = SIClassTypeInfo;
457 } else {
458 VTableName = VMIClassTypeInfo;
459 }
460
461 break;
462 }
463
464 case Type::ObjCObject:
465 // Ignore protocol qualifiers.
466 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
467
468 // Handle id and Class.
469 if (isa<BuiltinType>(Ty)) {
470 VTableName = ClassTypeInfo;
471 break;
472 }
473
474 assert(isa<ObjCInterfaceType>(Ty));
475 // Fall through.
476
477 case Type::ObjCInterface:
478 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
479 VTableName = SIClassTypeInfo;
480 } else {
481 VTableName = ClassTypeInfo;
482 }
483 break;
484
485 case Type::ObjCObjectPointer:
486 case Type::Pointer:
487 // abi::__pointer_type_info.
488 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
489 break;
490
491 case Type::MemberPointer:
492 // abi::__pointer_to_member_type_info.
493 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
494 break;
495 }
496
497 llvm::Constant *VTable =
498 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
499
500 llvm::Type *PtrDiffTy =
501 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
502
503 // The vtable address point is 2.
504 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
505 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
506 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
507
508 Fields.push_back(VTable);
509}
510
Tim Northover618ca292014-03-29 15:09:55 +0000511/// What sort of unique-RTTI behavior should we use?
512enum UniqueRTTIKind {
513 /// We are guaranteeing, or need to guarantee, that the RTTI string
514 /// is unique.
515 UniqueRTTI,
516
517 /// We are not guaranteeing uniqueness for the RTTI string, so we
518 /// can demote to hidden visibility and use string comparisons.
519 NonUniqueHiddenRTTI,
520
521 /// We are not guaranteeing uniqueness for the RTTI string, so we
522 /// have to use string comparisons, but we also have to emit it with
523 /// non-hidden visibility.
524 NonUniqueVisibleRTTI
525};
526
527/// What sort of uniqueness rules should we use for the RTTI for the
528/// given type?
529static UniqueRTTIKind
530classifyUniqueRTTI(CodeGenModule &CGM, QualType canTy,
531 llvm::GlobalValue::LinkageTypes linkage) {
532 // We only support non-unique RTTI on iOS64.
533 // FIXME: abstract this into CGCXXABI after this code moves to trunk.
534 if (CGM.getTarget().getCXXABI().getKind() != TargetCXXABI::iOS64)
535 return UniqueRTTI;
536
537 // It's only necessary for linkonce_odr or weak_odr linkage.
538 if (linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
539 linkage != llvm::GlobalValue::WeakODRLinkage)
540 return UniqueRTTI;
541
542 // It's only necessary with default visibility.
543 if (canTy->getVisibility() != DefaultVisibility)
544 return UniqueRTTI;
545
546 // If we're not required to publish this symbol, hide it.
547 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage)
548 return NonUniqueHiddenRTTI;
549
550 // If we're required to publish this symbol, as we might be under an
551 // explicit instantiation, leave it with default visibility but
552 // enable string-comparisons.
553 assert(linkage == llvm::GlobalValue::WeakODRLinkage);
554 return NonUniqueVisibleRTTI;
555}
556
Guy Benyei11169dd2012-12-18 14:30:41 +0000557llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
558 // We want to operate on the canonical type.
559 Ty = CGM.getContext().getCanonicalType(Ty);
560
561 // Check if we've already emitted an RTTI descriptor for this type.
562 SmallString<256> OutName;
563 llvm::raw_svector_ostream Out(OutName);
564 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
565 Out.flush();
566 StringRef Name = OutName.str();
567
568 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
569 if (OldGV && !OldGV->isDeclaration()) {
Eli Friedmanba2778f2013-06-28 22:13:27 +0000570 assert(!OldGV->hasAvailableExternallyLinkage() &&
571 "available_externally typeinfos not yet implemented");
Guy Benyei11169dd2012-12-18 14:30:41 +0000572
573 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
574 }
575
576 // Check if there is already an external RTTI descriptor for this type.
577 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
578 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
579 return GetAddrOfExternalRTTIDescriptor(Ty);
580
581 // Emit the standard library with external linkage.
582 llvm::GlobalVariable::LinkageTypes Linkage;
583 if (IsStdLib)
584 Linkage = llvm::GlobalValue::ExternalLinkage;
585 else
586 Linkage = getTypeInfoLinkage(CGM, Ty);
587
588 // Add the vtable pointer.
589 BuildVTablePointer(cast<Type>(Ty));
590
591 // And the name.
592 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
Tim Northover618ca292014-03-29 15:09:55 +0000593 llvm::Constant *typeNameField;
Guy Benyei11169dd2012-12-18 14:30:41 +0000594
Tim Northover618ca292014-03-29 15:09:55 +0000595 // If we're supposed to demote the visibility, be sure to set a flag
596 // to use a string comparison for type_info comparisons.
597 UniqueRTTIKind uniqueRTTI = classifyUniqueRTTI(CGM, Ty, Linkage);
598 if (uniqueRTTI != UniqueRTTI) {
599 // The flag is the sign bit, which on ARM64 is defined to be clear
600 // for global pointers. This is very ARM64-specific.
601 typeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
602 llvm::Constant *flag =
603 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
604 typeNameField = llvm::ConstantExpr::getAdd(typeNameField, flag);
605 typeNameField =
606 llvm::ConstantExpr::getIntToPtr(typeNameField, CGM.Int8PtrTy);
607 } else {
608 typeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
609 }
610 Fields.push_back(typeNameField);
Guy Benyei11169dd2012-12-18 14:30:41 +0000611
612 switch (Ty->getTypeClass()) {
613#define TYPE(Class, Base)
614#define ABSTRACT_TYPE(Class, Base)
615#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
616#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
617#define DEPENDENT_TYPE(Class, Base) case Type::Class:
618#include "clang/AST/TypeNodes.def"
619 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
620
621 // GCC treats vector types as fundamental types.
622 case Type::Builtin:
623 case Type::Vector:
624 case Type::ExtVector:
625 case Type::Complex:
626 case Type::BlockPointer:
627 // Itanium C++ ABI 2.9.5p4:
628 // abi::__fundamental_type_info adds no data members to std::type_info.
629 break;
630
631 case Type::LValueReference:
632 case Type::RValueReference:
633 llvm_unreachable("References shouldn't get here");
634
Richard Smith27d807c2013-04-30 13:56:41 +0000635 case Type::Auto:
636 llvm_unreachable("Undeduced auto type shouldn't get here");
637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 case Type::ConstantArray:
639 case Type::IncompleteArray:
640 case Type::VariableArray:
641 // Itanium C++ ABI 2.9.5p5:
642 // abi::__array_type_info adds no data members to std::type_info.
643 break;
644
645 case Type::FunctionNoProto:
646 case Type::FunctionProto:
647 // Itanium C++ ABI 2.9.5p5:
648 // abi::__function_type_info adds no data members to std::type_info.
649 break;
650
651 case Type::Enum:
652 // Itanium C++ ABI 2.9.5p5:
653 // abi::__enum_type_info adds no data members to std::type_info.
654 break;
655
656 case Type::Record: {
657 const CXXRecordDecl *RD =
658 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
659 if (!RD->hasDefinition() || !RD->getNumBases()) {
660 // We don't need to emit any fields.
661 break;
662 }
663
664 if (CanUseSingleInheritance(RD))
665 BuildSIClassTypeInfo(RD);
666 else
667 BuildVMIClassTypeInfo(RD);
668
669 break;
670 }
671
672 case Type::ObjCObject:
673 case Type::ObjCInterface:
674 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
675 break;
676
677 case Type::ObjCObjectPointer:
678 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
679 break;
680
681 case Type::Pointer:
682 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
683 break;
684
685 case Type::MemberPointer:
686 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
687 break;
688
689 case Type::Atomic:
690 // No fields, at least for the moment.
691 break;
692 }
693
694 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
695
696 llvm::GlobalVariable *GV =
697 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
698 /*Constant=*/true, Linkage, Init, Name);
699
700 // If there's already an old global variable, replace it with the new one.
701 if (OldGV) {
702 GV->takeName(OldGV);
703 llvm::Constant *NewPtr =
704 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
705 OldGV->replaceAllUsesWith(NewPtr);
706 OldGV->eraseFromParent();
707 }
708
John McCall57420b32014-02-08 03:26:05 +0000709 // The Itanium ABI specifies that type_info objects must be globally
710 // unique, with one exception: if the type is an incomplete class
711 // type or a (possibly indirect) pointer to one. That exception
712 // affects the general case of comparing type_info objects produced
713 // by the typeid operator, which is why the comparison operators on
714 // std::type_info generally use the type_info name pointers instead
715 // of the object addresses. However, the language's built-in uses
716 // of RTTI generally require class types to be complete, even when
717 // manipulating pointers to those class types. This allows the
718 // implementation of dynamic_cast to rely on address equality tests,
719 // which is much faster.
720
721 // All of this is to say that it's important that both the type_info
722 // object and the type_info name be uniqued when weakly emitted.
723
John McCall8f80a612014-02-08 00:41:16 +0000724 // Give the type_info object and name the formal visibility of the
725 // type itself.
726 Visibility formalVisibility = Ty->getVisibility();
727 llvm::GlobalValue::VisibilityTypes llvmVisibility =
728 CodeGenModule::GetLLVMVisibility(formalVisibility);
729 TypeName->setVisibility(llvmVisibility);
730 GV->setVisibility(llvmVisibility);
Guy Benyei11169dd2012-12-18 14:30:41 +0000731
Tim Northover618ca292014-03-29 15:09:55 +0000732 // FIXME: integrate this better into the above when we move to trunk
733 if (uniqueRTTI == NonUniqueHiddenRTTI) {
734 TypeName->setVisibility(llvm::GlobalValue::HiddenVisibility);
735 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
736 }
737
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
739}
740
741/// ComputeQualifierFlags - Compute the pointer type info flags from the
742/// given qualifier.
743static unsigned ComputeQualifierFlags(Qualifiers Quals) {
744 unsigned Flags = 0;
745
746 if (Quals.hasConst())
747 Flags |= RTTIBuilder::PTI_Const;
748 if (Quals.hasVolatile())
749 Flags |= RTTIBuilder::PTI_Volatile;
750 if (Quals.hasRestrict())
751 Flags |= RTTIBuilder::PTI_Restrict;
752
753 return Flags;
754}
755
756/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
757/// for the given Objective-C object type.
758void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
759 // Drop qualifiers.
760 const Type *T = OT->getBaseType().getTypePtr();
761 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
762
763 // The builtin types are abi::__class_type_infos and don't require
764 // extra fields.
765 if (isa<BuiltinType>(T)) return;
766
767 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
768 ObjCInterfaceDecl *Super = Class->getSuperClass();
769
770 // Root classes are also __class_type_info.
771 if (!Super) return;
772
773 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
774
775 // Everything else is single inheritance.
776 llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
777 Fields.push_back(BaseTypeInfo);
778}
779
780/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
781/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
782void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
783 // Itanium C++ ABI 2.9.5p6b:
784 // It adds to abi::__class_type_info a single member pointing to the
785 // type_info structure for the base type,
786 llvm::Constant *BaseTypeInfo =
787 RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
788 Fields.push_back(BaseTypeInfo);
789}
790
791namespace {
792 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
793 /// a class hierarchy.
794 struct SeenBases {
795 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
796 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
797 };
798}
799
800/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
801/// abi::__vmi_class_type_info.
802///
803static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
804 SeenBases &Bases) {
805
806 unsigned Flags = 0;
807
808 const CXXRecordDecl *BaseDecl =
809 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
810
811 if (Base->isVirtual()) {
812 // Mark the virtual base as seen.
813 if (!Bases.VirtualBases.insert(BaseDecl)) {
814 // If this virtual base has been seen before, then the class is diamond
815 // shaped.
816 Flags |= RTTIBuilder::VMI_DiamondShaped;
817 } else {
818 if (Bases.NonVirtualBases.count(BaseDecl))
819 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
820 }
821 } else {
822 // Mark the non-virtual base as seen.
823 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
824 // If this non-virtual base has been seen before, then the class has non-
825 // diamond shaped repeated inheritance.
826 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
827 } else {
828 if (Bases.VirtualBases.count(BaseDecl))
829 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
830 }
831 }
832
833 // Walk all bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000834 for (const auto &I : BaseDecl->bases())
835 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
Guy Benyei11169dd2012-12-18 14:30:41 +0000836
837 return Flags;
838}
839
840static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
841 unsigned Flags = 0;
842 SeenBases Bases;
843
844 // Walk all bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000845 for (const auto &I : RD->bases())
846 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
Guy Benyei11169dd2012-12-18 14:30:41 +0000847
848 return Flags;
849}
850
851/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
852/// classes with bases that do not satisfy the abi::__si_class_type_info
853/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
854void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
855 llvm::Type *UnsignedIntLTy =
856 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
857
858 // Itanium C++ ABI 2.9.5p6c:
859 // __flags is a word with flags describing details about the class
860 // structure, which may be referenced by using the __flags_masks
861 // enumeration. These flags refer to both direct and indirect bases.
862 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
863 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
864
865 // Itanium C++ ABI 2.9.5p6c:
866 // __base_count is a word with the number of direct proper base class
867 // descriptions that follow.
868 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
869
870 if (!RD->getNumBases())
871 return;
872
873 llvm::Type *LongLTy =
874 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
875
876 // Now add the base class descriptions.
877
878 // Itanium C++ ABI 2.9.5p6c:
879 // __base_info[] is an array of base class descriptions -- one for every
880 // direct proper base. Each description is of the type:
881 //
882 // struct abi::__base_class_type_info {
883 // public:
884 // const __class_type_info *__base_type;
885 // long __offset_flags;
886 //
887 // enum __offset_flags_masks {
888 // __virtual_mask = 0x1,
889 // __public_mask = 0x2,
890 // __offset_shift = 8
891 // };
892 // };
Aaron Ballman574705e2014-03-13 15:41:46 +0000893 for (const auto &Base : RD->bases()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000894 // The __base_type member points to the RTTI for the base type.
Aaron Ballman574705e2014-03-13 15:41:46 +0000895 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base.getType()));
Guy Benyei11169dd2012-12-18 14:30:41 +0000896
897 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000898 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000899
900 int64_t OffsetFlags = 0;
901
902 // All but the lower 8 bits of __offset_flags are a signed offset.
903 // For a non-virtual base, this is the offset in the object of the base
904 // subobject. For a virtual base, this is the offset in the virtual table of
905 // the virtual base offset for the virtual base referenced (negative).
906 CharUnits Offset;
Aaron Ballman574705e2014-03-13 15:41:46 +0000907 if (Base.isVirtual())
Guy Benyei11169dd2012-12-18 14:30:41 +0000908 Offset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000909 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000910 else {
911 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
912 Offset = Layout.getBaseClassOffset(BaseDecl);
913 };
914
915 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
916
917 // The low-order byte of __offset_flags contains flags, as given by the
918 // masks from the enumeration __offset_flags_masks.
Aaron Ballman574705e2014-03-13 15:41:46 +0000919 if (Base.isVirtual())
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 OffsetFlags |= BCTI_Virtual;
Aaron Ballman574705e2014-03-13 15:41:46 +0000921 if (Base.getAccessSpecifier() == AS_public)
Guy Benyei11169dd2012-12-18 14:30:41 +0000922 OffsetFlags |= BCTI_Public;
923
924 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
925 }
926}
927
928/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
929/// used for pointer types.
930void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
931 Qualifiers Quals;
932 QualType UnqualifiedPointeeTy =
933 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
934
935 // Itanium C++ ABI 2.9.5p7:
936 // __flags is a flag word describing the cv-qualification and other
937 // attributes of the type pointed to
938 unsigned Flags = ComputeQualifierFlags(Quals);
939
940 // Itanium C++ ABI 2.9.5p7:
941 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
942 // incomplete class type, the incomplete target type flag is set.
943 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
944 Flags |= PTI_Incomplete;
945
946 llvm::Type *UnsignedIntLTy =
947 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
948 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
949
950 // Itanium C++ ABI 2.9.5p7:
951 // __pointee is a pointer to the std::type_info derivation for the
952 // unqualified type being pointed to.
953 llvm::Constant *PointeeTypeInfo =
954 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
955 Fields.push_back(PointeeTypeInfo);
956}
957
958/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
959/// struct, used for member pointer types.
960void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
961 QualType PointeeTy = Ty->getPointeeType();
962
963 Qualifiers Quals;
964 QualType UnqualifiedPointeeTy =
965 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
966
967 // Itanium C++ ABI 2.9.5p7:
968 // __flags is a flag word describing the cv-qualification and other
969 // attributes of the type pointed to.
970 unsigned Flags = ComputeQualifierFlags(Quals);
971
972 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
973
974 // Itanium C++ ABI 2.9.5p7:
975 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
976 // incomplete class type, the incomplete target type flag is set.
977 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
978 Flags |= PTI_Incomplete;
979
980 if (IsIncompleteClassType(ClassType))
981 Flags |= PTI_ContainingClassIncomplete;
982
983 llvm::Type *UnsignedIntLTy =
984 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
985 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
986
987 // Itanium C++ ABI 2.9.5p7:
988 // __pointee is a pointer to the std::type_info derivation for the
989 // unqualified type being pointed to.
990 llvm::Constant *PointeeTypeInfo =
991 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
992 Fields.push_back(PointeeTypeInfo);
993
994 // Itanium C++ ABI 2.9.5p9:
995 // __context is a pointer to an abi::__class_type_info corresponding to the
996 // class type containing the member pointed to
997 // (e.g., the "A" in "int A::*").
998 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
999}
1000
1001llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
1002 bool ForEH) {
1003 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
1004 // FIXME: should we even be calling this method if RTTI is disabled
1005 // and it's not for EH?
1006 if (!ForEH && !getLangOpts().RTTI)
1007 return llvm::Constant::getNullValue(Int8PtrTy);
1008
1009 if (ForEH && Ty->isObjCObjectPointerType() &&
1010 LangOpts.ObjCRuntime.isGNUFamily())
1011 return ObjCRuntime->GetEHType(Ty);
1012
1013 return RTTIBuilder(*this).BuildTypeInfo(Ty);
1014}
1015
1016void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
1017 QualType PointerType = Context.getPointerType(Type);
1018 QualType PointerTypeConst = Context.getPointerType(Type.withConst());
1019 RTTIBuilder(*this).BuildTypeInfo(Type, true);
1020 RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
1021 RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
1022}
1023
1024void CodeGenModule::EmitFundamentalRTTIDescriptors() {
1025 QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
1026 Context.BoolTy, Context.WCharTy,
1027 Context.CharTy, Context.UnsignedCharTy,
1028 Context.SignedCharTy, Context.ShortTy,
1029 Context.UnsignedShortTy, Context.IntTy,
1030 Context.UnsignedIntTy, Context.LongTy,
1031 Context.UnsignedLongTy, Context.LongLongTy,
1032 Context.UnsignedLongLongTy, Context.FloatTy,
1033 Context.DoubleTy, Context.LongDoubleTy,
1034 Context.Char16Ty, Context.Char32Ty };
Craig Toppere5ce8312013-07-15 03:38:40 +00001035 for (unsigned i = 0; i < llvm::array_lengthof(FundamentalTypes); ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00001036 EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);
1037}