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