Home | History | Annotate | Download | only in CodeGen
      1 //===--- 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 "clang/AST/RecordLayout.h"
     17 #include "clang/AST/Type.h"
     18 #include "clang/Frontend/CodeGenOptions.h"
     19 #include "CGObjCRuntime.h"
     20 
     21 using namespace clang;
     22 using namespace CodeGen;
     23 
     24 namespace {
     25 class RTTIBuilder {
     26   CodeGenModule &CGM;  // Per-module state.
     27   llvm::LLVMContext &VMContext;
     28 
     29   llvm::Type *Int8PtrTy;
     30 
     31   /// Fields - The fields of the RTTI descriptor currently being built.
     32   SmallVector<llvm::Constant *, 16> Fields;
     33 
     34   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
     35   llvm::GlobalVariable *
     36   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
     37 
     38   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
     39   /// descriptor of the given type.
     40   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
     41 
     42   /// BuildVTablePointer - Build the vtable pointer for the given type.
     43   void BuildVTablePointer(const Type *Ty);
     44 
     45   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
     46   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
     47   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
     48 
     49   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
     50   /// classes with bases that do not satisfy the abi::__si_class_type_info
     51   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
     52   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
     53 
     54   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
     55   /// for pointer types.
     56   void BuildPointerTypeInfo(QualType PointeeTy);
     57 
     58   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
     59   /// type_info for an object type.
     60   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
     61 
     62   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
     63   /// struct, used for member pointer types.
     64   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
     65 
     66 public:
     67   RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),
     68     VMContext(CGM.getModule().getContext()),
     69     Int8PtrTy(llvm::Type::getInt8PtrTy(VMContext)) { }
     70 
     71   // Pointer type info flags.
     72   enum {
     73     /// PTI_Const - Type has const qualifier.
     74     PTI_Const = 0x1,
     75 
     76     /// PTI_Volatile - Type has volatile qualifier.
     77     PTI_Volatile = 0x2,
     78 
     79     /// PTI_Restrict - Type has restrict qualifier.
     80     PTI_Restrict = 0x4,
     81 
     82     /// PTI_Incomplete - Type is incomplete.
     83     PTI_Incomplete = 0x8,
     84 
     85     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
     86     /// (in pointer to member).
     87     PTI_ContainingClassIncomplete = 0x10
     88   };
     89 
     90   // VMI type info flags.
     91   enum {
     92     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
     93     VMI_NonDiamondRepeat = 0x1,
     94 
     95     /// VMI_DiamondShaped - Class is diamond shaped.
     96     VMI_DiamondShaped = 0x2
     97   };
     98 
     99   // Base class type info flags.
    100   enum {
    101     /// BCTI_Virtual - Base class is virtual.
    102     BCTI_Virtual = 0x1,
    103 
    104     /// BCTI_Public - Base class is public.
    105     BCTI_Public = 0x2
    106   };
    107 
    108   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
    109   ///
    110   /// \param Force - true to force the creation of this RTTI value
    111   /// \param ForEH - true if this is for exception handling
    112   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
    113 };
    114 }
    115 
    116 llvm::GlobalVariable *
    117 RTTIBuilder::GetAddrOfTypeName(QualType Ty,
    118                                llvm::GlobalVariable::LinkageTypes Linkage) {
    119   llvm::SmallString<256> OutName;
    120   llvm::raw_svector_ostream Out(OutName);
    121   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
    122   Out.flush();
    123   StringRef Name = OutName.str();
    124 
    125   // We know that the mangled name of the type starts at index 4 of the
    126   // mangled name of the typename, so we can just index into it in order to
    127   // get the mangled name of the type.
    128   llvm::Constant *Init = llvm::ConstantArray::get(VMContext, Name.substr(4));
    129 
    130   llvm::GlobalVariable *GV =
    131     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
    132 
    133   GV->setInitializer(Init);
    134 
    135   return GV;
    136 }
    137 
    138 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
    139   // Mangle the RTTI name.
    140   llvm::SmallString<256> OutName;
    141   llvm::raw_svector_ostream Out(OutName);
    142   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
    143   Out.flush();
    144   StringRef Name = OutName.str();
    145 
    146   // Look for an existing global.
    147   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
    148 
    149   if (!GV) {
    150     // Create a new global variable.
    151     GV = new llvm::GlobalVariable(CGM.getModule(), Int8PtrTy, /*Constant=*/true,
    152                                   llvm::GlobalValue::ExternalLinkage, 0, Name);
    153   }
    154 
    155   return llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
    156 }
    157 
    158 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
    159 /// info for that type is defined in the standard library.
    160 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
    161   // Itanium C++ ABI 2.9.2:
    162   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
    163   //   the run-time support library. Specifically, the run-time support
    164   //   library should contain type_info objects for the types X, X* and
    165   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
    166   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
    167   //   long, unsigned long, long long, unsigned long long, float, double,
    168   //   long double, char16_t, char32_t, and the IEEE 754r decimal and
    169   //   half-precision floating point types.
    170   switch (Ty->getKind()) {
    171     case BuiltinType::Void:
    172     case BuiltinType::NullPtr:
    173     case BuiltinType::Bool:
    174     case BuiltinType::WChar_S:
    175     case BuiltinType::WChar_U:
    176     case BuiltinType::Char_U:
    177     case BuiltinType::Char_S:
    178     case BuiltinType::UChar:
    179     case BuiltinType::SChar:
    180     case BuiltinType::Short:
    181     case BuiltinType::UShort:
    182     case BuiltinType::Int:
    183     case BuiltinType::UInt:
    184     case BuiltinType::Long:
    185     case BuiltinType::ULong:
    186     case BuiltinType::LongLong:
    187     case BuiltinType::ULongLong:
    188     case BuiltinType::Half:
    189     case BuiltinType::Float:
    190     case BuiltinType::Double:
    191     case BuiltinType::LongDouble:
    192     case BuiltinType::Char16:
    193     case BuiltinType::Char32:
    194     case BuiltinType::Int128:
    195     case BuiltinType::UInt128:
    196       return true;
    197 
    198     case BuiltinType::Dependent:
    199 #define BUILTIN_TYPE(Id, SingletonId)
    200 #define PLACEHOLDER_TYPE(Id, SingletonId) \
    201     case BuiltinType::Id:
    202 #include "clang/AST/BuiltinTypes.def"
    203       llvm_unreachable("asking for RRTI for a placeholder type!");
    204 
    205     case BuiltinType::ObjCId:
    206     case BuiltinType::ObjCClass:
    207     case BuiltinType::ObjCSel:
    208       llvm_unreachable("FIXME: Objective-C types are unsupported!");
    209   }
    210 
    211   // Silent gcc.
    212   return false;
    213 }
    214 
    215 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
    216   QualType PointeeTy = PointerTy->getPointeeType();
    217   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
    218   if (!BuiltinTy)
    219     return false;
    220 
    221   // Check the qualifiers.
    222   Qualifiers Quals = PointeeTy.getQualifiers();
    223   Quals.removeConst();
    224 
    225   if (!Quals.empty())
    226     return false;
    227 
    228   return TypeInfoIsInStandardLibrary(BuiltinTy);
    229 }
    230 
    231 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
    232 /// information for the given type exists in the standard library.
    233 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
    234   // Type info for builtin types is defined in the standard library.
    235   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
    236     return TypeInfoIsInStandardLibrary(BuiltinTy);
    237 
    238   // Type info for some pointer types to builtin types is defined in the
    239   // standard library.
    240   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
    241     return TypeInfoIsInStandardLibrary(PointerTy);
    242 
    243   return false;
    244 }
    245 
    246 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
    247 /// the given type exists somewhere else, and that we should not emit the type
    248 /// information in this translation unit.  Assumes that it is not a
    249 /// standard-library type.
    250 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty) {
    251   ASTContext &Context = CGM.getContext();
    252 
    253   // If RTTI is disabled, don't consider key functions.
    254   if (!Context.getLangOptions().RTTI) return false;
    255 
    256   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
    257     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
    258     if (!RD->hasDefinition())
    259       return false;
    260 
    261     if (!RD->isDynamicClass())
    262       return false;
    263 
    264     return !CGM.getVTables().ShouldEmitVTableInThisTU(RD);
    265   }
    266 
    267   return false;
    268 }
    269 
    270 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
    271 static bool IsIncompleteClassType(const RecordType *RecordTy) {
    272   return !RecordTy->getDecl()->isCompleteDefinition();
    273 }
    274 
    275 /// ContainsIncompleteClassType - Returns whether the given type contains an
    276 /// incomplete class type. This is true if
    277 ///
    278 ///   * The given type is an incomplete class type.
    279 ///   * The given type is a pointer type whose pointee type contains an
    280 ///     incomplete class type.
    281 ///   * The given type is a member pointer type whose class is an incomplete
    282 ///     class type.
    283 ///   * The given type is a member pointer type whoise pointee type contains an
    284 ///     incomplete class type.
    285 /// is an indirect or direct pointer to an incomplete class type.
    286 static bool ContainsIncompleteClassType(QualType Ty) {
    287   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
    288     if (IsIncompleteClassType(RecordTy))
    289       return true;
    290   }
    291 
    292   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
    293     return ContainsIncompleteClassType(PointerTy->getPointeeType());
    294 
    295   if (const MemberPointerType *MemberPointerTy =
    296       dyn_cast<MemberPointerType>(Ty)) {
    297     // Check if the class type is incomplete.
    298     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
    299     if (IsIncompleteClassType(ClassType))
    300       return true;
    301 
    302     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
    303   }
    304 
    305   return false;
    306 }
    307 
    308 /// getTypeInfoLinkage - Return the linkage that the type info and type info
    309 /// name constants should have for the given type.
    310 static llvm::GlobalVariable::LinkageTypes
    311 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
    312   // Itanium C++ ABI 2.9.5p7:
    313   //   In addition, it and all of the intermediate abi::__pointer_type_info
    314   //   structs in the chain down to the abi::__class_type_info for the
    315   //   incomplete class type must be prevented from resolving to the
    316   //   corresponding type_info structs for the complete class type, possibly
    317   //   by making them local static objects. Finally, a dummy class RTTI is
    318   //   generated for the incomplete type that will not resolve to the final
    319   //   complete class RTTI (because the latter need not exist), possibly by
    320   //   making it a local static object.
    321   if (ContainsIncompleteClassType(Ty))
    322     return llvm::GlobalValue::InternalLinkage;
    323 
    324   switch (Ty->getLinkage()) {
    325   case NoLinkage:
    326   case InternalLinkage:
    327   case UniqueExternalLinkage:
    328     return llvm::GlobalValue::InternalLinkage;
    329 
    330   case ExternalLinkage:
    331     if (!CGM.getLangOptions().RTTI) {
    332       // RTTI is not enabled, which means that this type info struct is going
    333       // to be used for exception handling. Give it linkonce_odr linkage.
    334       return llvm::GlobalValue::LinkOnceODRLinkage;
    335     }
    336 
    337     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
    338       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
    339       if (RD->isDynamicClass())
    340         return CGM.getVTableLinkage(RD);
    341     }
    342 
    343     return llvm::GlobalValue::LinkOnceODRLinkage;
    344   }
    345 
    346   return llvm::GlobalValue::LinkOnceODRLinkage;
    347 }
    348 
    349 // CanUseSingleInheritance - Return whether the given record decl has a "single,
    350 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
    351 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
    352 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
    353   // Check the number of bases.
    354   if (RD->getNumBases() != 1)
    355     return false;
    356 
    357   // Get the base.
    358   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
    359 
    360   // Check that the base is not virtual.
    361   if (Base->isVirtual())
    362     return false;
    363 
    364   // Check that the base is public.
    365   if (Base->getAccessSpecifier() != AS_public)
    366     return false;
    367 
    368   // Check that the class is dynamic iff the base is.
    369   const CXXRecordDecl *BaseDecl =
    370     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
    371   if (!BaseDecl->isEmpty() &&
    372       BaseDecl->isDynamicClass() != RD->isDynamicClass())
    373     return false;
    374 
    375   return true;
    376 }
    377 
    378 void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
    379   // abi::__class_type_info.
    380   static const char * const ClassTypeInfo =
    381     "_ZTVN10__cxxabiv117__class_type_infoE";
    382   // abi::__si_class_type_info.
    383   static const char * const SIClassTypeInfo =
    384     "_ZTVN10__cxxabiv120__si_class_type_infoE";
    385   // abi::__vmi_class_type_info.
    386   static const char * const VMIClassTypeInfo =
    387     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
    388 
    389   const char *VTableName = 0;
    390 
    391   switch (Ty->getTypeClass()) {
    392 #define TYPE(Class, Base)
    393 #define ABSTRACT_TYPE(Class, Base)
    394 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
    395 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
    396 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
    397 #include "clang/AST/TypeNodes.def"
    398     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
    399 
    400   case Type::LValueReference:
    401   case Type::RValueReference:
    402     llvm_unreachable("References shouldn't get here");
    403 
    404   case Type::Builtin:
    405   // GCC treats vector and complex types as fundamental types.
    406   case Type::Vector:
    407   case Type::ExtVector:
    408   case Type::Complex:
    409   case Type::Atomic:
    410   // FIXME: GCC treats block pointers as fundamental types?!
    411   case Type::BlockPointer:
    412     // abi::__fundamental_type_info.
    413     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
    414     break;
    415 
    416   case Type::ConstantArray:
    417   case Type::IncompleteArray:
    418   case Type::VariableArray:
    419     // abi::__array_type_info.
    420     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
    421     break;
    422 
    423   case Type::FunctionNoProto:
    424   case Type::FunctionProto:
    425     // abi::__function_type_info.
    426     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
    427     break;
    428 
    429   case Type::Enum:
    430     // abi::__enum_type_info.
    431     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
    432     break;
    433 
    434   case Type::Record: {
    435     const CXXRecordDecl *RD =
    436       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
    437 
    438     if (!RD->hasDefinition() || !RD->getNumBases()) {
    439       VTableName = ClassTypeInfo;
    440     } else if (CanUseSingleInheritance(RD)) {
    441       VTableName = SIClassTypeInfo;
    442     } else {
    443       VTableName = VMIClassTypeInfo;
    444     }
    445 
    446     break;
    447   }
    448 
    449   case Type::ObjCObject:
    450     // Ignore protocol qualifiers.
    451     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
    452 
    453     // Handle id and Class.
    454     if (isa<BuiltinType>(Ty)) {
    455       VTableName = ClassTypeInfo;
    456       break;
    457     }
    458 
    459     assert(isa<ObjCInterfaceType>(Ty));
    460     // Fall through.
    461 
    462   case Type::ObjCInterface:
    463     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
    464       VTableName = SIClassTypeInfo;
    465     } else {
    466       VTableName = ClassTypeInfo;
    467     }
    468     break;
    469 
    470   case Type::ObjCObjectPointer:
    471   case Type::Pointer:
    472     // abi::__pointer_type_info.
    473     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
    474     break;
    475 
    476   case Type::MemberPointer:
    477     // abi::__pointer_to_member_type_info.
    478     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
    479     break;
    480   }
    481 
    482   llvm::Constant *VTable =
    483     CGM.getModule().getOrInsertGlobal(VTableName, Int8PtrTy);
    484 
    485   llvm::Type *PtrDiffTy =
    486     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
    487 
    488   // The vtable address point is 2.
    489   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
    490   VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
    491   VTable = llvm::ConstantExpr::getBitCast(VTable, Int8PtrTy);
    492 
    493   Fields.push_back(VTable);
    494 }
    495 
    496 // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
    497 // from available_externally to the correct linkage if necessary. An example of
    498 // this is:
    499 //
    500 //   struct A {
    501 //     virtual void f();
    502 //   };
    503 //
    504 //   const std::type_info &g() {
    505 //     return typeid(A);
    506 //   }
    507 //
    508 //   void A::f() { }
    509 //
    510 // When we're generating the typeid(A) expression, we do not yet know that
    511 // A's key function is defined in this translation unit, so we will give the
    512 // typeinfo and typename structures available_externally linkage. When A::f
    513 // forces the vtable to be generated, we need to change the linkage of the
    514 // typeinfo and typename structs, otherwise we'll end up with undefined
    515 // externals when linking.
    516 static void
    517 maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
    518                        QualType Ty) {
    519   // We're only interested in globals with available_externally linkage.
    520   if (!GV->hasAvailableExternallyLinkage())
    521     return;
    522 
    523   // Get the real linkage for the type.
    524   llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
    525 
    526   // If variable is supposed to have available_externally linkage, we don't
    527   // need to do anything.
    528   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
    529     return;
    530 
    531   // Update the typeinfo linkage.
    532   GV->setLinkage(Linkage);
    533 
    534   // Get the typename global.
    535   llvm::SmallString<256> OutName;
    536   llvm::raw_svector_ostream Out(OutName);
    537   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
    538   Out.flush();
    539   StringRef Name = OutName.str();
    540 
    541   llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
    542 
    543   assert(TypeNameGV->hasAvailableExternallyLinkage() &&
    544          "Type name has different linkage from type info!");
    545 
    546   // And update its linkage.
    547   TypeNameGV->setLinkage(Linkage);
    548 }
    549 
    550 llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
    551   // We want to operate on the canonical type.
    552   Ty = CGM.getContext().getCanonicalType(Ty);
    553 
    554   // Check if we've already emitted an RTTI descriptor for this type.
    555   llvm::SmallString<256> OutName;
    556   llvm::raw_svector_ostream Out(OutName);
    557   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
    558   Out.flush();
    559   StringRef Name = OutName.str();
    560 
    561   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
    562   if (OldGV && !OldGV->isDeclaration()) {
    563     maybeUpdateRTTILinkage(CGM, OldGV, Ty);
    564 
    565     return llvm::ConstantExpr::getBitCast(OldGV, Int8PtrTy);
    566   }
    567 
    568   // Check if there is already an external RTTI descriptor for this type.
    569   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
    570   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
    571     return GetAddrOfExternalRTTIDescriptor(Ty);
    572 
    573   // Emit the standard library with external linkage.
    574   llvm::GlobalVariable::LinkageTypes Linkage;
    575   if (IsStdLib)
    576     Linkage = llvm::GlobalValue::ExternalLinkage;
    577   else
    578     Linkage = getTypeInfoLinkage(CGM, Ty);
    579 
    580   // Add the vtable pointer.
    581   BuildVTablePointer(cast<Type>(Ty));
    582 
    583   // And the name.
    584   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
    585 
    586   llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
    587   Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, Int8PtrTy));
    588 
    589   switch (Ty->getTypeClass()) {
    590 #define TYPE(Class, Base)
    591 #define ABSTRACT_TYPE(Class, Base)
    592 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
    593 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
    594 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
    595 #include "clang/AST/TypeNodes.def"
    596     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
    597 
    598   // GCC treats vector types as fundamental types.
    599   case Type::Builtin:
    600   case Type::Vector:
    601   case Type::ExtVector:
    602   case Type::Complex:
    603   case Type::BlockPointer:
    604     // Itanium C++ ABI 2.9.5p4:
    605     // abi::__fundamental_type_info adds no data members to std::type_info.
    606     break;
    607 
    608   case Type::LValueReference:
    609   case Type::RValueReference:
    610     llvm_unreachable("References shouldn't get here");
    611 
    612   case Type::ConstantArray:
    613   case Type::IncompleteArray:
    614   case Type::VariableArray:
    615     // Itanium C++ ABI 2.9.5p5:
    616     // abi::__array_type_info adds no data members to std::type_info.
    617     break;
    618 
    619   case Type::FunctionNoProto:
    620   case Type::FunctionProto:
    621     // Itanium C++ ABI 2.9.5p5:
    622     // abi::__function_type_info adds no data members to std::type_info.
    623     break;
    624 
    625   case Type::Enum:
    626     // Itanium C++ ABI 2.9.5p5:
    627     // abi::__enum_type_info adds no data members to std::type_info.
    628     break;
    629 
    630   case Type::Record: {
    631     const CXXRecordDecl *RD =
    632       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
    633     if (!RD->hasDefinition() || !RD->getNumBases()) {
    634       // We don't need to emit any fields.
    635       break;
    636     }
    637 
    638     if (CanUseSingleInheritance(RD))
    639       BuildSIClassTypeInfo(RD);
    640     else
    641       BuildVMIClassTypeInfo(RD);
    642 
    643     break;
    644   }
    645 
    646   case Type::ObjCObject:
    647   case Type::ObjCInterface:
    648     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
    649     break;
    650 
    651   case Type::ObjCObjectPointer:
    652     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
    653     break;
    654 
    655   case Type::Pointer:
    656     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
    657     break;
    658 
    659   case Type::MemberPointer:
    660     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
    661     break;
    662 
    663   case Type::Atomic:
    664     // No fields, at least for the moment.
    665     break;
    666   }
    667 
    668   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
    669 
    670   llvm::GlobalVariable *GV =
    671     new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
    672                              /*Constant=*/true, Linkage, Init, Name);
    673 
    674   // If there's already an old global variable, replace it with the new one.
    675   if (OldGV) {
    676     GV->takeName(OldGV);
    677     llvm::Constant *NewPtr =
    678       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
    679     OldGV->replaceAllUsesWith(NewPtr);
    680     OldGV->eraseFromParent();
    681   }
    682 
    683   // GCC only relies on the uniqueness of the type names, not the
    684   // type_infos themselves, so we can emit these as hidden symbols.
    685   // But don't do this if we're worried about strict visibility
    686   // compatibility.
    687   if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
    688     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
    689 
    690     CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
    691     CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
    692   } else {
    693     Visibility TypeInfoVisibility = DefaultVisibility;
    694     if (CGM.getCodeGenOpts().HiddenWeakVTables &&
    695         Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
    696       TypeInfoVisibility = HiddenVisibility;
    697 
    698     // The type name should have the same visibility as the type itself.
    699     Visibility ExplicitVisibility = Ty->getVisibility();
    700     TypeName->setVisibility(CodeGenModule::
    701                             GetLLVMVisibility(ExplicitVisibility));
    702 
    703     TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
    704     GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
    705   }
    706 
    707   GV->setUnnamedAddr(true);
    708 
    709   return llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
    710 }
    711 
    712 /// ComputeQualifierFlags - Compute the pointer type info flags from the
    713 /// given qualifier.
    714 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
    715   unsigned Flags = 0;
    716 
    717   if (Quals.hasConst())
    718     Flags |= RTTIBuilder::PTI_Const;
    719   if (Quals.hasVolatile())
    720     Flags |= RTTIBuilder::PTI_Volatile;
    721   if (Quals.hasRestrict())
    722     Flags |= RTTIBuilder::PTI_Restrict;
    723 
    724   return Flags;
    725 }
    726 
    727 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
    728 /// for the given Objective-C object type.
    729 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
    730   // Drop qualifiers.
    731   const Type *T = OT->getBaseType().getTypePtr();
    732   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
    733 
    734   // The builtin types are abi::__class_type_infos and don't require
    735   // extra fields.
    736   if (isa<BuiltinType>(T)) return;
    737 
    738   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
    739   ObjCInterfaceDecl *Super = Class->getSuperClass();
    740 
    741   // Root classes are also __class_type_info.
    742   if (!Super) return;
    743 
    744   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
    745 
    746   // Everything else is single inheritance.
    747   llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
    748   Fields.push_back(BaseTypeInfo);
    749 }
    750 
    751 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
    752 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
    753 void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
    754   // Itanium C++ ABI 2.9.5p6b:
    755   // It adds to abi::__class_type_info a single member pointing to the
    756   // type_info structure for the base type,
    757   llvm::Constant *BaseTypeInfo =
    758     RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
    759   Fields.push_back(BaseTypeInfo);
    760 }
    761 
    762 namespace {
    763   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
    764   /// a class hierarchy.
    765   struct SeenBases {
    766     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
    767     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
    768   };
    769 }
    770 
    771 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
    772 /// abi::__vmi_class_type_info.
    773 ///
    774 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
    775                                              SeenBases &Bases) {
    776 
    777   unsigned Flags = 0;
    778 
    779   const CXXRecordDecl *BaseDecl =
    780     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
    781 
    782   if (Base->isVirtual()) {
    783     if (Bases.VirtualBases.count(BaseDecl)) {
    784       // If this virtual base has been seen before, then the class is diamond
    785       // shaped.
    786       Flags |= RTTIBuilder::VMI_DiamondShaped;
    787     } else {
    788       if (Bases.NonVirtualBases.count(BaseDecl))
    789         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
    790 
    791       // Mark the virtual base as seen.
    792       Bases.VirtualBases.insert(BaseDecl);
    793     }
    794   } else {
    795     if (Bases.NonVirtualBases.count(BaseDecl)) {
    796       // If this non-virtual base has been seen before, then the class has non-
    797       // diamond shaped repeated inheritance.
    798       Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
    799     } else {
    800       if (Bases.VirtualBases.count(BaseDecl))
    801         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
    802 
    803       // Mark the non-virtual base as seen.
    804       Bases.NonVirtualBases.insert(BaseDecl);
    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 
    816 static 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.
    831 void 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 = 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.
    910 void 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.
    940 void 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 
    981 llvm::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 && !getContext().getLangOptions().RTTI) {
    987     llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
    988     return llvm::Constant::getNullValue(Int8PtrTy);
    989   }
    990 
    991   if (ForEH && Ty->isObjCObjectPointerType() && !Features.NeXTRuntime) {
    992     return ObjCRuntime->GetEHType(Ty);
    993   }
    994 
    995   return RTTIBuilder(*this).BuildTypeInfo(Ty);
    996 }
    997 
    998 void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
    999   QualType PointerType = Context.getPointerType(Type);
   1000   QualType PointerTypeConst = Context.getPointerType(Type.withConst());
   1001   RTTIBuilder(*this).BuildTypeInfo(Type, true);
   1002   RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
   1003   RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
   1004 }
   1005 
   1006 void CodeGenModule::EmitFundamentalRTTIDescriptors() {
   1007   QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
   1008                                   Context.BoolTy, Context.WCharTy,
   1009                                   Context.CharTy, Context.UnsignedCharTy,
   1010                                   Context.SignedCharTy, Context.ShortTy,
   1011                                   Context.UnsignedShortTy, Context.IntTy,
   1012                                   Context.UnsignedIntTy, Context.LongTy,
   1013                                   Context.UnsignedLongTy, Context.LongLongTy,
   1014                                   Context.UnsignedLongLongTy, Context.FloatTy,
   1015                                   Context.DoubleTy, Context.LongDoubleTy,
   1016                                   Context.Char16Ty, Context.Char32Ty };
   1017   for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
   1018     EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);
   1019 }
   1020