]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/AST/VTableBuilder.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / AST / VTableBuilder.cpp
1 //===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
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 generation of the layout of virtual tables.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/VTableBuilder.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "llvm/Support/Format.h"
19 #include <algorithm>
20 #include <cstdio>
21
22 using namespace clang;
23
24 #define DUMP_OVERRIDERS 0
25
26 namespace {
27
28 /// BaseOffset - Represents an offset from a derived class to a direct or
29 /// indirect base class.
30 struct BaseOffset {
31   /// DerivedClass - The derived class.
32   const CXXRecordDecl *DerivedClass;
33   
34   /// VirtualBase - If the path from the derived class to the base class
35   /// involves a virtual base class, this holds its declaration.
36   const CXXRecordDecl *VirtualBase;
37
38   /// NonVirtualOffset - The offset from the derived class to the base class.
39   /// (Or the offset from the virtual base class to the base class, if the 
40   /// path from the derived class to the base class involves a virtual base
41   /// class.
42   CharUnits NonVirtualOffset;
43   
44   BaseOffset() : DerivedClass(0), VirtualBase(0), 
45     NonVirtualOffset(CharUnits::Zero()) { }
46   BaseOffset(const CXXRecordDecl *DerivedClass,
47              const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
48     : DerivedClass(DerivedClass), VirtualBase(VirtualBase), 
49     NonVirtualOffset(NonVirtualOffset) { }
50
51   bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
52 };
53
54 /// FinalOverriders - Contains the final overrider member functions for all
55 /// member functions in the base subobjects of a class.
56 class FinalOverriders {
57 public:
58   /// OverriderInfo - Information about a final overrider.
59   struct OverriderInfo {
60     /// Method - The method decl of the overrider.
61     const CXXMethodDecl *Method;
62
63     /// Offset - the base offset of the overrider in the layout class.
64     CharUnits Offset;
65     
66     OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
67   };
68
69 private:
70   /// MostDerivedClass - The most derived class for which the final overriders
71   /// are stored.
72   const CXXRecordDecl *MostDerivedClass;
73   
74   /// MostDerivedClassOffset - If we're building final overriders for a 
75   /// construction vtable, this holds the offset from the layout class to the
76   /// most derived class.
77   const CharUnits MostDerivedClassOffset;
78
79   /// LayoutClass - The class we're using for layout information. Will be 
80   /// different than the most derived class if the final overriders are for a
81   /// construction vtable.  
82   const CXXRecordDecl *LayoutClass;  
83
84   ASTContext &Context;
85   
86   /// MostDerivedClassLayout - the AST record layout of the most derived class.
87   const ASTRecordLayout &MostDerivedClassLayout;
88
89   /// MethodBaseOffsetPairTy - Uniquely identifies a member function
90   /// in a base subobject.
91   typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
92
93   typedef llvm::DenseMap<MethodBaseOffsetPairTy,
94                          OverriderInfo> OverridersMapTy;
95   
96   /// OverridersMap - The final overriders for all virtual member functions of 
97   /// all the base subobjects of the most derived class.
98   OverridersMapTy OverridersMap;
99   
100   /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
101   /// as a record decl and a subobject number) and its offsets in the most
102   /// derived class as well as the layout class.
103   typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>, 
104                          CharUnits> SubobjectOffsetMapTy;
105
106   typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
107   
108   /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
109   /// given base.
110   void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
111                           CharUnits OffsetInLayoutClass,
112                           SubobjectOffsetMapTy &SubobjectOffsets,
113                           SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
114                           SubobjectCountMapTy &SubobjectCounts);
115
116   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
117   
118   /// dump - dump the final overriders for a base subobject, and all its direct
119   /// and indirect base subobjects.
120   void dump(raw_ostream &Out, BaseSubobject Base,
121             VisitedVirtualBasesSetTy& VisitedVirtualBases);
122   
123 public:
124   FinalOverriders(const CXXRecordDecl *MostDerivedClass,
125                   CharUnits MostDerivedClassOffset,
126                   const CXXRecordDecl *LayoutClass);
127
128   /// getOverrider - Get the final overrider for the given method declaration in
129   /// the subobject with the given base offset. 
130   OverriderInfo getOverrider(const CXXMethodDecl *MD, 
131                              CharUnits BaseOffset) const {
132     assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) && 
133            "Did not find overrider!");
134     
135     return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
136   }
137   
138   /// dump - dump the final overriders.
139   void dump() {
140     VisitedVirtualBasesSetTy VisitedVirtualBases;
141     dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()), 
142          VisitedVirtualBases);
143   }
144   
145 };
146
147 #define DUMP_OVERRIDERS 0
148
149 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
150                                  CharUnits MostDerivedClassOffset,
151                                  const CXXRecordDecl *LayoutClass)
152   : MostDerivedClass(MostDerivedClass), 
153   MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
154   Context(MostDerivedClass->getASTContext()),
155   MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
156
157   // Compute base offsets.
158   SubobjectOffsetMapTy SubobjectOffsets;
159   SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
160   SubobjectCountMapTy SubobjectCounts;
161   ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 
162                      /*IsVirtual=*/false,
163                      MostDerivedClassOffset, 
164                      SubobjectOffsets, SubobjectLayoutClassOffsets, 
165                      SubobjectCounts);
166
167   // Get the the final overriders.
168   CXXFinalOverriderMap FinalOverriders;
169   MostDerivedClass->getFinalOverriders(FinalOverriders);
170
171   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
172        E = FinalOverriders.end(); I != E; ++I) {
173     const CXXMethodDecl *MD = I->first;
174     const OverridingMethods& Methods = I->second;
175
176     for (OverridingMethods::const_iterator I = Methods.begin(),
177          E = Methods.end(); I != E; ++I) {
178       unsigned SubobjectNumber = I->first;
179       assert(SubobjectOffsets.count(std::make_pair(MD->getParent(), 
180                                                    SubobjectNumber)) &&
181              "Did not find subobject offset!");
182       
183       CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
184                                                             SubobjectNumber)];
185
186       assert(I->second.size() == 1 && "Final overrider is not unique!");
187       const UniqueVirtualMethod &Method = I->second.front();
188
189       const CXXRecordDecl *OverriderRD = Method.Method->getParent();
190       assert(SubobjectLayoutClassOffsets.count(
191              std::make_pair(OverriderRD, Method.Subobject))
192              && "Did not find subobject offset!");
193       CharUnits OverriderOffset =
194         SubobjectLayoutClassOffsets[std::make_pair(OverriderRD, 
195                                                    Method.Subobject)];
196
197       OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
198       assert(!Overrider.Method && "Overrider should not exist yet!");
199       
200       Overrider.Offset = OverriderOffset;
201       Overrider.Method = Method.Method;
202     }
203   }
204
205 #if DUMP_OVERRIDERS
206   // And dump them (for now).
207   dump();
208 #endif
209 }
210
211 static BaseOffset ComputeBaseOffset(ASTContext &Context, 
212                                     const CXXRecordDecl *DerivedRD,
213                                     const CXXBasePath &Path) {
214   CharUnits NonVirtualOffset = CharUnits::Zero();
215
216   unsigned NonVirtualStart = 0;
217   const CXXRecordDecl *VirtualBase = 0;
218   
219   // First, look for the virtual base class.
220   for (unsigned I = 0, E = Path.size(); I != E; ++I) {
221     const CXXBasePathElement &Element = Path[I];
222     
223     if (Element.Base->isVirtual()) {
224       // FIXME: Can we break when we find the first virtual base?
225       // (If we can't, can't we just iterate over the path in reverse order?)
226       NonVirtualStart = I + 1;
227       QualType VBaseType = Element.Base->getType();
228       VirtualBase = 
229         cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
230     }
231   }
232   
233   // Now compute the non-virtual offset.
234   for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
235     const CXXBasePathElement &Element = Path[I];
236     
237     // Check the base class offset.
238     const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
239
240     const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
241     const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
242
243     NonVirtualOffset += Layout.getBaseClassOffset(Base);
244   }
245   
246   // FIXME: This should probably use CharUnits or something. Maybe we should
247   // even change the base offsets in ASTRecordLayout to be specified in 
248   // CharUnits.
249   return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
250   
251 }
252
253 static BaseOffset ComputeBaseOffset(ASTContext &Context, 
254                                     const CXXRecordDecl *BaseRD,
255                                     const CXXRecordDecl *DerivedRD) {
256   CXXBasePaths Paths(/*FindAmbiguities=*/false,
257                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
258   
259   if (!const_cast<CXXRecordDecl *>(DerivedRD)->
260       isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
261     llvm_unreachable("Class must be derived from the passed in base class!");
262   }
263
264   return ComputeBaseOffset(Context, DerivedRD, Paths.front());
265 }
266
267 static BaseOffset
268 ComputeReturnAdjustmentBaseOffset(ASTContext &Context, 
269                                   const CXXMethodDecl *DerivedMD,
270                                   const CXXMethodDecl *BaseMD) {
271   const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
272   const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
273   
274   // Canonicalize the return types.
275   CanQualType CanDerivedReturnType = 
276     Context.getCanonicalType(DerivedFT->getResultType());
277   CanQualType CanBaseReturnType = 
278     Context.getCanonicalType(BaseFT->getResultType());
279   
280   assert(CanDerivedReturnType->getTypeClass() == 
281          CanBaseReturnType->getTypeClass() && 
282          "Types must have same type class!");
283   
284   if (CanDerivedReturnType == CanBaseReturnType) {
285     // No adjustment needed.
286     return BaseOffset();
287   }
288   
289   if (isa<ReferenceType>(CanDerivedReturnType)) {
290     CanDerivedReturnType = 
291       CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
292     CanBaseReturnType = 
293       CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
294   } else if (isa<PointerType>(CanDerivedReturnType)) {
295     CanDerivedReturnType = 
296       CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
297     CanBaseReturnType = 
298       CanBaseReturnType->getAs<PointerType>()->getPointeeType();
299   } else {
300     llvm_unreachable("Unexpected return type!");
301   }
302   
303   // We need to compare unqualified types here; consider
304   //   const T *Base::foo();
305   //   T *Derived::foo();
306   if (CanDerivedReturnType.getUnqualifiedType() == 
307       CanBaseReturnType.getUnqualifiedType()) {
308     // No adjustment needed.
309     return BaseOffset();
310   }
311   
312   const CXXRecordDecl *DerivedRD = 
313     cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
314   
315   const CXXRecordDecl *BaseRD = 
316     cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
317
318   return ComputeBaseOffset(Context, BaseRD, DerivedRD);
319 }
320
321 void 
322 FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
323                               CharUnits OffsetInLayoutClass,
324                               SubobjectOffsetMapTy &SubobjectOffsets,
325                               SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
326                               SubobjectCountMapTy &SubobjectCounts) {
327   const CXXRecordDecl *RD = Base.getBase();
328   
329   unsigned SubobjectNumber = 0;
330   if (!IsVirtual)
331     SubobjectNumber = ++SubobjectCounts[RD];
332
333   // Set up the subobject to offset mapping.
334   assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
335          && "Subobject offset already exists!");
336   assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber)) 
337          && "Subobject offset already exists!");
338
339   SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
340   SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
341     OffsetInLayoutClass;
342   
343   // Traverse our bases.
344   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
345        E = RD->bases_end(); I != E; ++I) {
346     const CXXRecordDecl *BaseDecl = 
347       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
348
349     CharUnits BaseOffset;
350     CharUnits BaseOffsetInLayoutClass;
351     if (I->isVirtual()) {
352       // Check if we've visited this virtual base before.
353       if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
354         continue;
355
356       const ASTRecordLayout &LayoutClassLayout =
357         Context.getASTRecordLayout(LayoutClass);
358
359       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
360       BaseOffsetInLayoutClass = 
361         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
362     } else {
363       const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
364       CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
365     
366       BaseOffset = Base.getBaseOffset() + Offset;
367       BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
368     }
369
370     ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), 
371                        I->isVirtual(), BaseOffsetInLayoutClass, 
372                        SubobjectOffsets, SubobjectLayoutClassOffsets, 
373                        SubobjectCounts);
374   }
375 }
376
377 void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
378                            VisitedVirtualBasesSetTy &VisitedVirtualBases) {
379   const CXXRecordDecl *RD = Base.getBase();
380   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
381
382   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
383        E = RD->bases_end(); I != E; ++I) {
384     const CXXRecordDecl *BaseDecl = 
385       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
386     
387     // Ignore bases that don't have any virtual member functions.
388     if (!BaseDecl->isPolymorphic())
389       continue;
390
391     CharUnits BaseOffset;
392     if (I->isVirtual()) {
393       if (!VisitedVirtualBases.insert(BaseDecl)) {
394         // We've visited this base before.
395         continue;
396       }
397       
398       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
399     } else {
400       BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
401     }
402
403     dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
404   }
405
406   Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
407   Out << Base.getBaseOffset().getQuantity() << ")\n";
408
409   // Now dump the overriders for this base subobject.
410   for (CXXRecordDecl::method_iterator I = RD->method_begin(), 
411        E = RD->method_end(); I != E; ++I) {
412     const CXXMethodDecl *MD = *I;
413
414     if (!MD->isVirtual())
415       continue;
416   
417     OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
418
419     Out << "  " << MD->getQualifiedNameAsString() << " - (";
420     Out << Overrider.Method->getQualifiedNameAsString();
421     Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
422
423     BaseOffset Offset;
424     if (!Overrider.Method->isPure())
425       Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
426
427     if (!Offset.isEmpty()) {
428       Out << " [ret-adj: ";
429       if (Offset.VirtualBase)
430         Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
431              
432       Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
433     }
434     
435     Out << "\n";
436   }  
437 }
438
439 /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
440 struct VCallOffsetMap {
441   
442   typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
443   
444   /// Offsets - Keeps track of methods and their offsets.
445   // FIXME: This should be a real map and not a vector.
446   SmallVector<MethodAndOffsetPairTy, 16> Offsets;
447
448   /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
449   /// can share the same vcall offset.
450   static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
451                                          const CXXMethodDecl *RHS);
452
453 public:
454   /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
455   /// add was successful, or false if there was already a member function with
456   /// the same signature in the map.
457   bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
458   
459   /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
460   /// vtable address point) for the given virtual member function.
461   CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
462   
463   // empty - Return whether the offset map is empty or not.
464   bool empty() const { return Offsets.empty(); }
465 };
466
467 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
468                                     const CXXMethodDecl *RHS) {
469   ASTContext &C = LHS->getASTContext(); // TODO: thread this down
470   CanQual<FunctionProtoType>
471     LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
472     RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
473
474   // Fast-path matches in the canonical types.
475   if (LT == RT) return true;
476
477   // Force the signatures to match.  We can't rely on the overrides
478   // list here because there isn't necessarily an inheritance
479   // relationship between the two methods.
480   if (LT.getQualifiers() != RT.getQualifiers() ||
481       LT->getNumArgs() != RT->getNumArgs())
482     return false;
483   for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
484     if (LT->getArgType(I) != RT->getArgType(I))
485       return false;
486   return true;
487 }
488
489 bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
490                                                 const CXXMethodDecl *RHS) {
491   assert(LHS->isVirtual() && "LHS must be virtual!");
492   assert(RHS->isVirtual() && "LHS must be virtual!");
493   
494   // A destructor can share a vcall offset with another destructor.
495   if (isa<CXXDestructorDecl>(LHS))
496     return isa<CXXDestructorDecl>(RHS);
497
498   // FIXME: We need to check more things here.
499   
500   // The methods must have the same name.
501   DeclarationName LHSName = LHS->getDeclName();
502   DeclarationName RHSName = RHS->getDeclName();
503   if (LHSName != RHSName)
504     return false;
505
506   // And the same signatures.
507   return HasSameVirtualSignature(LHS, RHS);
508 }
509
510 bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, 
511                                     CharUnits OffsetOffset) {
512   // Check if we can reuse an offset.
513   for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
514     if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
515       return false;
516   }
517   
518   // Add the offset.
519   Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
520   return true;
521 }
522
523 CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
524   // Look for an offset.
525   for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
526     if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
527       return Offsets[I].second;
528   }
529   
530   llvm_unreachable("Should always find a vcall offset offset!");
531 }
532
533 /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
534 class VCallAndVBaseOffsetBuilder {
535 public:
536   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> 
537     VBaseOffsetOffsetsMapTy;
538
539 private:
540   /// MostDerivedClass - The most derived class for which we're building vcall
541   /// and vbase offsets.
542   const CXXRecordDecl *MostDerivedClass;
543   
544   /// LayoutClass - The class we're using for layout information. Will be 
545   /// different than the most derived class if we're building a construction
546   /// vtable.
547   const CXXRecordDecl *LayoutClass;
548   
549   /// Context - The ASTContext which we will use for layout information.
550   ASTContext &Context;
551
552   /// Components - vcall and vbase offset components
553   typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
554   VTableComponentVectorTy Components;
555   
556   /// VisitedVirtualBases - Visited virtual bases.
557   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
558   
559   /// VCallOffsets - Keeps track of vcall offsets.
560   VCallOffsetMap VCallOffsets;
561
562
563   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
564   /// relative to the address point.
565   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
566   
567   /// FinalOverriders - The final overriders of the most derived class.
568   /// (Can be null when we're not building a vtable of the most derived class).
569   const FinalOverriders *Overriders;
570
571   /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
572   /// given base subobject.
573   void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
574                                CharUnits RealBaseOffset);
575   
576   /// AddVCallOffsets - Add vcall offsets for the given base subobject.
577   void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
578   
579   /// AddVBaseOffsets - Add vbase offsets for the given class.
580   void AddVBaseOffsets(const CXXRecordDecl *Base, 
581                        CharUnits OffsetInLayoutClass);
582   
583   /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
584   /// chars, relative to the vtable address point.
585   CharUnits getCurrentOffsetOffset() const;
586   
587 public:
588   VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
589                              const CXXRecordDecl *LayoutClass,
590                              const FinalOverriders *Overriders,
591                              BaseSubobject Base, bool BaseIsVirtual,
592                              CharUnits OffsetInLayoutClass)
593     : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), 
594     Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
595       
596     // Add vcall and vbase offsets.
597     AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
598   }
599   
600   /// Methods for iterating over the components.
601   typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
602   const_iterator components_begin() const { return Components.rbegin(); }
603   const_iterator components_end() const { return Components.rend(); }
604   
605   const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
606   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
607     return VBaseOffsetOffsets;
608   }
609 };
610   
611 void 
612 VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
613                                                     bool BaseIsVirtual,
614                                                     CharUnits RealBaseOffset) {
615   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
616   
617   // Itanium C++ ABI 2.5.2:
618   //   ..in classes sharing a virtual table with a primary base class, the vcall
619   //   and vbase offsets added by the derived class all come before the vcall
620   //   and vbase offsets required by the base class, so that the latter may be
621   //   laid out as required by the base class without regard to additions from
622   //   the derived class(es).
623
624   // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
625   // emit them for the primary base first).
626   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
627     bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
628
629     CharUnits PrimaryBaseOffset;
630     
631     // Get the base offset of the primary base.
632     if (PrimaryBaseIsVirtual) {
633       assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
634              "Primary vbase should have a zero offset!");
635       
636       const ASTRecordLayout &MostDerivedClassLayout =
637         Context.getASTRecordLayout(MostDerivedClass);
638       
639       PrimaryBaseOffset = 
640         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
641     } else {
642       assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
643              "Primary base should have a zero offset!");
644
645       PrimaryBaseOffset = Base.getBaseOffset();
646     }
647
648     AddVCallAndVBaseOffsets(
649       BaseSubobject(PrimaryBase,PrimaryBaseOffset),
650       PrimaryBaseIsVirtual, RealBaseOffset);
651   }
652
653   AddVBaseOffsets(Base.getBase(), RealBaseOffset);
654
655   // We only want to add vcall offsets for virtual bases.
656   if (BaseIsVirtual)
657     AddVCallOffsets(Base, RealBaseOffset);
658 }
659
660 CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
661   // OffsetIndex is the index of this vcall or vbase offset, relative to the 
662   // vtable address point. (We subtract 3 to account for the information just
663   // above the address point, the RTTI info, the offset to top, and the
664   // vcall offset itself).
665   int64_t OffsetIndex = -(int64_t)(3 + Components.size());
666     
667   CharUnits PointerWidth = 
668     Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
669   CharUnits OffsetOffset = PointerWidth * OffsetIndex;
670   return OffsetOffset;
671 }
672
673 void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, 
674                                                  CharUnits VBaseOffset) {
675   const CXXRecordDecl *RD = Base.getBase();
676   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
677
678   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
679
680   // Handle the primary base first.
681   // We only want to add vcall offsets if the base is non-virtual; a virtual
682   // primary base will have its vcall and vbase offsets emitted already.
683   if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
684     // Get the base offset of the primary base.
685     assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
686            "Primary base should have a zero offset!");
687
688     AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
689                     VBaseOffset);
690   }
691   
692   // Add the vcall offsets.
693   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
694        E = RD->method_end(); I != E; ++I) {
695     const CXXMethodDecl *MD = *I;
696     
697     if (!MD->isVirtual())
698       continue;
699
700     CharUnits OffsetOffset = getCurrentOffsetOffset();
701     
702     // Don't add a vcall offset if we already have one for this member function
703     // signature.
704     if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
705       continue;
706
707     CharUnits Offset = CharUnits::Zero();
708
709     if (Overriders) {
710       // Get the final overrider.
711       FinalOverriders::OverriderInfo Overrider = 
712         Overriders->getOverrider(MD, Base.getBaseOffset());
713       
714       /// The vcall offset is the offset from the virtual base to the object 
715       /// where the function was overridden.
716       Offset = Overrider.Offset - VBaseOffset;
717     }
718     
719     Components.push_back(
720       VTableComponent::MakeVCallOffset(Offset));
721   }
722
723   // And iterate over all non-virtual bases (ignoring the primary base).
724   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
725        E = RD->bases_end(); I != E; ++I) {
726   
727     if (I->isVirtual())
728       continue;
729
730     const CXXRecordDecl *BaseDecl =
731       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
732     if (BaseDecl == PrimaryBase)
733       continue;
734
735     // Get the base offset of this base.
736     CharUnits BaseOffset = Base.getBaseOffset() + 
737       Layout.getBaseClassOffset(BaseDecl);
738     
739     AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), 
740                     VBaseOffset);
741   }
742 }
743
744 void 
745 VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
746                                             CharUnits OffsetInLayoutClass) {
747   const ASTRecordLayout &LayoutClassLayout = 
748     Context.getASTRecordLayout(LayoutClass);
749
750   // Add vbase offsets.
751   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
752        E = RD->bases_end(); I != E; ++I) {
753     const CXXRecordDecl *BaseDecl =
754       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
755
756     // Check if this is a virtual base that we haven't visited before.
757     if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
758       CharUnits Offset = 
759         LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
760
761       // Add the vbase offset offset.
762       assert(!VBaseOffsetOffsets.count(BaseDecl) &&
763              "vbase offset offset already exists!");
764
765       CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
766       VBaseOffsetOffsets.insert(
767           std::make_pair(BaseDecl, VBaseOffsetOffset));
768
769       Components.push_back(
770           VTableComponent::MakeVBaseOffset(Offset));
771     }
772
773     // Check the base class looking for more vbase offsets.
774     AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
775   }
776 }
777
778 /// VTableBuilder - Class for building vtable layout information.
779 class VTableBuilder {
780 public:
781   /// PrimaryBasesSetVectorTy - A set vector of direct and indirect 
782   /// primary bases.
783   typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> 
784     PrimaryBasesSetVectorTy;
785   
786   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> 
787     VBaseOffsetOffsetsMapTy;
788   
789   typedef llvm::DenseMap<BaseSubobject, uint64_t> 
790     AddressPointsMapTy;
791
792 private:
793   /// VTables - Global vtable information.
794   VTableContext &VTables;
795   
796   /// MostDerivedClass - The most derived class for which we're building this
797   /// vtable.
798   const CXXRecordDecl *MostDerivedClass;
799
800   /// MostDerivedClassOffset - If we're building a construction vtable, this
801   /// holds the offset from the layout class to the most derived class.
802   const CharUnits MostDerivedClassOffset;
803   
804   /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual 
805   /// base. (This only makes sense when building a construction vtable).
806   bool MostDerivedClassIsVirtual;
807   
808   /// LayoutClass - The class we're using for layout information. Will be 
809   /// different than the most derived class if we're building a construction
810   /// vtable.
811   const CXXRecordDecl *LayoutClass;
812   
813   /// Context - The ASTContext which we will use for layout information.
814   ASTContext &Context;
815   
816   /// FinalOverriders - The final overriders of the most derived class.
817   const FinalOverriders Overriders;
818
819   /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
820   /// bases in this vtable.
821   llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
822
823   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
824   /// the most derived class.
825   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
826   
827   /// Components - The components of the vtable being built.
828   SmallVector<VTableComponent, 64> Components;
829
830   /// AddressPoints - Address points for the vtable being built.
831   AddressPointsMapTy AddressPoints;
832
833   /// MethodInfo - Contains information about a method in a vtable.
834   /// (Used for computing 'this' pointer adjustment thunks.
835   struct MethodInfo {
836     /// BaseOffset - The base offset of this method.
837     const CharUnits BaseOffset;
838     
839     /// BaseOffsetInLayoutClass - The base offset in the layout class of this
840     /// method.
841     const CharUnits BaseOffsetInLayoutClass;
842     
843     /// VTableIndex - The index in the vtable that this method has.
844     /// (For destructors, this is the index of the complete destructor).
845     const uint64_t VTableIndex;
846     
847     MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass, 
848                uint64_t VTableIndex)
849       : BaseOffset(BaseOffset), 
850       BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851       VTableIndex(VTableIndex) { }
852     
853     MethodInfo() 
854       : BaseOffset(CharUnits::Zero()), 
855       BaseOffsetInLayoutClass(CharUnits::Zero()), 
856       VTableIndex(0) { }
857   };
858   
859   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
860   
861   /// MethodInfoMap - The information for all methods in the vtable we're
862   /// currently building.
863   MethodInfoMapTy MethodInfoMap;
864   
865   typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
866   
867   /// VTableThunks - The thunks by vtable index in the vtable currently being 
868   /// built.
869   VTableThunksMapTy VTableThunks;
870
871   typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
872   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
873   
874   /// Thunks - A map that contains all the thunks needed for all methods in the
875   /// most derived class for which the vtable is currently being built.
876   ThunksMapTy Thunks;
877   
878   /// AddThunk - Add a thunk for the given method.
879   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
880   
881   /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
882   /// part of the vtable we're currently building.
883   void ComputeThisAdjustments();
884   
885   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
886
887   /// PrimaryVirtualBases - All known virtual bases who are a primary base of
888   /// some other base.
889   VisitedVirtualBasesSetTy PrimaryVirtualBases;
890
891   /// ComputeReturnAdjustment - Compute the return adjustment given a return
892   /// adjustment base offset.
893   ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
894   
895   /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
896   /// the 'this' pointer from the base subobject to the derived subobject.
897   BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
898                                              BaseSubobject Derived) const;
899
900   /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
901   /// given virtual member function, its offset in the layout class and its
902   /// final overrider.
903   ThisAdjustment 
904   ComputeThisAdjustment(const CXXMethodDecl *MD, 
905                         CharUnits BaseOffsetInLayoutClass,
906                         FinalOverriders::OverriderInfo Overrider);
907
908   /// AddMethod - Add a single virtual member function to the vtable
909   /// components vector.
910   void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
911
912   /// IsOverriderUsed - Returns whether the overrider will ever be used in this
913   /// part of the vtable. 
914   ///
915   /// Itanium C++ ABI 2.5.2:
916   ///
917   ///   struct A { virtual void f(); };
918   ///   struct B : virtual public A { int i; };
919   ///   struct C : virtual public A { int j; };
920   ///   struct D : public B, public C {};
921   ///
922   ///   When B and C are declared, A is a primary base in each case, so although
923   ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
924   ///   adjustment is required and no thunk is generated. However, inside D
925   ///   objects, A is no longer a primary base of C, so if we allowed calls to
926   ///   C::f() to use the copy of A's vtable in the C subobject, we would need
927   ///   to adjust this from C* to B::A*, which would require a third-party 
928   ///   thunk. Since we require that a call to C::f() first convert to A*, 
929   ///   C-in-D's copy of A's vtable is never referenced, so this is not 
930   ///   necessary.
931   bool IsOverriderUsed(const CXXMethodDecl *Overrider,
932                        CharUnits BaseOffsetInLayoutClass,
933                        const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
934                        CharUnits FirstBaseOffsetInLayoutClass) const;
935
936   
937   /// AddMethods - Add the methods of this base subobject and all its
938   /// primary bases to the vtable components vector.
939   void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
940                   const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
941                   CharUnits FirstBaseOffsetInLayoutClass,
942                   PrimaryBasesSetVectorTy &PrimaryBases);
943
944   // LayoutVTable - Layout the vtable for the given base class, including its
945   // secondary vtables and any vtables for virtual bases.
946   void LayoutVTable();
947
948   /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
949   /// given base subobject, as well as all its secondary vtables.
950   ///
951   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
952   /// or a direct or indirect base of a virtual base.
953   ///
954   /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
955   /// in the layout class. 
956   void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
957                                         bool BaseIsMorallyVirtual,
958                                         bool BaseIsVirtualInLayoutClass,
959                                         CharUnits OffsetInLayoutClass);
960   
961   /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
962   /// subobject.
963   ///
964   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
965   /// or a direct or indirect base of a virtual base.
966   void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
967                               CharUnits OffsetInLayoutClass);
968
969   /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
970   /// class hierarchy.
971   void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, 
972                                     CharUnits OffsetInLayoutClass,
973                                     VisitedVirtualBasesSetTy &VBases);
974
975   /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
976   /// given base (excluding any primary bases).
977   void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, 
978                                     VisitedVirtualBasesSetTy &VBases);
979
980   /// isBuildingConstructionVTable - Return whether this vtable builder is
981   /// building a construction vtable.
982   bool isBuildingConstructorVTable() const { 
983     return MostDerivedClass != LayoutClass;
984   }
985
986 public:
987   VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
988                 CharUnits MostDerivedClassOffset, 
989                 bool MostDerivedClassIsVirtual, const 
990                 CXXRecordDecl *LayoutClass)
991     : VTables(VTables), MostDerivedClass(MostDerivedClass),
992     MostDerivedClassOffset(MostDerivedClassOffset), 
993     MostDerivedClassIsVirtual(MostDerivedClassIsVirtual), 
994     LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), 
995     Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
996
997     LayoutVTable();
998
999     if (Context.getLangOptions().DumpVTableLayouts)
1000       dumpLayout(llvm::errs());
1001   }
1002
1003   uint64_t getNumThunks() const {
1004     return Thunks.size();
1005   }
1006
1007   ThunksMapTy::const_iterator thunks_begin() const {
1008     return Thunks.begin();
1009   }
1010
1011   ThunksMapTy::const_iterator thunks_end() const {
1012     return Thunks.end();
1013   }
1014
1015   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1016     return VBaseOffsetOffsets;
1017   }
1018
1019   const AddressPointsMapTy &getAddressPoints() const {
1020     return AddressPoints;
1021   }
1022
1023   /// getNumVTableComponents - Return the number of components in the vtable
1024   /// currently built.
1025   uint64_t getNumVTableComponents() const {
1026     return Components.size();
1027   }
1028
1029   const VTableComponent *vtable_component_begin() const {
1030     return Components.begin();
1031   }
1032   
1033   const VTableComponent *vtable_component_end() const {
1034     return Components.end();
1035   }
1036   
1037   AddressPointsMapTy::const_iterator address_points_begin() const {
1038     return AddressPoints.begin();
1039   }
1040
1041   AddressPointsMapTy::const_iterator address_points_end() const {
1042     return AddressPoints.end();
1043   }
1044
1045   VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1046     return VTableThunks.begin();
1047   }
1048
1049   VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1050     return VTableThunks.end();
1051   }
1052
1053   /// dumpLayout - Dump the vtable layout.
1054   void dumpLayout(raw_ostream&);
1055 };
1056
1057 void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1058   assert(!isBuildingConstructorVTable() && 
1059          "Can't add thunks for construction vtable");
1060
1061   SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1062   
1063   // Check if we have this thunk already.
1064   if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != 
1065       ThunksVector.end())
1066     return;
1067   
1068   ThunksVector.push_back(Thunk);
1069 }
1070
1071 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1072
1073 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1074 /// the overridden methods that the function decl overrides.
1075 static void 
1076 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1077                             OverriddenMethodsSetTy& OverriddenMethods) {
1078   assert(MD->isVirtual() && "Method is not virtual!");
1079
1080   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1081        E = MD->end_overridden_methods(); I != E; ++I) {
1082     const CXXMethodDecl *OverriddenMD = *I;
1083     
1084     OverriddenMethods.insert(OverriddenMD);
1085     
1086     ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1087   }
1088 }
1089
1090 void VTableBuilder::ComputeThisAdjustments() {
1091   // Now go through the method info map and see if any of the methods need
1092   // 'this' pointer adjustments.
1093   for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1094        E = MethodInfoMap.end(); I != E; ++I) {
1095     const CXXMethodDecl *MD = I->first;
1096     const MethodInfo &MethodInfo = I->second;
1097
1098     // Ignore adjustments for unused function pointers.
1099     uint64_t VTableIndex = MethodInfo.VTableIndex;
1100     if (Components[VTableIndex].getKind() == 
1101         VTableComponent::CK_UnusedFunctionPointer)
1102       continue;
1103     
1104     // Get the final overrider for this method.
1105     FinalOverriders::OverriderInfo Overrider =
1106       Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1107     
1108     // Check if we need an adjustment at all.
1109     if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1110       // When a return thunk is needed by a derived class that overrides a
1111       // virtual base, gcc uses a virtual 'this' adjustment as well. 
1112       // While the thunk itself might be needed by vtables in subclasses or
1113       // in construction vtables, there doesn't seem to be a reason for using
1114       // the thunk in this vtable. Still, we do so to match gcc.
1115       if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1116         continue;
1117     }
1118
1119     ThisAdjustment ThisAdjustment =
1120       ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1121
1122     if (ThisAdjustment.isEmpty())
1123       continue;
1124
1125     // Add it.
1126     VTableThunks[VTableIndex].This = ThisAdjustment;
1127
1128     if (isa<CXXDestructorDecl>(MD)) {
1129       // Add an adjustment for the deleting destructor as well.
1130       VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1131     }
1132   }
1133
1134   /// Clear the method info map.
1135   MethodInfoMap.clear();
1136   
1137   if (isBuildingConstructorVTable()) {
1138     // We don't need to store thunk information for construction vtables.
1139     return;
1140   }
1141
1142   for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1143        E = VTableThunks.end(); I != E; ++I) {
1144     const VTableComponent &Component = Components[I->first];
1145     const ThunkInfo &Thunk = I->second;
1146     const CXXMethodDecl *MD;
1147     
1148     switch (Component.getKind()) {
1149     default:
1150       llvm_unreachable("Unexpected vtable component kind!");
1151     case VTableComponent::CK_FunctionPointer:
1152       MD = Component.getFunctionDecl();
1153       break;
1154     case VTableComponent::CK_CompleteDtorPointer:
1155       MD = Component.getDestructorDecl();
1156       break;
1157     case VTableComponent::CK_DeletingDtorPointer:
1158       // We've already added the thunk when we saw the complete dtor pointer.
1159       continue;
1160     }
1161
1162     if (MD->getParent() == MostDerivedClass)
1163       AddThunk(MD, Thunk);
1164   }
1165 }
1166
1167 ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1168   ReturnAdjustment Adjustment;
1169   
1170   if (!Offset.isEmpty()) {
1171     if (Offset.VirtualBase) {
1172       // Get the virtual base offset offset.
1173       if (Offset.DerivedClass == MostDerivedClass) {
1174         // We can get the offset offset directly from our map.
1175         Adjustment.VBaseOffsetOffset = 
1176           VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1177       } else {
1178         Adjustment.VBaseOffsetOffset = 
1179           VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1180                                              Offset.VirtualBase).getQuantity();
1181       }
1182     }
1183
1184     Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1185   }
1186   
1187   return Adjustment;
1188 }
1189
1190 BaseOffset
1191 VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1192                                                BaseSubobject Derived) const {
1193   const CXXRecordDecl *BaseRD = Base.getBase();
1194   const CXXRecordDecl *DerivedRD = Derived.getBase();
1195   
1196   CXXBasePaths Paths(/*FindAmbiguities=*/true,
1197                      /*RecordPaths=*/true, /*DetectVirtual=*/true);
1198
1199   if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1200       isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1201     llvm_unreachable("Class must be derived from the passed in base class!");
1202   }
1203
1204   // We have to go through all the paths, and see which one leads us to the
1205   // right base subobject.
1206   for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1207        I != E; ++I) {
1208     BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1209     
1210     CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1211     
1212     if (Offset.VirtualBase) {
1213       // If we have a virtual base class, the non-virtual offset is relative
1214       // to the virtual base class offset.
1215       const ASTRecordLayout &LayoutClassLayout =
1216         Context.getASTRecordLayout(LayoutClass);
1217       
1218       /// Get the virtual base offset, relative to the most derived class 
1219       /// layout.
1220       OffsetToBaseSubobject += 
1221         LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1222     } else {
1223       // Otherwise, the non-virtual offset is relative to the derived class 
1224       // offset.
1225       OffsetToBaseSubobject += Derived.getBaseOffset();
1226     }
1227     
1228     // Check if this path gives us the right base subobject.
1229     if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1230       // Since we're going from the base class _to_ the derived class, we'll
1231       // invert the non-virtual offset here.
1232       Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1233       return Offset;
1234     }      
1235   }
1236   
1237   return BaseOffset();
1238 }
1239   
1240 ThisAdjustment 
1241 VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD, 
1242                                      CharUnits BaseOffsetInLayoutClass,
1243                                      FinalOverriders::OverriderInfo Overrider) {
1244   // Ignore adjustments for pure virtual member functions.
1245   if (Overrider.Method->isPure())
1246     return ThisAdjustment();
1247   
1248   BaseSubobject OverriddenBaseSubobject(MD->getParent(), 
1249                                         BaseOffsetInLayoutClass);
1250   
1251   BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1252                                        Overrider.Offset);
1253   
1254   // Compute the adjustment offset.
1255   BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1256                                                       OverriderBaseSubobject);
1257   if (Offset.isEmpty())
1258     return ThisAdjustment();
1259
1260   ThisAdjustment Adjustment;
1261   
1262   if (Offset.VirtualBase) {
1263     // Get the vcall offset map for this virtual base.
1264     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1265
1266     if (VCallOffsets.empty()) {
1267       // We don't have vcall offsets for this virtual base, go ahead and
1268       // build them.
1269       VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1270                                          /*FinalOverriders=*/0,
1271                                          BaseSubobject(Offset.VirtualBase,
1272                                                        CharUnits::Zero()),
1273                                          /*BaseIsVirtual=*/true,
1274                                          /*OffsetInLayoutClass=*/
1275                                              CharUnits::Zero());
1276         
1277       VCallOffsets = Builder.getVCallOffsets();
1278     }
1279       
1280     Adjustment.VCallOffsetOffset = 
1281       VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1282   }
1283
1284   // Set the non-virtual part of the adjustment.
1285   Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1286   
1287   return Adjustment;
1288 }
1289   
1290 void 
1291 VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1292                          ReturnAdjustment ReturnAdjustment) {
1293   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1294     assert(ReturnAdjustment.isEmpty() && 
1295            "Destructor can't have return adjustment!");
1296
1297     // Add both the complete destructor and the deleting destructor.
1298     Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1299     Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1300   } else {
1301     // Add the return adjustment if necessary.
1302     if (!ReturnAdjustment.isEmpty())
1303       VTableThunks[Components.size()].Return = ReturnAdjustment;
1304
1305     // Add the function.
1306     Components.push_back(VTableComponent::MakeFunction(MD));
1307   }
1308 }
1309
1310 /// OverridesIndirectMethodInBase - Return whether the given member function
1311 /// overrides any methods in the set of given bases. 
1312 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1313 /// For example, if we have:
1314 ///
1315 /// struct A { virtual void f(); }
1316 /// struct B : A { virtual void f(); }
1317 /// struct C : B { virtual void f(); }
1318 ///
1319 /// OverridesIndirectMethodInBase will return true if given C::f as the method 
1320 /// and { A } as the set of bases.
1321 static bool
1322 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1323                                VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1324   if (Bases.count(MD->getParent()))
1325     return true;
1326   
1327   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1328        E = MD->end_overridden_methods(); I != E; ++I) {
1329     const CXXMethodDecl *OverriddenMD = *I;
1330     
1331     // Check "indirect overriders".
1332     if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1333       return true;
1334   }
1335    
1336   return false;
1337 }
1338
1339 bool 
1340 VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1341                                CharUnits BaseOffsetInLayoutClass,
1342                                const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1343                                CharUnits FirstBaseOffsetInLayoutClass) const {
1344   // If the base and the first base in the primary base chain have the same
1345   // offsets, then this overrider will be used.
1346   if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1347    return true;
1348
1349   // We know now that Base (or a direct or indirect base of it) is a primary
1350   // base in part of the class hierarchy, but not a primary base in the most 
1351   // derived class.
1352   
1353   // If the overrider is the first base in the primary base chain, we know
1354   // that the overrider will be used.
1355   if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1356     return true;
1357   
1358   VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1359
1360   const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1361   PrimaryBases.insert(RD);
1362
1363   // Now traverse the base chain, starting with the first base, until we find
1364   // the base that is no longer a primary base.
1365   while (true) {
1366     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1367     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1368     
1369     if (!PrimaryBase)
1370       break;
1371     
1372     if (Layout.isPrimaryBaseVirtual()) {
1373       assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 && 
1374              "Primary base should always be at offset 0!");
1375
1376       const ASTRecordLayout &LayoutClassLayout =
1377         Context.getASTRecordLayout(LayoutClass);
1378
1379       // Now check if this is the primary base that is not a primary base in the
1380       // most derived class.
1381       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1382           FirstBaseOffsetInLayoutClass) {
1383         // We found it, stop walking the chain.
1384         break;
1385       }
1386     } else {
1387       assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 && 
1388              "Primary base should always be at offset 0!");
1389     }
1390     
1391     if (!PrimaryBases.insert(PrimaryBase))
1392       llvm_unreachable("Found a duplicate primary base!");
1393
1394     RD = PrimaryBase;
1395   }
1396   
1397   // If the final overrider is an override of one of the primary bases,
1398   // then we know that it will be used.
1399   return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1400 }
1401
1402 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1403 /// from the nearest base. Returns null if no method was found.
1404 static const CXXMethodDecl * 
1405 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1406                             VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1407   OverriddenMethodsSetTy OverriddenMethods;
1408   ComputeAllOverriddenMethods(MD, OverriddenMethods);
1409   
1410   for (int I = Bases.size(), E = 0; I != E; --I) {
1411     const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1412
1413     // Now check the overriden methods.
1414     for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1415          E = OverriddenMethods.end(); I != E; ++I) {
1416       const CXXMethodDecl *OverriddenMD = *I;
1417       
1418       // We found our overridden method.
1419       if (OverriddenMD->getParent() == PrimaryBase)
1420         return OverriddenMD;
1421     }
1422   }
1423   
1424   return 0;
1425 }  
1426
1427 void
1428 VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1429                           const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1430                           CharUnits FirstBaseOffsetInLayoutClass,
1431                           PrimaryBasesSetVectorTy &PrimaryBases) {
1432   const CXXRecordDecl *RD = Base.getBase();
1433   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1434
1435   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1436     CharUnits PrimaryBaseOffset;
1437     CharUnits PrimaryBaseOffsetInLayoutClass;
1438     if (Layout.isPrimaryBaseVirtual()) {
1439       assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1440              "Primary vbase should have a zero offset!");
1441       
1442       const ASTRecordLayout &MostDerivedClassLayout =
1443         Context.getASTRecordLayout(MostDerivedClass);
1444       
1445       PrimaryBaseOffset = 
1446         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1447       
1448       const ASTRecordLayout &LayoutClassLayout =
1449         Context.getASTRecordLayout(LayoutClass);
1450
1451       PrimaryBaseOffsetInLayoutClass =
1452         LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1453     } else {
1454       assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1455              "Primary base should have a zero offset!");
1456
1457       PrimaryBaseOffset = Base.getBaseOffset();
1458       PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1459     }
1460
1461     AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1462                PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, 
1463                FirstBaseOffsetInLayoutClass, PrimaryBases);
1464     
1465     if (!PrimaryBases.insert(PrimaryBase))
1466       llvm_unreachable("Found a duplicate primary base!");
1467   }
1468
1469   // Now go through all virtual member functions and add them.
1470   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1471        E = RD->method_end(); I != E; ++I) {
1472     const CXXMethodDecl *MD = *I;
1473   
1474     if (!MD->isVirtual())
1475       continue;
1476
1477     // Get the final overrider.
1478     FinalOverriders::OverriderInfo Overrider = 
1479       Overriders.getOverrider(MD, Base.getBaseOffset());
1480
1481     // Check if this virtual member function overrides a method in a primary
1482     // base. If this is the case, and the return type doesn't require adjustment
1483     // then we can just use the member function from the primary base.
1484     if (const CXXMethodDecl *OverriddenMD = 
1485           FindNearestOverriddenMethod(MD, PrimaryBases)) {
1486       if (ComputeReturnAdjustmentBaseOffset(Context, MD, 
1487                                             OverriddenMD).isEmpty()) {
1488         // Replace the method info of the overridden method with our own
1489         // method.
1490         assert(MethodInfoMap.count(OverriddenMD) && 
1491                "Did not find the overridden method!");
1492         MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1493         
1494         MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1495                               OverriddenMethodInfo.VTableIndex);
1496
1497         assert(!MethodInfoMap.count(MD) &&
1498                "Should not have method info for this method yet!");
1499         
1500         MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1501         MethodInfoMap.erase(OverriddenMD);
1502         
1503         // If the overridden method exists in a virtual base class or a direct
1504         // or indirect base class of a virtual base class, we need to emit a
1505         // thunk if we ever have a class hierarchy where the base class is not
1506         // a primary base in the complete object.
1507         if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1508           // Compute the this adjustment.
1509           ThisAdjustment ThisAdjustment =
1510             ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1511                                   Overrider);
1512
1513           if (ThisAdjustment.VCallOffsetOffset &&
1514               Overrider.Method->getParent() == MostDerivedClass) {
1515
1516             // There's no return adjustment from OverriddenMD and MD,
1517             // but that doesn't mean there isn't one between MD and
1518             // the final overrider.
1519             BaseOffset ReturnAdjustmentOffset =
1520               ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1521             ReturnAdjustment ReturnAdjustment = 
1522               ComputeReturnAdjustment(ReturnAdjustmentOffset);
1523
1524             // This is a virtual thunk for the most derived class, add it.
1525             AddThunk(Overrider.Method, 
1526                      ThunkInfo(ThisAdjustment, ReturnAdjustment));
1527           }
1528         }
1529
1530         continue;
1531       }
1532     }
1533
1534     // Insert the method info for this method.
1535     MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1536                           Components.size());
1537
1538     assert(!MethodInfoMap.count(MD) &&
1539            "Should not have method info for this method yet!");
1540     MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1541
1542     // Check if this overrider is going to be used.
1543     const CXXMethodDecl *OverriderMD = Overrider.Method;
1544     if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1545                          FirstBaseInPrimaryBaseChain, 
1546                          FirstBaseOffsetInLayoutClass)) {
1547       Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1548       continue;
1549     }
1550     
1551     // Check if this overrider needs a return adjustment.
1552     // We don't want to do this for pure virtual member functions.
1553     BaseOffset ReturnAdjustmentOffset;
1554     if (!OverriderMD->isPure()) {
1555       ReturnAdjustmentOffset = 
1556         ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1557     }
1558
1559     ReturnAdjustment ReturnAdjustment = 
1560       ComputeReturnAdjustment(ReturnAdjustmentOffset);
1561     
1562     AddMethod(Overrider.Method, ReturnAdjustment);
1563   }
1564 }
1565
1566 void VTableBuilder::LayoutVTable() {
1567   LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1568                                                  CharUnits::Zero()),
1569                                    /*BaseIsMorallyVirtual=*/false,
1570                                    MostDerivedClassIsVirtual,
1571                                    MostDerivedClassOffset);
1572   
1573   VisitedVirtualBasesSetTy VBases;
1574   
1575   // Determine the primary virtual bases.
1576   DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset, 
1577                                VBases);
1578   VBases.clear();
1579   
1580   LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1581
1582   // -fapple-kext adds an extra entry at end of vtbl.
1583   bool IsAppleKext = Context.getLangOptions().AppleKext;
1584   if (IsAppleKext)
1585     Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1586 }
1587   
1588 void
1589 VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1590                                                 bool BaseIsMorallyVirtual,
1591                                                 bool BaseIsVirtualInLayoutClass,
1592                                                 CharUnits OffsetInLayoutClass) {
1593   assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1594
1595   // Add vcall and vbase offsets for this vtable.
1596   VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1597                                      Base, BaseIsVirtualInLayoutClass, 
1598                                      OffsetInLayoutClass);
1599   Components.append(Builder.components_begin(), Builder.components_end());
1600   
1601   // Check if we need to add these vcall offsets.
1602   if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1603     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1604     
1605     if (VCallOffsets.empty())
1606       VCallOffsets = Builder.getVCallOffsets();
1607   }
1608
1609   // If we're laying out the most derived class we want to keep track of the
1610   // virtual base class offset offsets.
1611   if (Base.getBase() == MostDerivedClass)
1612     VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1613
1614   // Add the offset to top.
1615   CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1616   Components.push_back(
1617     VTableComponent::MakeOffsetToTop(OffsetToTop));
1618   
1619   // Next, add the RTTI.
1620   Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1621   
1622   uint64_t AddressPoint = Components.size();
1623
1624   // Now go through all virtual member functions and add them.
1625   PrimaryBasesSetVectorTy PrimaryBases;
1626   AddMethods(Base, OffsetInLayoutClass,
1627              Base.getBase(), OffsetInLayoutClass, 
1628              PrimaryBases);
1629
1630   // Compute 'this' pointer adjustments.
1631   ComputeThisAdjustments();
1632
1633   // Add all address points.
1634   const CXXRecordDecl *RD = Base.getBase();
1635   while (true) {
1636     AddressPoints.insert(std::make_pair(
1637       BaseSubobject(RD, OffsetInLayoutClass),
1638       AddressPoint));
1639
1640     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1641     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1642     
1643     if (!PrimaryBase)
1644       break;
1645     
1646     if (Layout.isPrimaryBaseVirtual()) {
1647       // Check if this virtual primary base is a primary base in the layout
1648       // class. If it's not, we don't want to add it.
1649       const ASTRecordLayout &LayoutClassLayout =
1650         Context.getASTRecordLayout(LayoutClass);
1651
1652       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1653           OffsetInLayoutClass) {
1654         // We don't want to add this class (or any of its primary bases).
1655         break;
1656       }
1657     }
1658
1659     RD = PrimaryBase;
1660   }
1661
1662   // Layout secondary vtables.
1663   LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1664 }
1665
1666 void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1667                                            bool BaseIsMorallyVirtual,
1668                                            CharUnits OffsetInLayoutClass) {
1669   // Itanium C++ ABI 2.5.2:
1670   //   Following the primary virtual table of a derived class are secondary 
1671   //   virtual tables for each of its proper base classes, except any primary
1672   //   base(s) with which it shares its primary virtual table.
1673
1674   const CXXRecordDecl *RD = Base.getBase();
1675   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1676   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1677   
1678   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1679        E = RD->bases_end(); I != E; ++I) {
1680     // Ignore virtual bases, we'll emit them later.
1681     if (I->isVirtual())
1682       continue;
1683     
1684     const CXXRecordDecl *BaseDecl = 
1685       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1686
1687     // Ignore bases that don't have a vtable.
1688     if (!BaseDecl->isDynamicClass())
1689       continue;
1690
1691     if (isBuildingConstructorVTable()) {
1692       // Itanium C++ ABI 2.6.4:
1693       //   Some of the base class subobjects may not need construction virtual
1694       //   tables, which will therefore not be present in the construction
1695       //   virtual table group, even though the subobject virtual tables are
1696       //   present in the main virtual table group for the complete object.
1697       if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1698         continue;
1699     }
1700
1701     // Get the base offset of this base.
1702     CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1703     CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1704     
1705     CharUnits BaseOffsetInLayoutClass = 
1706       OffsetInLayoutClass + RelativeBaseOffset;
1707     
1708     // Don't emit a secondary vtable for a primary base. We might however want 
1709     // to emit secondary vtables for other bases of this base.
1710     if (BaseDecl == PrimaryBase) {
1711       LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1712                              BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1713       continue;
1714     }
1715
1716     // Layout the primary vtable (and any secondary vtables) for this base.
1717     LayoutPrimaryAndSecondaryVTables(
1718       BaseSubobject(BaseDecl, BaseOffset),
1719       BaseIsMorallyVirtual,
1720       /*BaseIsVirtualInLayoutClass=*/false,
1721       BaseOffsetInLayoutClass);
1722   }
1723 }
1724
1725 void
1726 VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1727                                             CharUnits OffsetInLayoutClass,
1728                                             VisitedVirtualBasesSetTy &VBases) {
1729   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1730   
1731   // Check if this base has a primary base.
1732   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1733
1734     // Check if it's virtual.
1735     if (Layout.isPrimaryBaseVirtual()) {
1736       bool IsPrimaryVirtualBase = true;
1737
1738       if (isBuildingConstructorVTable()) {
1739         // Check if the base is actually a primary base in the class we use for
1740         // layout.
1741         const ASTRecordLayout &LayoutClassLayout =
1742           Context.getASTRecordLayout(LayoutClass);
1743
1744         CharUnits PrimaryBaseOffsetInLayoutClass =
1745           LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1746         
1747         // We know that the base is not a primary base in the layout class if 
1748         // the base offsets are different.
1749         if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1750           IsPrimaryVirtualBase = false;
1751       }
1752         
1753       if (IsPrimaryVirtualBase)
1754         PrimaryVirtualBases.insert(PrimaryBase);
1755     }
1756   }
1757
1758   // Traverse bases, looking for more primary virtual bases.
1759   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1760        E = RD->bases_end(); I != E; ++I) {
1761     const CXXRecordDecl *BaseDecl = 
1762       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1763
1764     CharUnits BaseOffsetInLayoutClass;
1765     
1766     if (I->isVirtual()) {
1767       if (!VBases.insert(BaseDecl))
1768         continue;
1769       
1770       const ASTRecordLayout &LayoutClassLayout =
1771         Context.getASTRecordLayout(LayoutClass);
1772
1773       BaseOffsetInLayoutClass = 
1774         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1775     } else {
1776       BaseOffsetInLayoutClass = 
1777         OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1778     }
1779
1780     DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1781   }
1782 }
1783
1784 void
1785 VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, 
1786                                             VisitedVirtualBasesSetTy &VBases) {
1787   // Itanium C++ ABI 2.5.2:
1788   //   Then come the virtual base virtual tables, also in inheritance graph
1789   //   order, and again excluding primary bases (which share virtual tables with
1790   //   the classes for which they are primary).
1791   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1792        E = RD->bases_end(); I != E; ++I) {
1793     const CXXRecordDecl *BaseDecl = 
1794       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1795
1796     // Check if this base needs a vtable. (If it's virtual, not a primary base
1797     // of some other class, and we haven't visited it before).
1798     if (I->isVirtual() && BaseDecl->isDynamicClass() && 
1799         !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1800       const ASTRecordLayout &MostDerivedClassLayout =
1801         Context.getASTRecordLayout(MostDerivedClass);
1802       CharUnits BaseOffset = 
1803         MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1804       
1805       const ASTRecordLayout &LayoutClassLayout =
1806         Context.getASTRecordLayout(LayoutClass);
1807       CharUnits BaseOffsetInLayoutClass = 
1808         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1809
1810       LayoutPrimaryAndSecondaryVTables(
1811         BaseSubobject(BaseDecl, BaseOffset),
1812         /*BaseIsMorallyVirtual=*/true,
1813         /*BaseIsVirtualInLayoutClass=*/true,
1814         BaseOffsetInLayoutClass);
1815     }
1816     
1817     // We only need to check the base for virtual base vtables if it actually
1818     // has virtual bases.
1819     if (BaseDecl->getNumVBases())
1820       LayoutVTablesForVirtualBases(BaseDecl, VBases);
1821   }
1822 }
1823
1824 /// dumpLayout - Dump the vtable layout.
1825 void VTableBuilder::dumpLayout(raw_ostream& Out) {
1826
1827   if (isBuildingConstructorVTable()) {
1828     Out << "Construction vtable for ('";
1829     Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1830     Out << MostDerivedClassOffset.getQuantity() << ") in '";
1831     Out << LayoutClass->getQualifiedNameAsString();
1832   } else {
1833     Out << "Vtable for '";
1834     Out << MostDerivedClass->getQualifiedNameAsString();
1835   }
1836   Out << "' (" << Components.size() << " entries).\n";
1837
1838   // Iterate through the address points and insert them into a new map where
1839   // they are keyed by the index and not the base object.
1840   // Since an address point can be shared by multiple subobjects, we use an
1841   // STL multimap.
1842   std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1843   for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(), 
1844        E = AddressPoints.end(); I != E; ++I) {
1845     const BaseSubobject& Base = I->first;
1846     uint64_t Index = I->second;
1847     
1848     AddressPointsByIndex.insert(std::make_pair(Index, Base));
1849   }
1850   
1851   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1852     uint64_t Index = I;
1853
1854     Out << llvm::format("%4d | ", I);
1855
1856     const VTableComponent &Component = Components[I];
1857
1858     // Dump the component.
1859     switch (Component.getKind()) {
1860
1861     case VTableComponent::CK_VCallOffset:
1862       Out << "vcall_offset ("
1863           << Component.getVCallOffset().getQuantity() 
1864           << ")";
1865       break;
1866
1867     case VTableComponent::CK_VBaseOffset:
1868       Out << "vbase_offset ("
1869           << Component.getVBaseOffset().getQuantity()
1870           << ")";
1871       break;
1872
1873     case VTableComponent::CK_OffsetToTop:
1874       Out << "offset_to_top ("
1875           << Component.getOffsetToTop().getQuantity()
1876           << ")";
1877       break;
1878     
1879     case VTableComponent::CK_RTTI:
1880       Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1881       break;
1882     
1883     case VTableComponent::CK_FunctionPointer: {
1884       const CXXMethodDecl *MD = Component.getFunctionDecl();
1885
1886       std::string Str = 
1887         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 
1888                                     MD);
1889       Out << Str;
1890       if (MD->isPure())
1891         Out << " [pure]";
1892
1893       ThunkInfo Thunk = VTableThunks.lookup(I);
1894       if (!Thunk.isEmpty()) {
1895         // If this function pointer has a return adjustment, dump it.
1896         if (!Thunk.Return.isEmpty()) {
1897           Out << "\n       [return adjustment: ";
1898           Out << Thunk.Return.NonVirtual << " non-virtual";
1899           
1900           if (Thunk.Return.VBaseOffsetOffset) {
1901             Out << ", " << Thunk.Return.VBaseOffsetOffset;
1902             Out << " vbase offset offset";
1903           }
1904
1905           Out << ']';
1906         }
1907
1908         // If this function pointer has a 'this' pointer adjustment, dump it.
1909         if (!Thunk.This.isEmpty()) {
1910           Out << "\n       [this adjustment: ";
1911           Out << Thunk.This.NonVirtual << " non-virtual";
1912           
1913           if (Thunk.This.VCallOffsetOffset) {
1914             Out << ", " << Thunk.This.VCallOffsetOffset;
1915             Out << " vcall offset offset";
1916           }
1917
1918           Out << ']';
1919         }          
1920       }
1921
1922       break;
1923     }
1924
1925     case VTableComponent::CK_CompleteDtorPointer: 
1926     case VTableComponent::CK_DeletingDtorPointer: {
1927       bool IsComplete = 
1928         Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1929       
1930       const CXXDestructorDecl *DD = Component.getDestructorDecl();
1931       
1932       Out << DD->getQualifiedNameAsString();
1933       if (IsComplete)
1934         Out << "() [complete]";
1935       else
1936         Out << "() [deleting]";
1937
1938       if (DD->isPure())
1939         Out << " [pure]";
1940
1941       ThunkInfo Thunk = VTableThunks.lookup(I);
1942       if (!Thunk.isEmpty()) {
1943         // If this destructor has a 'this' pointer adjustment, dump it.
1944         if (!Thunk.This.isEmpty()) {
1945           Out << "\n       [this adjustment: ";
1946           Out << Thunk.This.NonVirtual << " non-virtual";
1947           
1948           if (Thunk.This.VCallOffsetOffset) {
1949             Out << ", " << Thunk.This.VCallOffsetOffset;
1950             Out << " vcall offset offset";
1951           }
1952           
1953           Out << ']';
1954         }          
1955       }        
1956
1957       break;
1958     }
1959
1960     case VTableComponent::CK_UnusedFunctionPointer: {
1961       const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1962
1963       std::string Str = 
1964         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 
1965                                     MD);
1966       Out << "[unused] " << Str;
1967       if (MD->isPure())
1968         Out << " [pure]";
1969     }
1970
1971     }
1972
1973     Out << '\n';
1974     
1975     // Dump the next address point.
1976     uint64_t NextIndex = Index + 1;
1977     if (AddressPointsByIndex.count(NextIndex)) {
1978       if (AddressPointsByIndex.count(NextIndex) == 1) {
1979         const BaseSubobject &Base = 
1980           AddressPointsByIndex.find(NextIndex)->second;
1981         
1982         Out << "       -- (" << Base.getBase()->getQualifiedNameAsString();
1983         Out << ", " << Base.getBaseOffset().getQuantity();
1984         Out << ") vtable address --\n";
1985       } else {
1986         CharUnits BaseOffset =
1987           AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
1988         
1989         // We store the class names in a set to get a stable order.
1990         std::set<std::string> ClassNames;
1991         for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
1992              AddressPointsByIndex.lower_bound(NextIndex), E =
1993              AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
1994           assert(I->second.getBaseOffset() == BaseOffset &&
1995                  "Invalid base offset!");
1996           const CXXRecordDecl *RD = I->second.getBase();
1997           ClassNames.insert(RD->getQualifiedNameAsString());
1998         }
1999         
2000         for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2001              E = ClassNames.end(); I != E; ++I) {
2002           Out << "       -- (" << *I;
2003           Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2004         }
2005       }
2006     }
2007   }
2008
2009   Out << '\n';
2010   
2011   if (isBuildingConstructorVTable())
2012     return;
2013   
2014   if (MostDerivedClass->getNumVBases()) {
2015     // We store the virtual base class names and their offsets in a map to get
2016     // a stable order.
2017
2018     std::map<std::string, CharUnits> ClassNamesAndOffsets;
2019     for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2020          E = VBaseOffsetOffsets.end(); I != E; ++I) {
2021       std::string ClassName = I->first->getQualifiedNameAsString();
2022       CharUnits OffsetOffset = I->second;
2023       ClassNamesAndOffsets.insert(
2024           std::make_pair(ClassName, OffsetOffset));
2025     }
2026     
2027     Out << "Virtual base offset offsets for '";
2028     Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2029     Out << ClassNamesAndOffsets.size();
2030     Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2031
2032     for (std::map<std::string, CharUnits>::const_iterator I =
2033          ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end(); 
2034          I != E; ++I)
2035       Out << "   " << I->first << " | " << I->second.getQuantity() << '\n';
2036
2037     Out << "\n";
2038   }
2039   
2040   if (!Thunks.empty()) {
2041     // We store the method names in a map to get a stable order.
2042     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2043     
2044     for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2045          I != E; ++I) {
2046       const CXXMethodDecl *MD = I->first;
2047       std::string MethodName = 
2048         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2049                                     MD);
2050       
2051       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2052     }
2053
2054     for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2055          MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end(); 
2056          I != E; ++I) {
2057       const std::string &MethodName = I->first;
2058       const CXXMethodDecl *MD = I->second;
2059
2060       ThunkInfoVectorTy ThunksVector = Thunks[MD];
2061       std::sort(ThunksVector.begin(), ThunksVector.end());
2062
2063       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2064       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2065       
2066       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2067         const ThunkInfo &Thunk = ThunksVector[I];
2068
2069         Out << llvm::format("%4d | ", I);
2070         
2071         // If this function pointer has a return pointer adjustment, dump it.
2072         if (!Thunk.Return.isEmpty()) {
2073           Out << "return adjustment: " << Thunk.This.NonVirtual;
2074           Out << " non-virtual";
2075           if (Thunk.Return.VBaseOffsetOffset) {
2076             Out << ", " << Thunk.Return.VBaseOffsetOffset;
2077             Out << " vbase offset offset";
2078           }
2079
2080           if (!Thunk.This.isEmpty())
2081             Out << "\n       ";
2082         }
2083
2084         // If this function pointer has a 'this' pointer adjustment, dump it.
2085         if (!Thunk.This.isEmpty()) {
2086           Out << "this adjustment: ";
2087           Out << Thunk.This.NonVirtual << " non-virtual";
2088           
2089           if (Thunk.This.VCallOffsetOffset) {
2090             Out << ", " << Thunk.This.VCallOffsetOffset;
2091             Out << " vcall offset offset";
2092           }
2093         }
2094         
2095         Out << '\n';
2096       }
2097       
2098       Out << '\n';
2099     }
2100   }
2101
2102   // Compute the vtable indices for all the member functions.
2103   // Store them in a map keyed by the index so we'll get a sorted table.
2104   std::map<uint64_t, std::string> IndicesMap;
2105
2106   for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2107        e = MostDerivedClass->method_end(); i != e; ++i) {
2108     const CXXMethodDecl *MD = *i;
2109     
2110     // We only want virtual member functions.
2111     if (!MD->isVirtual())
2112       continue;
2113
2114     std::string MethodName =
2115       PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2116                                   MD);
2117
2118     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2119       IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))] =
2120         MethodName + " [complete]";
2121       IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))] =
2122         MethodName + " [deleting]";
2123     } else {
2124       IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
2125     }
2126   }
2127
2128   // Print the vtable indices for all the member functions.
2129   if (!IndicesMap.empty()) {
2130     Out << "VTable indices for '";
2131     Out << MostDerivedClass->getQualifiedNameAsString();
2132     Out << "' (" << IndicesMap.size() << " entries).\n";
2133
2134     for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2135          E = IndicesMap.end(); I != E; ++I) {
2136       uint64_t VTableIndex = I->first;
2137       const std::string &MethodName = I->second;
2138
2139       Out << llvm::format(" %4u | ", VTableIndex) << MethodName << '\n';
2140     }
2141   }
2142
2143   Out << '\n';
2144 }
2145   
2146 }
2147
2148 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2149                            const VTableComponent *VTableComponents,
2150                            uint64_t NumVTableThunks,
2151                            const VTableThunkTy *VTableThunks,
2152                            const AddressPointsMapTy &AddressPoints)
2153   : NumVTableComponents(NumVTableComponents),
2154     VTableComponents(new VTableComponent[NumVTableComponents]),
2155     NumVTableThunks(NumVTableThunks),
2156     VTableThunks(new VTableThunkTy[NumVTableThunks]),
2157     AddressPoints(AddressPoints) {
2158   std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2159             this->VTableComponents);
2160   std::copy(VTableThunks, VTableThunks+NumVTableThunks, this->VTableThunks);
2161 }
2162
2163 VTableLayout::~VTableLayout() {
2164   delete[] VTableComponents;
2165 }
2166
2167 VTableContext::~VTableContext() {
2168   llvm::DeleteContainerSeconds(VTableLayouts);
2169 }
2170
2171 static void 
2172 CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2173                     VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2174   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2175   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2176
2177   if (!PrimaryBase)
2178     return;
2179
2180   CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2181
2182   if (!PrimaryBases.insert(PrimaryBase))
2183     llvm_unreachable("Found a duplicate primary base!");
2184 }
2185
2186 void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2187   
2188   // Itanium C++ ABI 2.5.2:
2189   //   The order of the virtual function pointers in a virtual table is the 
2190   //   order of declaration of the corresponding member functions in the class.
2191   //
2192   //   There is an entry for any virtual function declared in a class, 
2193   //   whether it is a new function or overrides a base class function, 
2194   //   unless it overrides a function from the primary base, and conversion
2195   //   between their return types does not require an adjustment. 
2196
2197   int64_t CurrentIndex = 0;
2198   
2199   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2200   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2201   
2202   if (PrimaryBase) {
2203     assert(PrimaryBase->isCompleteDefinition() && 
2204            "Should have the definition decl of the primary base!");
2205
2206     // Since the record decl shares its vtable pointer with the primary base
2207     // we need to start counting at the end of the primary base's vtable.
2208     CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2209   }
2210
2211   // Collect all the primary bases, so we can check whether methods override
2212   // a method from the base.
2213   VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2214   CollectPrimaryBases(RD, Context, PrimaryBases);
2215
2216   const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2217   
2218   for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2219        e = RD->method_end(); i != e; ++i) {
2220     const CXXMethodDecl *MD = *i;
2221
2222     // We only want virtual methods.
2223     if (!MD->isVirtual())
2224       continue;
2225
2226     // Check if this method overrides a method in the primary base.
2227     if (const CXXMethodDecl *OverriddenMD = 
2228           FindNearestOverriddenMethod(MD, PrimaryBases)) {
2229       // Check if converting from the return type of the method to the 
2230       // return type of the overridden method requires conversion.
2231       if (ComputeReturnAdjustmentBaseOffset(Context, MD, 
2232                                             OverriddenMD).isEmpty()) {
2233         // This index is shared between the index in the vtable of the primary
2234         // base class.
2235         if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2236           const CXXDestructorDecl *OverriddenDD = 
2237             cast<CXXDestructorDecl>(OverriddenMD);
2238           
2239           // Add both the complete and deleting entries.
2240           MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = 
2241             getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2242           MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = 
2243             getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2244         } else {
2245           MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2246         }
2247         
2248         // We don't need to add an entry for this method.
2249         continue;
2250       }
2251     }
2252     
2253     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2254       if (MD->isImplicit()) {
2255         assert(!ImplicitVirtualDtor && 
2256                "Did already see an implicit virtual dtor!");
2257         ImplicitVirtualDtor = DD;
2258         continue;
2259       } 
2260
2261       // Add the complete dtor.
2262       MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2263       
2264       // Add the deleting dtor.
2265       MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2266     } else {
2267       // Add the entry.
2268       MethodVTableIndices[MD] = CurrentIndex++;
2269     }
2270   }
2271
2272   if (ImplicitVirtualDtor) {
2273     // Itanium C++ ABI 2.5.2:
2274     //   If a class has an implicitly-defined virtual destructor, 
2275     //   its entries come after the declared virtual function pointers.
2276
2277     // Add the complete dtor.
2278     MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] = 
2279       CurrentIndex++;
2280     
2281     // Add the deleting dtor.
2282     MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] = 
2283       CurrentIndex++;
2284   }
2285   
2286   NumVirtualFunctionPointers[RD] = CurrentIndex;
2287 }
2288
2289 uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2290   llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I = 
2291     NumVirtualFunctionPointers.find(RD);
2292   if (I != NumVirtualFunctionPointers.end())
2293     return I->second;
2294
2295   ComputeMethodVTableIndices(RD);
2296
2297   I = NumVirtualFunctionPointers.find(RD);
2298   assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2299   return I->second;
2300 }
2301       
2302 uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2303   MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2304   if (I != MethodVTableIndices.end())
2305     return I->second;
2306   
2307   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2308
2309   ComputeMethodVTableIndices(RD);
2310
2311   I = MethodVTableIndices.find(GD);
2312   assert(I != MethodVTableIndices.end() && "Did not find index!");
2313   return I->second;
2314 }
2315
2316 CharUnits 
2317 VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, 
2318                                           const CXXRecordDecl *VBase) {
2319   ClassPairTy ClassPair(RD, VBase);
2320   
2321   VirtualBaseClassOffsetOffsetsMapTy::iterator I = 
2322     VirtualBaseClassOffsetOffsets.find(ClassPair);
2323   if (I != VirtualBaseClassOffsetOffsets.end())
2324     return I->second;
2325   
2326   VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2327                                      BaseSubobject(RD, CharUnits::Zero()),
2328                                      /*BaseIsVirtual=*/false,
2329                                      /*OffsetInLayoutClass=*/CharUnits::Zero());
2330
2331   for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2332        Builder.getVBaseOffsetOffsets().begin(), 
2333        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2334     // Insert all types.
2335     ClassPairTy ClassPair(RD, I->first);
2336     
2337     VirtualBaseClassOffsetOffsets.insert(
2338         std::make_pair(ClassPair, I->second));
2339   }
2340   
2341   I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2342   assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2343   
2344   return I->second;
2345 }
2346
2347 static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2348   SmallVector<VTableLayout::VTableThunkTy, 1>
2349     VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2350   std::sort(VTableThunks.begin(), VTableThunks.end());
2351
2352   return new VTableLayout(Builder.getNumVTableComponents(),
2353                           Builder.vtable_component_begin(),
2354                           VTableThunks.size(),
2355                           VTableThunks.data(),
2356                           Builder.getAddressPoints());
2357 }
2358
2359 void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2360   const VTableLayout *&Entry = VTableLayouts[RD];
2361
2362   // Check if we've computed this information before.
2363   if (Entry)
2364     return;
2365
2366   VTableBuilder Builder(*this, RD, CharUnits::Zero(), 
2367                         /*MostDerivedClassIsVirtual=*/0, RD);
2368   Entry = CreateVTableLayout(Builder);
2369
2370   // Add the known thunks.
2371   Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2372
2373   // If we don't have the vbase information for this class, insert it.
2374   // getVirtualBaseOffsetOffset will compute it separately without computing
2375   // the rest of the vtable related information.
2376   if (!RD->getNumVBases())
2377     return;
2378   
2379   const RecordType *VBaseRT = 
2380     RD->vbases_begin()->getType()->getAs<RecordType>();
2381   const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2382   
2383   if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2384     return;
2385   
2386   for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2387        Builder.getVBaseOffsetOffsets().begin(), 
2388        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2389     // Insert all types.
2390     ClassPairTy ClassPair(RD, I->first);
2391     
2392     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2393   }
2394 }
2395
2396 VTableLayout *VTableContext::createConstructionVTableLayout(
2397                                           const CXXRecordDecl *MostDerivedClass,
2398                                           CharUnits MostDerivedClassOffset,
2399                                           bool MostDerivedClassIsVirtual,
2400                                           const CXXRecordDecl *LayoutClass) {
2401   VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset, 
2402                         MostDerivedClassIsVirtual, LayoutClass);
2403   return CreateVTableLayout(Builder);
2404 }