clang API Documentation

CXXInheritance.cpp
Go to the documentation of this file.
00001 //===------ CXXInheritance.cpp - C++ Inheritance ----------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file provides routines that help analyzing C++ inheritance hierarchies.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #include "clang/AST/CXXInheritance.h"
00014 #include "clang/AST/RecordLayout.h"
00015 #include "clang/AST/DeclCXX.h"
00016 #include <algorithm>
00017 #include <set>
00018 
00019 using namespace clang;
00020 
00021 /// \brief Computes the set of declarations referenced by these base
00022 /// paths.
00023 void CXXBasePaths::ComputeDeclsFound() {
00024   assert(NumDeclsFound == 0 && !DeclsFound &&
00025          "Already computed the set of declarations");
00026 
00027   SmallVector<NamedDecl *, 8> Decls;
00028   for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
00029     Decls.push_back(*Path->Decls.first);
00030 
00031   // Eliminate duplicated decls.
00032   llvm::array_pod_sort(Decls.begin(), Decls.end());
00033   Decls.erase(std::unique(Decls.begin(), Decls.end()), Decls.end());
00034 
00035   NumDeclsFound = Decls.size();
00036   DeclsFound = new NamedDecl * [NumDeclsFound];
00037   std::copy(Decls.begin(), Decls.end(), DeclsFound);
00038 }
00039 
00040 CXXBasePaths::decl_iterator CXXBasePaths::found_decls_begin() {
00041   if (NumDeclsFound == 0)
00042     ComputeDeclsFound();
00043   return DeclsFound;
00044 }
00045 
00046 CXXBasePaths::decl_iterator CXXBasePaths::found_decls_end() {
00047   if (NumDeclsFound == 0)
00048     ComputeDeclsFound();
00049   return DeclsFound + NumDeclsFound;
00050 }
00051 
00052 /// isAmbiguous - Determines whether the set of paths provided is
00053 /// ambiguous, i.e., there are two or more paths that refer to
00054 /// different base class subobjects of the same type. BaseType must be
00055 /// an unqualified, canonical class type.
00056 bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
00057   BaseType = BaseType.getUnqualifiedType();
00058   std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
00059   return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
00060 }
00061 
00062 /// clear - Clear out all prior path information.
00063 void CXXBasePaths::clear() {
00064   Paths.clear();
00065   ClassSubobjects.clear();
00066   ScratchPath.clear();
00067   DetectedVirtual = 0;
00068 }
00069 
00070 /// @brief Swaps the contents of this CXXBasePaths structure with the
00071 /// contents of Other.
00072 void CXXBasePaths::swap(CXXBasePaths &Other) {
00073   std::swap(Origin, Other.Origin);
00074   Paths.swap(Other.Paths);
00075   ClassSubobjects.swap(Other.ClassSubobjects);
00076   std::swap(FindAmbiguities, Other.FindAmbiguities);
00077   std::swap(RecordPaths, Other.RecordPaths);
00078   std::swap(DetectVirtual, Other.DetectVirtual);
00079   std::swap(DetectedVirtual, Other.DetectedVirtual);
00080 }
00081 
00082 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
00083   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
00084                      /*DetectVirtual=*/false);
00085   return isDerivedFrom(Base, Paths);
00086 }
00087 
00088 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
00089                                   CXXBasePaths &Paths) const {
00090   if (getCanonicalDecl() == Base->getCanonicalDecl())
00091     return false;
00092   
00093   Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
00094   return lookupInBases(&FindBaseClass,
00095                        const_cast<CXXRecordDecl*>(Base->getCanonicalDecl()),
00096                        Paths);
00097 }
00098 
00099 bool CXXRecordDecl::isVirtuallyDerivedFrom(CXXRecordDecl *Base) const {
00100   if (!getNumVBases())
00101     return false;
00102 
00103   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
00104                      /*DetectVirtual=*/false);
00105 
00106   if (getCanonicalDecl() == Base->getCanonicalDecl())
00107     return false;
00108   
00109   Paths.setOrigin(const_cast<CXXRecordDecl*>(this));  
00110   return lookupInBases(&FindVirtualBaseClass, Base->getCanonicalDecl(), Paths);
00111 }
00112 
00113 static bool BaseIsNot(const CXXRecordDecl *Base, void *OpaqueTarget) {
00114   // OpaqueTarget is a CXXRecordDecl*.
00115   return Base->getCanonicalDecl() != (const CXXRecordDecl*) OpaqueTarget;
00116 }
00117 
00118 bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
00119   return forallBases(BaseIsNot, (void*) Base->getCanonicalDecl());
00120 }
00121 
00122 bool CXXRecordDecl::forallBases(ForallBasesCallback *BaseMatches,
00123                                 void *OpaqueData,
00124                                 bool AllowShortCircuit) const {
00125   SmallVector<const CXXRecordDecl*, 8> Queue;
00126 
00127   const CXXRecordDecl *Record = this;
00128   bool AllMatches = true;
00129   while (true) {
00130     for (CXXRecordDecl::base_class_const_iterator
00131            I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
00132       const RecordType *Ty = I->getType()->getAs<RecordType>();
00133       if (!Ty) {
00134         if (AllowShortCircuit) return false;
00135         AllMatches = false;
00136         continue;
00137       }
00138 
00139       CXXRecordDecl *Base = 
00140             cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
00141       if (!Base) {
00142         if (AllowShortCircuit) return false;
00143         AllMatches = false;
00144         continue;
00145       }
00146       
00147       Queue.push_back(Base);
00148       if (!BaseMatches(Base, OpaqueData)) {
00149         if (AllowShortCircuit) return false;
00150         AllMatches = false;
00151         continue;
00152       }
00153     }
00154 
00155     if (Queue.empty()) break;
00156     Record = Queue.back(); // not actually a queue.
00157     Queue.pop_back();
00158   }
00159 
00160   return AllMatches;
00161 }
00162 
00163 bool CXXBasePaths::lookupInBases(ASTContext &Context, 
00164                                  const CXXRecordDecl *Record,
00165                                CXXRecordDecl::BaseMatchesCallback *BaseMatches, 
00166                                  void *UserData) {
00167   bool FoundPath = false;
00168 
00169   // The access of the path down to this record.
00170   AccessSpecifier AccessToHere = ScratchPath.Access;
00171   bool IsFirstStep = ScratchPath.empty();
00172 
00173   for (CXXRecordDecl::base_class_const_iterator BaseSpec = Record->bases_begin(),
00174          BaseSpecEnd = Record->bases_end(); 
00175        BaseSpec != BaseSpecEnd; 
00176        ++BaseSpec) {
00177     // Find the record of the base class subobjects for this type.
00178     QualType BaseType = Context.getCanonicalType(BaseSpec->getType())
00179                                                           .getUnqualifiedType();
00180     
00181     // C++ [temp.dep]p3:
00182     //   In the definition of a class template or a member of a class template,
00183     //   if a base class of the class template depends on a template-parameter,
00184     //   the base class scope is not examined during unqualified name lookup 
00185     //   either at the point of definition of the class template or member or 
00186     //   during an instantiation of the class tem- plate or member.
00187     if (BaseType->isDependentType())
00188       continue;
00189     
00190     // Determine whether we need to visit this base class at all,
00191     // updating the count of subobjects appropriately.
00192     std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
00193     bool VisitBase = true;
00194     bool SetVirtual = false;
00195     if (BaseSpec->isVirtual()) {
00196       VisitBase = !Subobjects.first;
00197       Subobjects.first = true;
00198       if (isDetectingVirtual() && DetectedVirtual == 0) {
00199         // If this is the first virtual we find, remember it. If it turns out
00200         // there is no base path here, we'll reset it later.
00201         DetectedVirtual = BaseType->getAs<RecordType>();
00202         SetVirtual = true;
00203       }
00204     } else
00205       ++Subobjects.second;
00206     
00207     if (isRecordingPaths()) {
00208       // Add this base specifier to the current path.
00209       CXXBasePathElement Element;
00210       Element.Base = &*BaseSpec;
00211       Element.Class = Record;
00212       if (BaseSpec->isVirtual())
00213         Element.SubobjectNumber = 0;
00214       else
00215         Element.SubobjectNumber = Subobjects.second;
00216       ScratchPath.push_back(Element);
00217 
00218       // Calculate the "top-down" access to this base class.
00219       // The spec actually describes this bottom-up, but top-down is
00220       // equivalent because the definition works out as follows:
00221       // 1. Write down the access along each step in the inheritance
00222       //    chain, followed by the access of the decl itself.
00223       //    For example, in
00224       //      class A { public: int foo; };
00225       //      class B : protected A {};
00226       //      class C : public B {};
00227       //      class D : private C {};
00228       //    we would write:
00229       //      private public protected public
00230       // 2. If 'private' appears anywhere except far-left, access is denied.
00231       // 3. Otherwise, overall access is determined by the most restrictive
00232       //    access in the sequence.
00233       if (IsFirstStep)
00234         ScratchPath.Access = BaseSpec->getAccessSpecifier();
00235       else
00236         ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, 
00237                                                  BaseSpec->getAccessSpecifier());
00238     }
00239     
00240     // Track whether there's a path involving this specific base.
00241     bool FoundPathThroughBase = false;
00242     
00243     if (BaseMatches(BaseSpec, ScratchPath, UserData)) {
00244       // We've found a path that terminates at this base.
00245       FoundPath = FoundPathThroughBase = true;
00246       if (isRecordingPaths()) {
00247         // We have a path. Make a copy of it before moving on.
00248         Paths.push_back(ScratchPath);
00249       } else if (!isFindingAmbiguities()) {
00250         // We found a path and we don't care about ambiguities;
00251         // return immediately.
00252         return FoundPath;
00253       }
00254     } else if (VisitBase) {
00255       CXXRecordDecl *BaseRecord
00256         = cast<CXXRecordDecl>(BaseSpec->getType()->getAs<RecordType>()
00257                                 ->getDecl());
00258       if (lookupInBases(Context, BaseRecord, BaseMatches, UserData)) {
00259         // C++ [class.member.lookup]p2:
00260         //   A member name f in one sub-object B hides a member name f in
00261         //   a sub-object A if A is a base class sub-object of B. Any
00262         //   declarations that are so hidden are eliminated from
00263         //   consideration.
00264         
00265         // There is a path to a base class that meets the criteria. If we're 
00266         // not collecting paths or finding ambiguities, we're done.
00267         FoundPath = FoundPathThroughBase = true;
00268         if (!isFindingAmbiguities())
00269           return FoundPath;
00270       }
00271     }
00272     
00273     // Pop this base specifier off the current path (if we're
00274     // collecting paths).
00275     if (isRecordingPaths()) {
00276       ScratchPath.pop_back();
00277     }
00278 
00279     // If we set a virtual earlier, and this isn't a path, forget it again.
00280     if (SetVirtual && !FoundPathThroughBase) {
00281       DetectedVirtual = 0;
00282     }
00283   }
00284 
00285   // Reset the scratch path access.
00286   ScratchPath.Access = AccessToHere;
00287   
00288   return FoundPath;
00289 }
00290 
00291 bool CXXRecordDecl::lookupInBases(BaseMatchesCallback *BaseMatches,
00292                                   void *UserData,
00293                                   CXXBasePaths &Paths) const {
00294   // If we didn't find anything, report that.
00295   if (!Paths.lookupInBases(getASTContext(), this, BaseMatches, UserData))
00296     return false;
00297 
00298   // If we're not recording paths or we won't ever find ambiguities,
00299   // we're done.
00300   if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
00301     return true;
00302   
00303   // C++ [class.member.lookup]p6:
00304   //   When virtual base classes are used, a hidden declaration can be
00305   //   reached along a path through the sub-object lattice that does
00306   //   not pass through the hiding declaration. This is not an
00307   //   ambiguity. The identical use with nonvirtual base classes is an
00308   //   ambiguity; in that case there is no unique instance of the name
00309   //   that hides all the others.
00310   //
00311   // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
00312   // way to make it any faster.
00313   for (CXXBasePaths::paths_iterator P = Paths.begin(), PEnd = Paths.end();
00314        P != PEnd; /* increment in loop */) {
00315     bool Hidden = false;
00316 
00317     for (CXXBasePath::iterator PE = P->begin(), PEEnd = P->end();
00318          PE != PEEnd && !Hidden; ++PE) {
00319       if (PE->Base->isVirtual()) {
00320         CXXRecordDecl *VBase = 0;
00321         if (const RecordType *Record = PE->Base->getType()->getAs<RecordType>())
00322           VBase = cast<CXXRecordDecl>(Record->getDecl());
00323         if (!VBase)
00324           break;
00325 
00326         // The declaration(s) we found along this path were found in a
00327         // subobject of a virtual base. Check whether this virtual
00328         // base is a subobject of any other path; if so, then the
00329         // declaration in this path are hidden by that patch.
00330         for (CXXBasePaths::paths_iterator HidingP = Paths.begin(),
00331                                        HidingPEnd = Paths.end();
00332              HidingP != HidingPEnd;
00333              ++HidingP) {
00334           CXXRecordDecl *HidingClass = 0;
00335           if (const RecordType *Record
00336                        = HidingP->back().Base->getType()->getAs<RecordType>())
00337             HidingClass = cast<CXXRecordDecl>(Record->getDecl());
00338           if (!HidingClass)
00339             break;
00340 
00341           if (HidingClass->isVirtuallyDerivedFrom(VBase)) {
00342             Hidden = true;
00343             break;
00344           }
00345         }
00346       }
00347     }
00348 
00349     if (Hidden)
00350       P = Paths.Paths.erase(P);
00351     else
00352       ++P;
00353   }
00354   
00355   return true;
00356 }
00357 
00358 bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, 
00359                                   CXXBasePath &Path,
00360                                   void *BaseRecord) {
00361   assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
00362          "User data for FindBaseClass is not canonical!");
00363   return Specifier->getType()->getAs<RecordType>()->getDecl()
00364            ->getCanonicalDecl() == BaseRecord;
00365 }
00366 
00367 bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, 
00368                                          CXXBasePath &Path,
00369                                          void *BaseRecord) {
00370   assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
00371          "User data for FindBaseClass is not canonical!");
00372   return Specifier->isVirtual() &&
00373          Specifier->getType()->getAs<RecordType>()->getDecl()
00374            ->getCanonicalDecl() == BaseRecord;
00375 }
00376 
00377 bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, 
00378                                   CXXBasePath &Path,
00379                                   void *Name) {
00380   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
00381 
00382   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
00383   for (Path.Decls = BaseRecord->lookup(N);
00384        Path.Decls.first != Path.Decls.second;
00385        ++Path.Decls.first) {
00386     if ((*Path.Decls.first)->isInIdentifierNamespace(IDNS_Tag))
00387       return true;
00388   }
00389 
00390   return false;
00391 }
00392 
00393 bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier, 
00394                                        CXXBasePath &Path,
00395                                        void *Name) {
00396   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
00397   
00398   const unsigned IDNS = IDNS_Ordinary | IDNS_Tag | IDNS_Member;
00399   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
00400   for (Path.Decls = BaseRecord->lookup(N);
00401        Path.Decls.first != Path.Decls.second;
00402        ++Path.Decls.first) {
00403     if ((*Path.Decls.first)->isInIdentifierNamespace(IDNS))
00404       return true;
00405   }
00406   
00407   return false;
00408 }
00409 
00410 bool CXXRecordDecl::
00411 FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, 
00412                               CXXBasePath &Path,
00413                               void *Name) {
00414   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
00415   
00416   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
00417   for (Path.Decls = BaseRecord->lookup(N);
00418        Path.Decls.first != Path.Decls.second;
00419        ++Path.Decls.first) {
00420     // FIXME: Refactor the "is it a nested-name-specifier?" check
00421     if (isa<TypedefNameDecl>(*Path.Decls.first) ||
00422         (*Path.Decls.first)->isInIdentifierNamespace(IDNS_Tag))
00423       return true;
00424   }
00425   
00426   return false;
00427 }
00428 
00429 void OverridingMethods::add(unsigned OverriddenSubobject, 
00430                             UniqueVirtualMethod Overriding) {
00431   SmallVector<UniqueVirtualMethod, 4> &SubobjectOverrides
00432     = Overrides[OverriddenSubobject];
00433   if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(), 
00434                 Overriding) == SubobjectOverrides.end())
00435     SubobjectOverrides.push_back(Overriding);
00436 }
00437 
00438 void OverridingMethods::add(const OverridingMethods &Other) {
00439   for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
00440     for (overriding_const_iterator M = I->second.begin(), 
00441                                 MEnd = I->second.end();
00442          M != MEnd; 
00443          ++M)
00444       add(I->first, *M);
00445   }
00446 }
00447 
00448 void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
00449   for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
00450     I->second.clear();
00451     I->second.push_back(Overriding);
00452   }
00453 }
00454 
00455 
00456 namespace {
00457   class FinalOverriderCollector {
00458     /// \brief The number of subobjects of a given class type that
00459     /// occur within the class hierarchy.
00460     llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
00461 
00462     /// \brief Overriders for each virtual base subobject.
00463     llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
00464 
00465     CXXFinalOverriderMap FinalOverriders;
00466 
00467   public:
00468     ~FinalOverriderCollector();
00469 
00470     void Collect(const CXXRecordDecl *RD, bool VirtualBase,
00471                  const CXXRecordDecl *InVirtualSubobject,
00472                  CXXFinalOverriderMap &Overriders);
00473   };
00474 }
00475 
00476 void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, 
00477                                       bool VirtualBase,
00478                                       const CXXRecordDecl *InVirtualSubobject,
00479                                       CXXFinalOverriderMap &Overriders) {
00480   unsigned SubobjectNumber = 0;
00481   if (!VirtualBase)
00482     SubobjectNumber
00483       = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
00484 
00485   for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
00486          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
00487     if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
00488       const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
00489       if (!BaseDecl->isPolymorphic())
00490         continue;
00491 
00492       if (Overriders.empty() && !Base->isVirtual()) {
00493         // There are no other overriders of virtual member functions,
00494         // so let the base class fill in our overriders for us.
00495         Collect(BaseDecl, false, InVirtualSubobject, Overriders);
00496         continue;
00497       }
00498 
00499       // Collect all of the overridders from the base class subobject
00500       // and merge them into the set of overridders for this class.
00501       // For virtual base classes, populate or use the cached virtual
00502       // overrides so that we do not walk the virtual base class (and
00503       // its base classes) more than once.
00504       CXXFinalOverriderMap ComputedBaseOverriders;
00505       CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
00506       if (Base->isVirtual()) {
00507         CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
00508         if (!MyVirtualOverriders) {
00509           MyVirtualOverriders = new CXXFinalOverriderMap;
00510           Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
00511         }
00512 
00513         BaseOverriders = MyVirtualOverriders;
00514       } else
00515         Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
00516 
00517       // Merge the overriders from this base class into our own set of
00518       // overriders.
00519       for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), 
00520                                OMEnd = BaseOverriders->end();
00521            OM != OMEnd;
00522            ++OM) {
00523         const CXXMethodDecl *CanonOM
00524           = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
00525         Overriders[CanonOM].add(OM->second);
00526       }
00527     }
00528   }
00529 
00530   for (CXXRecordDecl::method_iterator M = RD->method_begin(), 
00531                                    MEnd = RD->method_end();
00532        M != MEnd;
00533        ++M) {
00534     // We only care about virtual methods.
00535     if (!M->isVirtual())
00536       continue;
00537 
00538     CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
00539 
00540     if (CanonM->begin_overridden_methods()
00541                                        == CanonM->end_overridden_methods()) {
00542       // This is a new virtual function that does not override any
00543       // other virtual function. Add it to the map of virtual
00544       // functions for which we are tracking overridders. 
00545 
00546       // C++ [class.virtual]p2:
00547       //   For convenience we say that any virtual function overrides itself.
00548       Overriders[CanonM].add(SubobjectNumber,
00549                              UniqueVirtualMethod(CanonM, SubobjectNumber,
00550                                                  InVirtualSubobject));
00551       continue;
00552     }
00553 
00554     // This virtual method overrides other virtual methods, so it does
00555     // not add any new slots into the set of overriders. Instead, we
00556     // replace entries in the set of overriders with the new
00557     // overrider. To do so, we dig down to the original virtual
00558     // functions using data recursion and update all of the methods it
00559     // overrides.
00560     typedef std::pair<CXXMethodDecl::method_iterator, 
00561                       CXXMethodDecl::method_iterator> OverriddenMethods;
00562     SmallVector<OverriddenMethods, 4> Stack;
00563     Stack.push_back(std::make_pair(CanonM->begin_overridden_methods(),
00564                                    CanonM->end_overridden_methods()));
00565     while (!Stack.empty()) {
00566       OverriddenMethods OverMethods = Stack.back();
00567       Stack.pop_back();
00568 
00569       for (; OverMethods.first != OverMethods.second; ++OverMethods.first) {
00570         const CXXMethodDecl *CanonOM
00571           = cast<CXXMethodDecl>((*OverMethods.first)->getCanonicalDecl());
00572 
00573         // C++ [class.virtual]p2:
00574         //   A virtual member function C::vf of a class object S is
00575         //   a final overrider unless the most derived class (1.8)
00576         //   of which S is a base class subobject (if any) declares
00577         //   or inherits another member function that overrides vf.
00578         //
00579         // Treating this object like the most derived class, we
00580         // replace any overrides from base classes with this
00581         // overriding virtual function.
00582         Overriders[CanonOM].replaceAll(
00583                                UniqueVirtualMethod(CanonM, SubobjectNumber,
00584                                                    InVirtualSubobject));
00585 
00586         if (CanonOM->begin_overridden_methods()
00587                                        == CanonOM->end_overridden_methods())
00588           continue;
00589 
00590         // Continue recursion to the methods that this virtual method
00591         // overrides.
00592         Stack.push_back(std::make_pair(CanonOM->begin_overridden_methods(),
00593                                        CanonOM->end_overridden_methods()));
00594       }
00595     }
00596 
00597     // C++ [class.virtual]p2:
00598     //   For convenience we say that any virtual function overrides itself.
00599     Overriders[CanonM].add(SubobjectNumber,
00600                            UniqueVirtualMethod(CanonM, SubobjectNumber,
00601                                                InVirtualSubobject));
00602   }
00603 }
00604 
00605 FinalOverriderCollector::~FinalOverriderCollector() {
00606   for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
00607          VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
00608        VO != VOEnd; 
00609        ++VO)
00610     delete VO->second;
00611 }
00612 
00613 void 
00614 CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
00615   FinalOverriderCollector Collector;
00616   Collector.Collect(this, false, 0, FinalOverriders);
00617 
00618   // Weed out any final overriders that come from virtual base class
00619   // subobjects that were hidden by other subobjects along any path.
00620   // This is the final-overrider variant of C++ [class.member.lookup]p10.
00621   for (CXXFinalOverriderMap::iterator OM = FinalOverriders.begin(), 
00622                            OMEnd = FinalOverriders.end();
00623        OM != OMEnd;
00624        ++OM) {
00625     for (OverridingMethods::iterator SO = OM->second.begin(), 
00626                                   SOEnd = OM->second.end();
00627          SO != SOEnd; 
00628          ++SO) {
00629       SmallVector<UniqueVirtualMethod, 4> &Overriding = SO->second;
00630       if (Overriding.size() < 2)
00631         continue;
00632 
00633       for (SmallVector<UniqueVirtualMethod, 4>::iterator 
00634              Pos = Overriding.begin(), PosEnd = Overriding.end();
00635            Pos != PosEnd;
00636            /* increment in loop */) {
00637         if (!Pos->InVirtualSubobject) {
00638           ++Pos;
00639           continue;
00640         }
00641 
00642         // We have an overriding method in a virtual base class
00643         // subobject (or non-virtual base class subobject thereof);
00644         // determine whether there exists an other overriding method
00645         // in a base class subobject that hides the virtual base class
00646         // subobject.
00647         bool Hidden = false;
00648         for (SmallVector<UniqueVirtualMethod, 4>::iterator
00649                OP = Overriding.begin(), OPEnd = Overriding.end();
00650              OP != OPEnd && !Hidden; 
00651              ++OP) {
00652           if (Pos == OP)
00653             continue;
00654 
00655           if (OP->Method->getParent()->isVirtuallyDerivedFrom(
00656                          const_cast<CXXRecordDecl *>(Pos->InVirtualSubobject)))
00657             Hidden = true;
00658         }
00659 
00660         if (Hidden) {
00661           // The current overriding function is hidden by another
00662           // overriding function; remove this one.
00663           Pos = Overriding.erase(Pos);
00664           PosEnd = Overriding.end();
00665         } else {
00666           ++Pos;
00667         }
00668       }
00669     }
00670   }
00671 }
00672 
00673 static void 
00674 AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
00675                         CXXIndirectPrimaryBaseSet& Bases) {
00676   // If the record has a virtual primary base class, add it to our set.
00677   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00678   if (Layout.isPrimaryBaseVirtual())
00679     Bases.insert(Layout.getPrimaryBase());
00680 
00681   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00682        E = RD->bases_end(); I != E; ++I) {
00683     assert(!I->getType()->isDependentType() &&
00684            "Cannot get indirect primary bases for class with dependent bases.");
00685 
00686     const CXXRecordDecl *BaseDecl =
00687       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00688 
00689     // Only bases with virtual bases participate in computing the
00690     // indirect primary virtual base classes.
00691     if (BaseDecl->getNumVBases())
00692       AddIndirectPrimaryBases(BaseDecl, Context, Bases);
00693   }
00694 
00695 }
00696 
00697 void 
00698 CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
00699   ASTContext &Context = getASTContext();
00700 
00701   if (!getNumVBases())
00702     return;
00703 
00704   for (CXXRecordDecl::base_class_const_iterator I = bases_begin(),
00705        E = bases_end(); I != E; ++I) {
00706     assert(!I->getType()->isDependentType() &&
00707            "Cannot get indirect primary bases for class with dependent bases.");
00708 
00709     const CXXRecordDecl *BaseDecl =
00710       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00711 
00712     // Only bases with virtual bases participate in computing the
00713     // indirect primary virtual base classes.
00714     if (BaseDecl->getNumVBases())
00715       AddIndirectPrimaryBases(BaseDecl, Context, Bases);
00716   }
00717 }
00718