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/ADT/SmallPtrSet.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 #include <cstdio>
24 
25 using namespace clang;
26 
27 #define DUMP_OVERRIDERS 0
28 
29 namespace {
30 
31 /// BaseOffset - Represents an offset from a derived class to a direct or
32 /// indirect base class.
33 struct BaseOffset {
34   /// DerivedClass - The derived class.
35   const CXXRecordDecl *DerivedClass;
36 
37   /// VirtualBase - If the path from the derived class to the base class
38   /// involves virtual base classes, this holds the declaration of the last
39   /// virtual base in this path (i.e. closest to the base class).
40   const CXXRecordDecl *VirtualBase;
41 
42   /// NonVirtualOffset - The offset from the derived class to the base class.
43   /// (Or the offset from the virtual base class to the base class, if the
44   /// path from the derived class to the base class involves a virtual base
45   /// class.
46   CharUnits NonVirtualOffset;
47 
48   BaseOffset() : DerivedClass(0), VirtualBase(0),
49     NonVirtualOffset(CharUnits::Zero()) { }
50   BaseOffset(const CXXRecordDecl *DerivedClass,
51              const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
52     : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
53     NonVirtualOffset(NonVirtualOffset) { }
54 
55   bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
56 };
57 
58 /// FinalOverriders - Contains the final overrider member functions for all
59 /// member functions in the base subobjects of a class.
60 class FinalOverriders {
61 public:
62   /// OverriderInfo - Information about a final overrider.
63   struct OverriderInfo {
64     /// Method - The method decl of the overrider.
65     const CXXMethodDecl *Method;
66 
67     /// VirtualBase - The virtual base class subobject of this overridder.
68     /// Note that this records the closest derived virtual base class subobject.
69     const CXXRecordDecl *VirtualBase;
70 
71     /// Offset - the base offset of the overrider's parent in the layout class.
72     CharUnits Offset;
73 
74     OverriderInfo() : Method(0), VirtualBase(0), Offset(CharUnits::Zero()) { }
75   };
76 
77 private:
78   /// MostDerivedClass - The most derived class for which the final overriders
79   /// are stored.
80   const CXXRecordDecl *MostDerivedClass;
81 
82   /// MostDerivedClassOffset - If we're building final overriders for a
83   /// construction vtable, this holds the offset from the layout class to the
84   /// most derived class.
85   const CharUnits MostDerivedClassOffset;
86 
87   /// LayoutClass - The class we're using for layout information. Will be
88   /// different than the most derived class if the final overriders are for a
89   /// construction vtable.
90   const CXXRecordDecl *LayoutClass;
91 
92   ASTContext &Context;
93 
94   /// MostDerivedClassLayout - the AST record layout of the most derived class.
95   const ASTRecordLayout &MostDerivedClassLayout;
96 
97   /// MethodBaseOffsetPairTy - Uniquely identifies a member function
98   /// in a base subobject.
99   typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
100 
101   typedef llvm::DenseMap<MethodBaseOffsetPairTy,
102                          OverriderInfo> OverridersMapTy;
103 
104   /// OverridersMap - The final overriders for all virtual member functions of
105   /// all the base subobjects of the most derived class.
106   OverridersMapTy OverridersMap;
107 
108   /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
109   /// as a record decl and a subobject number) and its offsets in the most
110   /// derived class as well as the layout class.
111   typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
112                          CharUnits> SubobjectOffsetMapTy;
113 
114   typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
115 
116   /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
117   /// given base.
118   void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
119                           CharUnits OffsetInLayoutClass,
120                           SubobjectOffsetMapTy &SubobjectOffsets,
121                           SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
122                           SubobjectCountMapTy &SubobjectCounts);
123 
124   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
125 
126   /// dump - dump the final overriders for a base subobject, and all its direct
127   /// and indirect base subobjects.
128   void dump(raw_ostream &Out, BaseSubobject Base,
129             VisitedVirtualBasesSetTy& VisitedVirtualBases);
130 
131 public:
132   FinalOverriders(const CXXRecordDecl *MostDerivedClass,
133                   CharUnits MostDerivedClassOffset,
134                   const CXXRecordDecl *LayoutClass);
135 
136   /// getOverrider - Get the final overrider for the given method declaration in
137   /// the subobject with the given base offset.
138   OverriderInfo getOverrider(const CXXMethodDecl *MD,
139                              CharUnits BaseOffset) const {
140     assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
141            "Did not find overrider!");
142 
143     return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
144   }
145 
146   /// dump - dump the final overriders.
147   void dump() {
148     VisitedVirtualBasesSetTy VisitedVirtualBases;
149     dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
150          VisitedVirtualBases);
151   }
152 
153 };
154 
155 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
156                                  CharUnits MostDerivedClassOffset,
157                                  const CXXRecordDecl *LayoutClass)
158   : MostDerivedClass(MostDerivedClass),
159   MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
160   Context(MostDerivedClass->getASTContext()),
161   MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
162 
163   // Compute base offsets.
164   SubobjectOffsetMapTy SubobjectOffsets;
165   SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
166   SubobjectCountMapTy SubobjectCounts;
167   ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
168                      /*IsVirtual=*/false,
169                      MostDerivedClassOffset,
170                      SubobjectOffsets, SubobjectLayoutClassOffsets,
171                      SubobjectCounts);
172 
173   // Get the final overriders.
174   CXXFinalOverriderMap FinalOverriders;
175   MostDerivedClass->getFinalOverriders(FinalOverriders);
176 
177   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
178        E = FinalOverriders.end(); I != E; ++I) {
179     const CXXMethodDecl *MD = I->first;
180     const OverridingMethods& Methods = I->second;
181 
182     for (OverridingMethods::const_iterator I = Methods.begin(),
183          E = Methods.end(); I != E; ++I) {
184       unsigned SubobjectNumber = I->first;
185       assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
186                                                    SubobjectNumber)) &&
187              "Did not find subobject offset!");
188 
189       CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
190                                                             SubobjectNumber)];
191 
192       assert(I->second.size() == 1 && "Final overrider is not unique!");
193       const UniqueVirtualMethod &Method = I->second.front();
194 
195       const CXXRecordDecl *OverriderRD = Method.Method->getParent();
196       assert(SubobjectLayoutClassOffsets.count(
197              std::make_pair(OverriderRD, Method.Subobject))
198              && "Did not find subobject offset!");
199       CharUnits OverriderOffset =
200         SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
201                                                    Method.Subobject)];
202 
203       OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
204       assert(!Overrider.Method && "Overrider should not exist yet!");
205 
206       Overrider.Offset = OverriderOffset;
207       Overrider.Method = Method.Method;
208       Overrider.VirtualBase = Method.InVirtualSubobject;
209     }
210   }
211 
212 #if DUMP_OVERRIDERS
213   // And dump them (for now).
214   dump();
215 #endif
216 }
217 
218 static BaseOffset ComputeBaseOffset(ASTContext &Context,
219                                     const CXXRecordDecl *DerivedRD,
220                                     const CXXBasePath &Path) {
221   CharUnits NonVirtualOffset = CharUnits::Zero();
222 
223   unsigned NonVirtualStart = 0;
224   const CXXRecordDecl *VirtualBase = 0;
225 
226   // First, look for the virtual base class.
227   for (int I = Path.size(), E = 0; I != E; --I) {
228     const CXXBasePathElement &Element = Path[I - 1];
229 
230     if (Element.Base->isVirtual()) {
231       NonVirtualStart = I;
232       QualType VBaseType = Element.Base->getType();
233       VirtualBase = VBaseType->getAsCXXRecordDecl();
234       break;
235     }
236   }
237 
238   // Now compute the non-virtual offset.
239   for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
240     const CXXBasePathElement &Element = Path[I];
241 
242     // Check the base class offset.
243     const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
244 
245     const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
246 
247     NonVirtualOffset += Layout.getBaseClassOffset(Base);
248   }
249 
250   // FIXME: This should probably use CharUnits or something. Maybe we should
251   // even change the base offsets in ASTRecordLayout to be specified in
252   // CharUnits.
253   return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
254 
255 }
256 
257 static BaseOffset ComputeBaseOffset(ASTContext &Context,
258                                     const CXXRecordDecl *BaseRD,
259                                     const CXXRecordDecl *DerivedRD) {
260   CXXBasePaths Paths(/*FindAmbiguities=*/false,
261                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
262 
263   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
264     llvm_unreachable("Class must be derived from the passed in base class!");
265 
266   return ComputeBaseOffset(Context, DerivedRD, Paths.front());
267 }
268 
269 static BaseOffset
270 ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
271                                   const CXXMethodDecl *DerivedMD,
272                                   const CXXMethodDecl *BaseMD) {
273   const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
274   const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
275 
276   // Canonicalize the return types.
277   CanQualType CanDerivedReturnType =
278       Context.getCanonicalType(DerivedFT->getReturnType());
279   CanQualType CanBaseReturnType =
280       Context.getCanonicalType(BaseFT->getReturnType());
281 
282   assert(CanDerivedReturnType->getTypeClass() ==
283          CanBaseReturnType->getTypeClass() &&
284          "Types must have same type class!");
285 
286   if (CanDerivedReturnType == CanBaseReturnType) {
287     // No adjustment needed.
288     return BaseOffset();
289   }
290 
291   if (isa<ReferenceType>(CanDerivedReturnType)) {
292     CanDerivedReturnType =
293       CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
294     CanBaseReturnType =
295       CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
296   } else if (isa<PointerType>(CanDerivedReturnType)) {
297     CanDerivedReturnType =
298       CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
299     CanBaseReturnType =
300       CanBaseReturnType->getAs<PointerType>()->getPointeeType();
301   } else {
302     llvm_unreachable("Unexpected return type!");
303   }
304 
305   // We need to compare unqualified types here; consider
306   //   const T *Base::foo();
307   //   T *Derived::foo();
308   if (CanDerivedReturnType.getUnqualifiedType() ==
309       CanBaseReturnType.getUnqualifiedType()) {
310     // No adjustment needed.
311     return BaseOffset();
312   }
313 
314   const CXXRecordDecl *DerivedRD =
315     cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
316 
317   const CXXRecordDecl *BaseRD =
318     cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
319 
320   return ComputeBaseOffset(Context, BaseRD, DerivedRD);
321 }
322 
323 void
324 FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
325                               CharUnits OffsetInLayoutClass,
326                               SubobjectOffsetMapTy &SubobjectOffsets,
327                               SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
328                               SubobjectCountMapTy &SubobjectCounts) {
329   const CXXRecordDecl *RD = Base.getBase();
330 
331   unsigned SubobjectNumber = 0;
332   if (!IsVirtual)
333     SubobjectNumber = ++SubobjectCounts[RD];
334 
335   // Set up the subobject to offset mapping.
336   assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
337          && "Subobject offset already exists!");
338   assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
339          && "Subobject offset already exists!");
340 
341   SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
342   SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
343     OffsetInLayoutClass;
344 
345   // Traverse our bases.
346   for (const auto &B : RD->bases()) {
347     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
348 
349     CharUnits BaseOffset;
350     CharUnits BaseOffsetInLayoutClass;
351     if (B.isVirtual()) {
352       // Check if we've visited this virtual base before.
353       if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
354         continue;
355 
356       const ASTRecordLayout &LayoutClassLayout =
357         Context.getASTRecordLayout(LayoutClass);
358 
359       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
360       BaseOffsetInLayoutClass =
361         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
362     } else {
363       const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
364       CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
365 
366       BaseOffset = Base.getBaseOffset() + Offset;
367       BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
368     }
369 
370     ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
371                        B.isVirtual(), BaseOffsetInLayoutClass,
372                        SubobjectOffsets, SubobjectLayoutClassOffsets,
373                        SubobjectCounts);
374   }
375 }
376 
377 void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
378                            VisitedVirtualBasesSetTy &VisitedVirtualBases) {
379   const CXXRecordDecl *RD = Base.getBase();
380   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
381 
382   for (const auto &B : RD->bases()) {
383     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
384 
385     // Ignore bases that don't have any virtual member functions.
386     if (!BaseDecl->isPolymorphic())
387       continue;
388 
389     CharUnits BaseOffset;
390     if (B.isVirtual()) {
391       if (!VisitedVirtualBases.insert(BaseDecl)) {
392         // We've visited this base before.
393         continue;
394       }
395 
396       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
397     } else {
398       BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
399     }
400 
401     dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
402   }
403 
404   Out << "Final overriders for (";
405   RD->printQualifiedName(Out);
406   Out << ", ";
407   Out << Base.getBaseOffset().getQuantity() << ")\n";
408 
409   // Now dump the overriders for this base subobject.
410   for (const auto *MD : RD->methods()) {
411     if (!MD->isVirtual())
412       continue;
413 
414     OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
415 
416     Out << "  ";
417     MD->printQualifiedName(Out);
418     Out << " - (";
419     Overrider.Method->printQualifiedName(Out);
420     Out << ", " << Overrider.Offset.getQuantity() << ')';
421 
422     BaseOffset Offset;
423     if (!Overrider.Method->isPure())
424       Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
425 
426     if (!Offset.isEmpty()) {
427       Out << " [ret-adj: ";
428       if (Offset.VirtualBase) {
429         Offset.VirtualBase->printQualifiedName(Out);
430         Out << " vbase, ";
431       }
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.
441 struct 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 
454 public:
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 
468 static 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->getNumParams() != RT->getNumParams())
483     return false;
484   for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
485     if (LT->getParamType(I) != RT->getParamType(I))
486       return false;
487   return true;
488 }
489 
490 bool 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 
511 bool 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 
524 CharUnits 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.
535 class VCallAndVBaseOffsetBuilder {
536 public:
537   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
538     VBaseOffsetOffsetsMapTy;
539 
540 private:
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 
588 public:
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 
612 void
613 VCallAndVBaseOffsetBuilder::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 
661 CharUnits 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 
674 void 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 (const auto *MD : RD->methods()) {
695     if (!MD->isVirtual())
696       continue;
697 
698     CharUnits OffsetOffset = getCurrentOffsetOffset();
699 
700     // Don't add a vcall offset if we already have one for this member function
701     // signature.
702     if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
703       continue;
704 
705     CharUnits Offset = CharUnits::Zero();
706 
707     if (Overriders) {
708       // Get the final overrider.
709       FinalOverriders::OverriderInfo Overrider =
710         Overriders->getOverrider(MD, Base.getBaseOffset());
711 
712       /// The vcall offset is the offset from the virtual base to the object
713       /// where the function was overridden.
714       Offset = Overrider.Offset - VBaseOffset;
715     }
716 
717     Components.push_back(
718       VTableComponent::MakeVCallOffset(Offset));
719   }
720 
721   // And iterate over all non-virtual bases (ignoring the primary base).
722   for (const auto &B : RD->bases()) {
723     if (B.isVirtual())
724       continue;
725 
726     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
727     if (BaseDecl == PrimaryBase)
728       continue;
729 
730     // Get the base offset of this base.
731     CharUnits BaseOffset = Base.getBaseOffset() +
732       Layout.getBaseClassOffset(BaseDecl);
733 
734     AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
735                     VBaseOffset);
736   }
737 }
738 
739 void
740 VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
741                                             CharUnits OffsetInLayoutClass) {
742   const ASTRecordLayout &LayoutClassLayout =
743     Context.getASTRecordLayout(LayoutClass);
744 
745   // Add vbase offsets.
746   for (const auto &B : RD->bases()) {
747     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
748 
749     // Check if this is a virtual base that we haven't visited before.
750     if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
751       CharUnits Offset =
752         LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
753 
754       // Add the vbase offset offset.
755       assert(!VBaseOffsetOffsets.count(BaseDecl) &&
756              "vbase offset offset already exists!");
757 
758       CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
759       VBaseOffsetOffsets.insert(
760           std::make_pair(BaseDecl, VBaseOffsetOffset));
761 
762       Components.push_back(
763           VTableComponent::MakeVBaseOffset(Offset));
764     }
765 
766     // Check the base class looking for more vbase offsets.
767     AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
768   }
769 }
770 
771 /// ItaniumVTableBuilder - Class for building vtable layout information.
772 class ItaniumVTableBuilder {
773 public:
774   /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
775   /// primary bases.
776   typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
777     PrimaryBasesSetVectorTy;
778 
779   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
780     VBaseOffsetOffsetsMapTy;
781 
782   typedef llvm::DenseMap<BaseSubobject, uint64_t>
783     AddressPointsMapTy;
784 
785   typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
786 
787 private:
788   /// VTables - Global vtable information.
789   ItaniumVTableContext &VTables;
790 
791   /// MostDerivedClass - The most derived class for which we're building this
792   /// vtable.
793   const CXXRecordDecl *MostDerivedClass;
794 
795   /// MostDerivedClassOffset - If we're building a construction vtable, this
796   /// holds the offset from the layout class to the most derived class.
797   const CharUnits MostDerivedClassOffset;
798 
799   /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
800   /// base. (This only makes sense when building a construction vtable).
801   bool MostDerivedClassIsVirtual;
802 
803   /// LayoutClass - The class we're using for layout information. Will be
804   /// different than the most derived class if we're building a construction
805   /// vtable.
806   const CXXRecordDecl *LayoutClass;
807 
808   /// Context - The ASTContext which we will use for layout information.
809   ASTContext &Context;
810 
811   /// FinalOverriders - The final overriders of the most derived class.
812   const FinalOverriders Overriders;
813 
814   /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
815   /// bases in this vtable.
816   llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
817 
818   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
819   /// the most derived class.
820   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
821 
822   /// Components - The components of the vtable being built.
823   SmallVector<VTableComponent, 64> Components;
824 
825   /// AddressPoints - Address points for the vtable being built.
826   AddressPointsMapTy AddressPoints;
827 
828   /// MethodInfo - Contains information about a method in a vtable.
829   /// (Used for computing 'this' pointer adjustment thunks.
830   struct MethodInfo {
831     /// BaseOffset - The base offset of this method.
832     const CharUnits BaseOffset;
833 
834     /// BaseOffsetInLayoutClass - The base offset in the layout class of this
835     /// method.
836     const CharUnits BaseOffsetInLayoutClass;
837 
838     /// VTableIndex - The index in the vtable that this method has.
839     /// (For destructors, this is the index of the complete destructor).
840     const uint64_t VTableIndex;
841 
842     MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
843                uint64_t VTableIndex)
844       : BaseOffset(BaseOffset),
845       BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
846       VTableIndex(VTableIndex) { }
847 
848     MethodInfo()
849       : BaseOffset(CharUnits::Zero()),
850       BaseOffsetInLayoutClass(CharUnits::Zero()),
851       VTableIndex(0) { }
852   };
853 
854   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
855 
856   /// MethodInfoMap - The information for all methods in the vtable we're
857   /// currently building.
858   MethodInfoMapTy MethodInfoMap;
859 
860   /// MethodVTableIndices - Contains the index (relative to the vtable address
861   /// point) where the function pointer for a virtual function is stored.
862   MethodVTableIndicesTy MethodVTableIndices;
863 
864   typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
865 
866   /// VTableThunks - The thunks by vtable index in the vtable currently being
867   /// built.
868   VTableThunksMapTy VTableThunks;
869 
870   typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
871   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
872 
873   /// Thunks - A map that contains all the thunks needed for all methods in the
874   /// most derived class for which the vtable is currently being built.
875   ThunksMapTy Thunks;
876 
877   /// AddThunk - Add a thunk for the given method.
878   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
879 
880   /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
881   /// part of the vtable we're currently building.
882   void ComputeThisAdjustments();
883 
884   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
885 
886   /// PrimaryVirtualBases - All known virtual bases who are a primary base of
887   /// some other base.
888   VisitedVirtualBasesSetTy PrimaryVirtualBases;
889 
890   /// ComputeReturnAdjustment - Compute the return adjustment given a return
891   /// adjustment base offset.
892   ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
893 
894   /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
895   /// the 'this' pointer from the base subobject to the derived subobject.
896   BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
897                                              BaseSubobject Derived) const;
898 
899   /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
900   /// given virtual member function, its offset in the layout class and its
901   /// final overrider.
902   ThisAdjustment
903   ComputeThisAdjustment(const CXXMethodDecl *MD,
904                         CharUnits BaseOffsetInLayoutClass,
905                         FinalOverriders::OverriderInfo Overrider);
906 
907   /// AddMethod - Add a single virtual member function to the vtable
908   /// components vector.
909   void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
910 
911   /// IsOverriderUsed - Returns whether the overrider will ever be used in this
912   /// part of the vtable.
913   ///
914   /// Itanium C++ ABI 2.5.2:
915   ///
916   ///   struct A { virtual void f(); };
917   ///   struct B : virtual public A { int i; };
918   ///   struct C : virtual public A { int j; };
919   ///   struct D : public B, public C {};
920   ///
921   ///   When B and C are declared, A is a primary base in each case, so although
922   ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
923   ///   adjustment is required and no thunk is generated. However, inside D
924   ///   objects, A is no longer a primary base of C, so if we allowed calls to
925   ///   C::f() to use the copy of A's vtable in the C subobject, we would need
926   ///   to adjust this from C* to B::A*, which would require a third-party
927   ///   thunk. Since we require that a call to C::f() first convert to A*,
928   ///   C-in-D's copy of A's vtable is never referenced, so this is not
929   ///   necessary.
930   bool IsOverriderUsed(const CXXMethodDecl *Overrider,
931                        CharUnits BaseOffsetInLayoutClass,
932                        const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
933                        CharUnits FirstBaseOffsetInLayoutClass) const;
934 
935 
936   /// AddMethods - Add the methods of this base subobject and all its
937   /// primary bases to the vtable components vector.
938   void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
939                   const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
940                   CharUnits FirstBaseOffsetInLayoutClass,
941                   PrimaryBasesSetVectorTy &PrimaryBases);
942 
943   // LayoutVTable - Layout the vtable for the given base class, including its
944   // secondary vtables and any vtables for virtual bases.
945   void LayoutVTable();
946 
947   /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
948   /// given base subobject, as well as all its secondary vtables.
949   ///
950   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
951   /// or a direct or indirect base of a virtual base.
952   ///
953   /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
954   /// in the layout class.
955   void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
956                                         bool BaseIsMorallyVirtual,
957                                         bool BaseIsVirtualInLayoutClass,
958                                         CharUnits OffsetInLayoutClass);
959 
960   /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
961   /// subobject.
962   ///
963   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
964   /// or a direct or indirect base of a virtual base.
965   void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
966                               CharUnits OffsetInLayoutClass);
967 
968   /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
969   /// class hierarchy.
970   void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
971                                     CharUnits OffsetInLayoutClass,
972                                     VisitedVirtualBasesSetTy &VBases);
973 
974   /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
975   /// given base (excluding any primary bases).
976   void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
977                                     VisitedVirtualBasesSetTy &VBases);
978 
979   /// isBuildingConstructionVTable - Return whether this vtable builder is
980   /// building a construction vtable.
981   bool isBuildingConstructorVTable() const {
982     return MostDerivedClass != LayoutClass;
983   }
984 
985 public:
986   ItaniumVTableBuilder(ItaniumVTableContext &VTables,
987                        const CXXRecordDecl *MostDerivedClass,
988                        CharUnits MostDerivedClassOffset,
989                        bool MostDerivedClassIsVirtual,
990                        const CXXRecordDecl *LayoutClass)
991       : VTables(VTables), MostDerivedClass(MostDerivedClass),
992         MostDerivedClassOffset(MostDerivedClassOffset),
993         MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
994         LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
995         Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
996     assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
997 
998     LayoutVTable();
999 
1000     if (Context.getLangOpts().DumpVTableLayouts)
1001       dumpLayout(llvm::outs());
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   MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1025     return MethodVTableIndices.begin();
1026   }
1027 
1028   MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1029     return MethodVTableIndices.end();
1030   }
1031 
1032   /// getNumVTableComponents - Return the number of components in the vtable
1033   /// currently built.
1034   uint64_t getNumVTableComponents() const {
1035     return Components.size();
1036   }
1037 
1038   const VTableComponent *vtable_component_begin() const {
1039     return Components.begin();
1040   }
1041 
1042   const VTableComponent *vtable_component_end() const {
1043     return Components.end();
1044   }
1045 
1046   AddressPointsMapTy::const_iterator address_points_begin() const {
1047     return AddressPoints.begin();
1048   }
1049 
1050   AddressPointsMapTy::const_iterator address_points_end() const {
1051     return AddressPoints.end();
1052   }
1053 
1054   VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1055     return VTableThunks.begin();
1056   }
1057 
1058   VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1059     return VTableThunks.end();
1060   }
1061 
1062   /// dumpLayout - Dump the vtable layout.
1063   void dumpLayout(raw_ostream&);
1064 };
1065 
1066 void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1067                                     const ThunkInfo &Thunk) {
1068   assert(!isBuildingConstructorVTable() &&
1069          "Can't add thunks for construction vtable");
1070 
1071   SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1072 
1073   // Check if we have this thunk already.
1074   if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1075       ThunksVector.end())
1076     return;
1077 
1078   ThunksVector.push_back(Thunk);
1079 }
1080 
1081 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1082 
1083 /// Visit all the methods overridden by the given method recursively,
1084 /// in a depth-first pre-order. The Visitor's visitor method returns a bool
1085 /// indicating whether to continue the recursion for the given overridden
1086 /// method (i.e. returning false stops the iteration).
1087 template <class VisitorTy>
1088 static void
1089 visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
1090   assert(MD->isVirtual() && "Method is not virtual!");
1091 
1092   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1093        E = MD->end_overridden_methods(); I != E; ++I) {
1094     const CXXMethodDecl *OverriddenMD = *I;
1095     if (!Visitor.visit(OverriddenMD))
1096       continue;
1097     visitAllOverriddenMethods(OverriddenMD, Visitor);
1098   }
1099 }
1100 
1101 namespace {
1102   struct OverriddenMethodsCollector {
1103     OverriddenMethodsSetTy *Methods;
1104 
1105     bool visit(const CXXMethodDecl *MD) {
1106       // Don't recurse on this method if we've already collected it.
1107       return Methods->insert(MD);
1108     }
1109   };
1110 }
1111 
1112 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1113 /// the overridden methods that the function decl overrides.
1114 static void
1115 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1116                             OverriddenMethodsSetTy& OverriddenMethods) {
1117   OverriddenMethodsCollector Collector = { &OverriddenMethods };
1118   visitAllOverriddenMethods(MD, Collector);
1119 }
1120 
1121 void ItaniumVTableBuilder::ComputeThisAdjustments() {
1122   // Now go through the method info map and see if any of the methods need
1123   // 'this' pointer adjustments.
1124   for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1125        E = MethodInfoMap.end(); I != E; ++I) {
1126     const CXXMethodDecl *MD = I->first;
1127     const MethodInfo &MethodInfo = I->second;
1128 
1129     // Ignore adjustments for unused function pointers.
1130     uint64_t VTableIndex = MethodInfo.VTableIndex;
1131     if (Components[VTableIndex].getKind() ==
1132         VTableComponent::CK_UnusedFunctionPointer)
1133       continue;
1134 
1135     // Get the final overrider for this method.
1136     FinalOverriders::OverriderInfo Overrider =
1137       Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1138 
1139     // Check if we need an adjustment at all.
1140     if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1141       // When a return thunk is needed by a derived class that overrides a
1142       // virtual base, gcc uses a virtual 'this' adjustment as well.
1143       // While the thunk itself might be needed by vtables in subclasses or
1144       // in construction vtables, there doesn't seem to be a reason for using
1145       // the thunk in this vtable. Still, we do so to match gcc.
1146       if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1147         continue;
1148     }
1149 
1150     ThisAdjustment ThisAdjustment =
1151       ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1152 
1153     if (ThisAdjustment.isEmpty())
1154       continue;
1155 
1156     // Add it.
1157     VTableThunks[VTableIndex].This = ThisAdjustment;
1158 
1159     if (isa<CXXDestructorDecl>(MD)) {
1160       // Add an adjustment for the deleting destructor as well.
1161       VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1162     }
1163   }
1164 
1165   /// Clear the method info map.
1166   MethodInfoMap.clear();
1167 
1168   if (isBuildingConstructorVTable()) {
1169     // We don't need to store thunk information for construction vtables.
1170     return;
1171   }
1172 
1173   for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1174        E = VTableThunks.end(); I != E; ++I) {
1175     const VTableComponent &Component = Components[I->first];
1176     const ThunkInfo &Thunk = I->second;
1177     const CXXMethodDecl *MD;
1178 
1179     switch (Component.getKind()) {
1180     default:
1181       llvm_unreachable("Unexpected vtable component kind!");
1182     case VTableComponent::CK_FunctionPointer:
1183       MD = Component.getFunctionDecl();
1184       break;
1185     case VTableComponent::CK_CompleteDtorPointer:
1186       MD = Component.getDestructorDecl();
1187       break;
1188     case VTableComponent::CK_DeletingDtorPointer:
1189       // We've already added the thunk when we saw the complete dtor pointer.
1190       continue;
1191     }
1192 
1193     if (MD->getParent() == MostDerivedClass)
1194       AddThunk(MD, Thunk);
1195   }
1196 }
1197 
1198 ReturnAdjustment
1199 ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1200   ReturnAdjustment Adjustment;
1201 
1202   if (!Offset.isEmpty()) {
1203     if (Offset.VirtualBase) {
1204       // Get the virtual base offset offset.
1205       if (Offset.DerivedClass == MostDerivedClass) {
1206         // We can get the offset offset directly from our map.
1207         Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1208           VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1209       } else {
1210         Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1211           VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1212                                              Offset.VirtualBase).getQuantity();
1213       }
1214     }
1215 
1216     Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1217   }
1218 
1219   return Adjustment;
1220 }
1221 
1222 BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1223     BaseSubobject Base, BaseSubobject Derived) const {
1224   const CXXRecordDecl *BaseRD = Base.getBase();
1225   const CXXRecordDecl *DerivedRD = Derived.getBase();
1226 
1227   CXXBasePaths Paths(/*FindAmbiguities=*/true,
1228                      /*RecordPaths=*/true, /*DetectVirtual=*/true);
1229 
1230   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1231     llvm_unreachable("Class must be derived from the passed in base class!");
1232 
1233   // We have to go through all the paths, and see which one leads us to the
1234   // right base subobject.
1235   for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1236        I != E; ++I) {
1237     BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1238 
1239     CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1240 
1241     if (Offset.VirtualBase) {
1242       // If we have a virtual base class, the non-virtual offset is relative
1243       // to the virtual base class offset.
1244       const ASTRecordLayout &LayoutClassLayout =
1245         Context.getASTRecordLayout(LayoutClass);
1246 
1247       /// Get the virtual base offset, relative to the most derived class
1248       /// layout.
1249       OffsetToBaseSubobject +=
1250         LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1251     } else {
1252       // Otherwise, the non-virtual offset is relative to the derived class
1253       // offset.
1254       OffsetToBaseSubobject += Derived.getBaseOffset();
1255     }
1256 
1257     // Check if this path gives us the right base subobject.
1258     if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1259       // Since we're going from the base class _to_ the derived class, we'll
1260       // invert the non-virtual offset here.
1261       Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1262       return Offset;
1263     }
1264   }
1265 
1266   return BaseOffset();
1267 }
1268 
1269 ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1270     const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1271     FinalOverriders::OverriderInfo Overrider) {
1272   // Ignore adjustments for pure virtual member functions.
1273   if (Overrider.Method->isPure())
1274     return ThisAdjustment();
1275 
1276   BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1277                                         BaseOffsetInLayoutClass);
1278 
1279   BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1280                                        Overrider.Offset);
1281 
1282   // Compute the adjustment offset.
1283   BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1284                                                       OverriderBaseSubobject);
1285   if (Offset.isEmpty())
1286     return ThisAdjustment();
1287 
1288   ThisAdjustment Adjustment;
1289 
1290   if (Offset.VirtualBase) {
1291     // Get the vcall offset map for this virtual base.
1292     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1293 
1294     if (VCallOffsets.empty()) {
1295       // We don't have vcall offsets for this virtual base, go ahead and
1296       // build them.
1297       VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1298                                          /*FinalOverriders=*/0,
1299                                          BaseSubobject(Offset.VirtualBase,
1300                                                        CharUnits::Zero()),
1301                                          /*BaseIsVirtual=*/true,
1302                                          /*OffsetInLayoutClass=*/
1303                                              CharUnits::Zero());
1304 
1305       VCallOffsets = Builder.getVCallOffsets();
1306     }
1307 
1308     Adjustment.Virtual.Itanium.VCallOffsetOffset =
1309       VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1310   }
1311 
1312   // Set the non-virtual part of the adjustment.
1313   Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1314 
1315   return Adjustment;
1316 }
1317 
1318 void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1319                                      ReturnAdjustment ReturnAdjustment) {
1320   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1321     assert(ReturnAdjustment.isEmpty() &&
1322            "Destructor can't have return adjustment!");
1323 
1324     // Add both the complete destructor and the deleting destructor.
1325     Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1326     Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1327   } else {
1328     // Add the return adjustment if necessary.
1329     if (!ReturnAdjustment.isEmpty())
1330       VTableThunks[Components.size()].Return = ReturnAdjustment;
1331 
1332     // Add the function.
1333     Components.push_back(VTableComponent::MakeFunction(MD));
1334   }
1335 }
1336 
1337 /// OverridesIndirectMethodInBase - Return whether the given member function
1338 /// overrides any methods in the set of given bases.
1339 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1340 /// For example, if we have:
1341 ///
1342 /// struct A { virtual void f(); }
1343 /// struct B : A { virtual void f(); }
1344 /// struct C : B { virtual void f(); }
1345 ///
1346 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1347 /// and { A } as the set of bases.
1348 static bool OverridesIndirectMethodInBases(
1349     const CXXMethodDecl *MD,
1350     ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1351   if (Bases.count(MD->getParent()))
1352     return true;
1353 
1354   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1355        E = MD->end_overridden_methods(); I != E; ++I) {
1356     const CXXMethodDecl *OverriddenMD = *I;
1357 
1358     // Check "indirect overriders".
1359     if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1360       return true;
1361   }
1362 
1363   return false;
1364 }
1365 
1366 bool ItaniumVTableBuilder::IsOverriderUsed(
1367     const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1368     const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1369     CharUnits FirstBaseOffsetInLayoutClass) const {
1370   // If the base and the first base in the primary base chain have the same
1371   // offsets, then this overrider will be used.
1372   if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1373    return true;
1374 
1375   // We know now that Base (or a direct or indirect base of it) is a primary
1376   // base in part of the class hierarchy, but not a primary base in the most
1377   // derived class.
1378 
1379   // If the overrider is the first base in the primary base chain, we know
1380   // that the overrider will be used.
1381   if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1382     return true;
1383 
1384   ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1385 
1386   const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1387   PrimaryBases.insert(RD);
1388 
1389   // Now traverse the base chain, starting with the first base, until we find
1390   // the base that is no longer a primary base.
1391   while (true) {
1392     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1393     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1394 
1395     if (!PrimaryBase)
1396       break;
1397 
1398     if (Layout.isPrimaryBaseVirtual()) {
1399       assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1400              "Primary base should always be at offset 0!");
1401 
1402       const ASTRecordLayout &LayoutClassLayout =
1403         Context.getASTRecordLayout(LayoutClass);
1404 
1405       // Now check if this is the primary base that is not a primary base in the
1406       // most derived class.
1407       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1408           FirstBaseOffsetInLayoutClass) {
1409         // We found it, stop walking the chain.
1410         break;
1411       }
1412     } else {
1413       assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1414              "Primary base should always be at offset 0!");
1415     }
1416 
1417     if (!PrimaryBases.insert(PrimaryBase))
1418       llvm_unreachable("Found a duplicate primary base!");
1419 
1420     RD = PrimaryBase;
1421   }
1422 
1423   // If the final overrider is an override of one of the primary bases,
1424   // then we know that it will be used.
1425   return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1426 }
1427 
1428 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1429 
1430 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1431 /// from the nearest base. Returns null if no method was found.
1432 /// The Bases are expected to be sorted in a base-to-derived order.
1433 static const CXXMethodDecl *
1434 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1435                             BasesSetVectorTy &Bases) {
1436   OverriddenMethodsSetTy OverriddenMethods;
1437   ComputeAllOverriddenMethods(MD, OverriddenMethods);
1438 
1439   for (int I = Bases.size(), E = 0; I != E; --I) {
1440     const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1441 
1442     // Now check the overridden methods.
1443     for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1444          E = OverriddenMethods.end(); I != E; ++I) {
1445       const CXXMethodDecl *OverriddenMD = *I;
1446 
1447       // We found our overridden method.
1448       if (OverriddenMD->getParent() == PrimaryBase)
1449         return OverriddenMD;
1450     }
1451   }
1452 
1453   return 0;
1454 }
1455 
1456 void ItaniumVTableBuilder::AddMethods(
1457     BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1458     const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1459     CharUnits FirstBaseOffsetInLayoutClass,
1460     PrimaryBasesSetVectorTy &PrimaryBases) {
1461   // Itanium C++ ABI 2.5.2:
1462   //   The order of the virtual function pointers in a virtual table is the
1463   //   order of declaration of the corresponding member functions in the class.
1464   //
1465   //   There is an entry for any virtual function declared in a class,
1466   //   whether it is a new function or overrides a base class function,
1467   //   unless it overrides a function from the primary base, and conversion
1468   //   between their return types does not require an adjustment.
1469 
1470   const CXXRecordDecl *RD = Base.getBase();
1471   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1472 
1473   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1474     CharUnits PrimaryBaseOffset;
1475     CharUnits PrimaryBaseOffsetInLayoutClass;
1476     if (Layout.isPrimaryBaseVirtual()) {
1477       assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1478              "Primary vbase should have a zero offset!");
1479 
1480       const ASTRecordLayout &MostDerivedClassLayout =
1481         Context.getASTRecordLayout(MostDerivedClass);
1482 
1483       PrimaryBaseOffset =
1484         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1485 
1486       const ASTRecordLayout &LayoutClassLayout =
1487         Context.getASTRecordLayout(LayoutClass);
1488 
1489       PrimaryBaseOffsetInLayoutClass =
1490         LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1491     } else {
1492       assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1493              "Primary base should have a zero offset!");
1494 
1495       PrimaryBaseOffset = Base.getBaseOffset();
1496       PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1497     }
1498 
1499     AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1500                PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1501                FirstBaseOffsetInLayoutClass, PrimaryBases);
1502 
1503     if (!PrimaryBases.insert(PrimaryBase))
1504       llvm_unreachable("Found a duplicate primary base!");
1505   }
1506 
1507   const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1508 
1509   typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1510   NewVirtualFunctionsTy NewVirtualFunctions;
1511 
1512   // Now go through all virtual member functions and add them.
1513   for (const auto *MD : RD->methods()) {
1514     if (!MD->isVirtual())
1515       continue;
1516 
1517     // Get the final overrider.
1518     FinalOverriders::OverriderInfo Overrider =
1519       Overriders.getOverrider(MD, Base.getBaseOffset());
1520 
1521     // Check if this virtual member function overrides a method in a primary
1522     // base. If this is the case, and the return type doesn't require adjustment
1523     // then we can just use the member function from the primary base.
1524     if (const CXXMethodDecl *OverriddenMD =
1525           FindNearestOverriddenMethod(MD, PrimaryBases)) {
1526       if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1527                                             OverriddenMD).isEmpty()) {
1528         // Replace the method info of the overridden method with our own
1529         // method.
1530         assert(MethodInfoMap.count(OverriddenMD) &&
1531                "Did not find the overridden method!");
1532         MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1533 
1534         MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1535                               OverriddenMethodInfo.VTableIndex);
1536 
1537         assert(!MethodInfoMap.count(MD) &&
1538                "Should not have method info for this method yet!");
1539 
1540         MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1541         MethodInfoMap.erase(OverriddenMD);
1542 
1543         // If the overridden method exists in a virtual base class or a direct
1544         // or indirect base class of a virtual base class, we need to emit a
1545         // thunk if we ever have a class hierarchy where the base class is not
1546         // a primary base in the complete object.
1547         if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1548           // Compute the this adjustment.
1549           ThisAdjustment ThisAdjustment =
1550             ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1551                                   Overrider);
1552 
1553           if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
1554               Overrider.Method->getParent() == MostDerivedClass) {
1555 
1556             // There's no return adjustment from OverriddenMD and MD,
1557             // but that doesn't mean there isn't one between MD and
1558             // the final overrider.
1559             BaseOffset ReturnAdjustmentOffset =
1560               ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1561             ReturnAdjustment ReturnAdjustment =
1562               ComputeReturnAdjustment(ReturnAdjustmentOffset);
1563 
1564             // This is a virtual thunk for the most derived class, add it.
1565             AddThunk(Overrider.Method,
1566                      ThunkInfo(ThisAdjustment, ReturnAdjustment));
1567           }
1568         }
1569 
1570         continue;
1571       }
1572     }
1573 
1574     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1575       if (MD->isImplicit()) {
1576         // Itanium C++ ABI 2.5.2:
1577         //   If a class has an implicitly-defined virtual destructor,
1578         //   its entries come after the declared virtual function pointers.
1579 
1580         assert(!ImplicitVirtualDtor &&
1581                "Did already see an implicit virtual dtor!");
1582         ImplicitVirtualDtor = DD;
1583         continue;
1584       }
1585     }
1586 
1587     NewVirtualFunctions.push_back(MD);
1588   }
1589 
1590   if (ImplicitVirtualDtor)
1591     NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1592 
1593   for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1594        E = NewVirtualFunctions.end(); I != E; ++I) {
1595     const CXXMethodDecl *MD = *I;
1596 
1597     // Get the final overrider.
1598     FinalOverriders::OverriderInfo Overrider =
1599       Overriders.getOverrider(MD, Base.getBaseOffset());
1600 
1601     // Insert the method info for this method.
1602     MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1603                           Components.size());
1604 
1605     assert(!MethodInfoMap.count(MD) &&
1606            "Should not have method info for this method yet!");
1607     MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1608 
1609     // Check if this overrider is going to be used.
1610     const CXXMethodDecl *OverriderMD = Overrider.Method;
1611     if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1612                          FirstBaseInPrimaryBaseChain,
1613                          FirstBaseOffsetInLayoutClass)) {
1614       Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1615       continue;
1616     }
1617 
1618     // Check if this overrider needs a return adjustment.
1619     // We don't want to do this for pure virtual member functions.
1620     BaseOffset ReturnAdjustmentOffset;
1621     if (!OverriderMD->isPure()) {
1622       ReturnAdjustmentOffset =
1623         ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1624     }
1625 
1626     ReturnAdjustment ReturnAdjustment =
1627       ComputeReturnAdjustment(ReturnAdjustmentOffset);
1628 
1629     AddMethod(Overrider.Method, ReturnAdjustment);
1630   }
1631 }
1632 
1633 void ItaniumVTableBuilder::LayoutVTable() {
1634   LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1635                                                  CharUnits::Zero()),
1636                                    /*BaseIsMorallyVirtual=*/false,
1637                                    MostDerivedClassIsVirtual,
1638                                    MostDerivedClassOffset);
1639 
1640   VisitedVirtualBasesSetTy VBases;
1641 
1642   // Determine the primary virtual bases.
1643   DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1644                                VBases);
1645   VBases.clear();
1646 
1647   LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1648 
1649   // -fapple-kext adds an extra entry at end of vtbl.
1650   bool IsAppleKext = Context.getLangOpts().AppleKext;
1651   if (IsAppleKext)
1652     Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1653 }
1654 
1655 void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1656     BaseSubobject Base, bool BaseIsMorallyVirtual,
1657     bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
1658   assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1659 
1660   // Add vcall and vbase offsets for this vtable.
1661   VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1662                                      Base, BaseIsVirtualInLayoutClass,
1663                                      OffsetInLayoutClass);
1664   Components.append(Builder.components_begin(), Builder.components_end());
1665 
1666   // Check if we need to add these vcall offsets.
1667   if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1668     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1669 
1670     if (VCallOffsets.empty())
1671       VCallOffsets = Builder.getVCallOffsets();
1672   }
1673 
1674   // If we're laying out the most derived class we want to keep track of the
1675   // virtual base class offset offsets.
1676   if (Base.getBase() == MostDerivedClass)
1677     VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1678 
1679   // Add the offset to top.
1680   CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1681   Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1682 
1683   // Next, add the RTTI.
1684   Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1685 
1686   uint64_t AddressPoint = Components.size();
1687 
1688   // Now go through all virtual member functions and add them.
1689   PrimaryBasesSetVectorTy PrimaryBases;
1690   AddMethods(Base, OffsetInLayoutClass,
1691              Base.getBase(), OffsetInLayoutClass,
1692              PrimaryBases);
1693 
1694   const CXXRecordDecl *RD = Base.getBase();
1695   if (RD == MostDerivedClass) {
1696     assert(MethodVTableIndices.empty());
1697     for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1698          E = MethodInfoMap.end(); I != E; ++I) {
1699       const CXXMethodDecl *MD = I->first;
1700       const MethodInfo &MI = I->second;
1701       if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1702         MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1703             = MI.VTableIndex - AddressPoint;
1704         MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1705             = MI.VTableIndex + 1 - AddressPoint;
1706       } else {
1707         MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1708       }
1709     }
1710   }
1711 
1712   // Compute 'this' pointer adjustments.
1713   ComputeThisAdjustments();
1714 
1715   // Add all address points.
1716   while (true) {
1717     AddressPoints.insert(std::make_pair(
1718       BaseSubobject(RD, OffsetInLayoutClass),
1719       AddressPoint));
1720 
1721     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1722     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1723 
1724     if (!PrimaryBase)
1725       break;
1726 
1727     if (Layout.isPrimaryBaseVirtual()) {
1728       // Check if this virtual primary base is a primary base in the layout
1729       // class. If it's not, we don't want to add it.
1730       const ASTRecordLayout &LayoutClassLayout =
1731         Context.getASTRecordLayout(LayoutClass);
1732 
1733       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1734           OffsetInLayoutClass) {
1735         // We don't want to add this class (or any of its primary bases).
1736         break;
1737       }
1738     }
1739 
1740     RD = PrimaryBase;
1741   }
1742 
1743   // Layout secondary vtables.
1744   LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1745 }
1746 
1747 void
1748 ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1749                                              bool BaseIsMorallyVirtual,
1750                                              CharUnits OffsetInLayoutClass) {
1751   // Itanium C++ ABI 2.5.2:
1752   //   Following the primary virtual table of a derived class are secondary
1753   //   virtual tables for each of its proper base classes, except any primary
1754   //   base(s) with which it shares its primary virtual table.
1755 
1756   const CXXRecordDecl *RD = Base.getBase();
1757   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1758   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1759 
1760   for (const auto &B : RD->bases()) {
1761     // Ignore virtual bases, we'll emit them later.
1762     if (B.isVirtual())
1763       continue;
1764 
1765     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1766 
1767     // Ignore bases that don't have a vtable.
1768     if (!BaseDecl->isDynamicClass())
1769       continue;
1770 
1771     if (isBuildingConstructorVTable()) {
1772       // Itanium C++ ABI 2.6.4:
1773       //   Some of the base class subobjects may not need construction virtual
1774       //   tables, which will therefore not be present in the construction
1775       //   virtual table group, even though the subobject virtual tables are
1776       //   present in the main virtual table group for the complete object.
1777       if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1778         continue;
1779     }
1780 
1781     // Get the base offset of this base.
1782     CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1783     CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1784 
1785     CharUnits BaseOffsetInLayoutClass =
1786       OffsetInLayoutClass + RelativeBaseOffset;
1787 
1788     // Don't emit a secondary vtable for a primary base. We might however want
1789     // to emit secondary vtables for other bases of this base.
1790     if (BaseDecl == PrimaryBase) {
1791       LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1792                              BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1793       continue;
1794     }
1795 
1796     // Layout the primary vtable (and any secondary vtables) for this base.
1797     LayoutPrimaryAndSecondaryVTables(
1798       BaseSubobject(BaseDecl, BaseOffset),
1799       BaseIsMorallyVirtual,
1800       /*BaseIsVirtualInLayoutClass=*/false,
1801       BaseOffsetInLayoutClass);
1802   }
1803 }
1804 
1805 void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1806     const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1807     VisitedVirtualBasesSetTy &VBases) {
1808   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1809 
1810   // Check if this base has a primary base.
1811   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1812 
1813     // Check if it's virtual.
1814     if (Layout.isPrimaryBaseVirtual()) {
1815       bool IsPrimaryVirtualBase = true;
1816 
1817       if (isBuildingConstructorVTable()) {
1818         // Check if the base is actually a primary base in the class we use for
1819         // layout.
1820         const ASTRecordLayout &LayoutClassLayout =
1821           Context.getASTRecordLayout(LayoutClass);
1822 
1823         CharUnits PrimaryBaseOffsetInLayoutClass =
1824           LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1825 
1826         // We know that the base is not a primary base in the layout class if
1827         // the base offsets are different.
1828         if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1829           IsPrimaryVirtualBase = false;
1830       }
1831 
1832       if (IsPrimaryVirtualBase)
1833         PrimaryVirtualBases.insert(PrimaryBase);
1834     }
1835   }
1836 
1837   // Traverse bases, looking for more primary virtual bases.
1838   for (const auto &B : RD->bases()) {
1839     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1840 
1841     CharUnits BaseOffsetInLayoutClass;
1842 
1843     if (B.isVirtual()) {
1844       if (!VBases.insert(BaseDecl))
1845         continue;
1846 
1847       const ASTRecordLayout &LayoutClassLayout =
1848         Context.getASTRecordLayout(LayoutClass);
1849 
1850       BaseOffsetInLayoutClass =
1851         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1852     } else {
1853       BaseOffsetInLayoutClass =
1854         OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1855     }
1856 
1857     DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1858   }
1859 }
1860 
1861 void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1862     const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
1863   // Itanium C++ ABI 2.5.2:
1864   //   Then come the virtual base virtual tables, also in inheritance graph
1865   //   order, and again excluding primary bases (which share virtual tables with
1866   //   the classes for which they are primary).
1867   for (const auto &B : RD->bases()) {
1868     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1869 
1870     // Check if this base needs a vtable. (If it's virtual, not a primary base
1871     // of some other class, and we haven't visited it before).
1872     if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1873         !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1874       const ASTRecordLayout &MostDerivedClassLayout =
1875         Context.getASTRecordLayout(MostDerivedClass);
1876       CharUnits BaseOffset =
1877         MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1878 
1879       const ASTRecordLayout &LayoutClassLayout =
1880         Context.getASTRecordLayout(LayoutClass);
1881       CharUnits BaseOffsetInLayoutClass =
1882         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1883 
1884       LayoutPrimaryAndSecondaryVTables(
1885         BaseSubobject(BaseDecl, BaseOffset),
1886         /*BaseIsMorallyVirtual=*/true,
1887         /*BaseIsVirtualInLayoutClass=*/true,
1888         BaseOffsetInLayoutClass);
1889     }
1890 
1891     // We only need to check the base for virtual base vtables if it actually
1892     // has virtual bases.
1893     if (BaseDecl->getNumVBases())
1894       LayoutVTablesForVirtualBases(BaseDecl, VBases);
1895   }
1896 }
1897 
1898 /// dumpLayout - Dump the vtable layout.
1899 void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
1900   // FIXME: write more tests that actually use the dumpLayout output to prevent
1901   // ItaniumVTableBuilder regressions.
1902 
1903   if (isBuildingConstructorVTable()) {
1904     Out << "Construction vtable for ('";
1905     MostDerivedClass->printQualifiedName(Out);
1906     Out << "', ";
1907     Out << MostDerivedClassOffset.getQuantity() << ") in '";
1908     LayoutClass->printQualifiedName(Out);
1909   } else {
1910     Out << "Vtable for '";
1911     MostDerivedClass->printQualifiedName(Out);
1912   }
1913   Out << "' (" << Components.size() << " entries).\n";
1914 
1915   // Iterate through the address points and insert them into a new map where
1916   // they are keyed by the index and not the base object.
1917   // Since an address point can be shared by multiple subobjects, we use an
1918   // STL multimap.
1919   std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1920   for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1921        E = AddressPoints.end(); I != E; ++I) {
1922     const BaseSubobject& Base = I->first;
1923     uint64_t Index = I->second;
1924 
1925     AddressPointsByIndex.insert(std::make_pair(Index, Base));
1926   }
1927 
1928   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1929     uint64_t Index = I;
1930 
1931     Out << llvm::format("%4d | ", I);
1932 
1933     const VTableComponent &Component = Components[I];
1934 
1935     // Dump the component.
1936     switch (Component.getKind()) {
1937 
1938     case VTableComponent::CK_VCallOffset:
1939       Out << "vcall_offset ("
1940           << Component.getVCallOffset().getQuantity()
1941           << ")";
1942       break;
1943 
1944     case VTableComponent::CK_VBaseOffset:
1945       Out << "vbase_offset ("
1946           << Component.getVBaseOffset().getQuantity()
1947           << ")";
1948       break;
1949 
1950     case VTableComponent::CK_OffsetToTop:
1951       Out << "offset_to_top ("
1952           << Component.getOffsetToTop().getQuantity()
1953           << ")";
1954       break;
1955 
1956     case VTableComponent::CK_RTTI:
1957       Component.getRTTIDecl()->printQualifiedName(Out);
1958       Out << " RTTI";
1959       break;
1960 
1961     case VTableComponent::CK_FunctionPointer: {
1962       const CXXMethodDecl *MD = Component.getFunctionDecl();
1963 
1964       std::string Str =
1965         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1966                                     MD);
1967       Out << Str;
1968       if (MD->isPure())
1969         Out << " [pure]";
1970 
1971       if (MD->isDeleted())
1972         Out << " [deleted]";
1973 
1974       ThunkInfo Thunk = VTableThunks.lookup(I);
1975       if (!Thunk.isEmpty()) {
1976         // If this function pointer has a return adjustment, dump it.
1977         if (!Thunk.Return.isEmpty()) {
1978           Out << "\n       [return adjustment: ";
1979           Out << Thunk.Return.NonVirtual << " non-virtual";
1980 
1981           if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1982             Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
1983             Out << " vbase offset offset";
1984           }
1985 
1986           Out << ']';
1987         }
1988 
1989         // If this function pointer has a 'this' pointer adjustment, dump it.
1990         if (!Thunk.This.isEmpty()) {
1991           Out << "\n       [this adjustment: ";
1992           Out << Thunk.This.NonVirtual << " non-virtual";
1993 
1994           if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1995             Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
1996             Out << " vcall offset offset";
1997           }
1998 
1999           Out << ']';
2000         }
2001       }
2002 
2003       break;
2004     }
2005 
2006     case VTableComponent::CK_CompleteDtorPointer:
2007     case VTableComponent::CK_DeletingDtorPointer: {
2008       bool IsComplete =
2009         Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2010 
2011       const CXXDestructorDecl *DD = Component.getDestructorDecl();
2012 
2013       DD->printQualifiedName(Out);
2014       if (IsComplete)
2015         Out << "() [complete]";
2016       else
2017         Out << "() [deleting]";
2018 
2019       if (DD->isPure())
2020         Out << " [pure]";
2021 
2022       ThunkInfo Thunk = VTableThunks.lookup(I);
2023       if (!Thunk.isEmpty()) {
2024         // If this destructor has a 'this' pointer adjustment, dump it.
2025         if (!Thunk.This.isEmpty()) {
2026           Out << "\n       [this adjustment: ";
2027           Out << Thunk.This.NonVirtual << " non-virtual";
2028 
2029           if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2030             Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2031             Out << " vcall offset offset";
2032           }
2033 
2034           Out << ']';
2035         }
2036       }
2037 
2038       break;
2039     }
2040 
2041     case VTableComponent::CK_UnusedFunctionPointer: {
2042       const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2043 
2044       std::string Str =
2045         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2046                                     MD);
2047       Out << "[unused] " << Str;
2048       if (MD->isPure())
2049         Out << " [pure]";
2050     }
2051 
2052     }
2053 
2054     Out << '\n';
2055 
2056     // Dump the next address point.
2057     uint64_t NextIndex = Index + 1;
2058     if (AddressPointsByIndex.count(NextIndex)) {
2059       if (AddressPointsByIndex.count(NextIndex) == 1) {
2060         const BaseSubobject &Base =
2061           AddressPointsByIndex.find(NextIndex)->second;
2062 
2063         Out << "       -- (";
2064         Base.getBase()->printQualifiedName(Out);
2065         Out << ", " << Base.getBaseOffset().getQuantity();
2066         Out << ") vtable address --\n";
2067       } else {
2068         CharUnits BaseOffset =
2069           AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2070 
2071         // We store the class names in a set to get a stable order.
2072         std::set<std::string> ClassNames;
2073         for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2074              AddressPointsByIndex.lower_bound(NextIndex), E =
2075              AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2076           assert(I->second.getBaseOffset() == BaseOffset &&
2077                  "Invalid base offset!");
2078           const CXXRecordDecl *RD = I->second.getBase();
2079           ClassNames.insert(RD->getQualifiedNameAsString());
2080         }
2081 
2082         for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2083              E = ClassNames.end(); I != E; ++I) {
2084           Out << "       -- (" << *I;
2085           Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2086         }
2087       }
2088     }
2089   }
2090 
2091   Out << '\n';
2092 
2093   if (isBuildingConstructorVTable())
2094     return;
2095 
2096   if (MostDerivedClass->getNumVBases()) {
2097     // We store the virtual base class names and their offsets in a map to get
2098     // a stable order.
2099 
2100     std::map<std::string, CharUnits> ClassNamesAndOffsets;
2101     for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2102          E = VBaseOffsetOffsets.end(); I != E; ++I) {
2103       std::string ClassName = I->first->getQualifiedNameAsString();
2104       CharUnits OffsetOffset = I->second;
2105       ClassNamesAndOffsets.insert(
2106           std::make_pair(ClassName, OffsetOffset));
2107     }
2108 
2109     Out << "Virtual base offset offsets for '";
2110     MostDerivedClass->printQualifiedName(Out);
2111     Out << "' (";
2112     Out << ClassNamesAndOffsets.size();
2113     Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2114 
2115     for (std::map<std::string, CharUnits>::const_iterator I =
2116          ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2117          I != E; ++I)
2118       Out << "   " << I->first << " | " << I->second.getQuantity() << '\n';
2119 
2120     Out << "\n";
2121   }
2122 
2123   if (!Thunks.empty()) {
2124     // We store the method names in a map to get a stable order.
2125     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2126 
2127     for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2128          I != E; ++I) {
2129       const CXXMethodDecl *MD = I->first;
2130       std::string MethodName =
2131         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2132                                     MD);
2133 
2134       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2135     }
2136 
2137     for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2138          MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2139          I != E; ++I) {
2140       const std::string &MethodName = I->first;
2141       const CXXMethodDecl *MD = I->second;
2142 
2143       ThunkInfoVectorTy ThunksVector = Thunks[MD];
2144       std::sort(ThunksVector.begin(), ThunksVector.end(),
2145                 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2146         assert(LHS.Method == 0 && RHS.Method == 0);
2147         return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
2148       });
2149 
2150       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2151       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2152 
2153       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2154         const ThunkInfo &Thunk = ThunksVector[I];
2155 
2156         Out << llvm::format("%4d | ", I);
2157 
2158         // If this function pointer has a return pointer adjustment, dump it.
2159         if (!Thunk.Return.isEmpty()) {
2160           Out << "return adjustment: " << Thunk.Return.NonVirtual;
2161           Out << " non-virtual";
2162           if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2163             Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
2164             Out << " vbase offset offset";
2165           }
2166 
2167           if (!Thunk.This.isEmpty())
2168             Out << "\n       ";
2169         }
2170 
2171         // If this function pointer has a 'this' pointer adjustment, dump it.
2172         if (!Thunk.This.isEmpty()) {
2173           Out << "this adjustment: ";
2174           Out << Thunk.This.NonVirtual << " non-virtual";
2175 
2176           if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2177             Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2178             Out << " vcall offset offset";
2179           }
2180         }
2181 
2182         Out << '\n';
2183       }
2184 
2185       Out << '\n';
2186     }
2187   }
2188 
2189   // Compute the vtable indices for all the member functions.
2190   // Store them in a map keyed by the index so we'll get a sorted table.
2191   std::map<uint64_t, std::string> IndicesMap;
2192 
2193   for (const auto *MD : MostDerivedClass->methods()) {
2194     // We only want virtual member functions.
2195     if (!MD->isVirtual())
2196       continue;
2197 
2198     std::string MethodName =
2199       PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2200                                   MD);
2201 
2202     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2203       GlobalDecl GD(DD, Dtor_Complete);
2204       assert(MethodVTableIndices.count(GD));
2205       uint64_t VTableIndex = MethodVTableIndices[GD];
2206       IndicesMap[VTableIndex] = MethodName + " [complete]";
2207       IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
2208     } else {
2209       assert(MethodVTableIndices.count(MD));
2210       IndicesMap[MethodVTableIndices[MD]] = MethodName;
2211     }
2212   }
2213 
2214   // Print the vtable indices for all the member functions.
2215   if (!IndicesMap.empty()) {
2216     Out << "VTable indices for '";
2217     MostDerivedClass->printQualifiedName(Out);
2218     Out << "' (" << IndicesMap.size() << " entries).\n";
2219 
2220     for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2221          E = IndicesMap.end(); I != E; ++I) {
2222       uint64_t VTableIndex = I->first;
2223       const std::string &MethodName = I->second;
2224 
2225       Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
2226           << '\n';
2227     }
2228   }
2229 
2230   Out << '\n';
2231 }
2232 }
2233 
2234 VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2235                            const VTableComponent *VTableComponents,
2236                            uint64_t NumVTableThunks,
2237                            const VTableThunkTy *VTableThunks,
2238                            const AddressPointsMapTy &AddressPoints,
2239                            bool IsMicrosoftABI)
2240   : NumVTableComponents(NumVTableComponents),
2241     VTableComponents(new VTableComponent[NumVTableComponents]),
2242     NumVTableThunks(NumVTableThunks),
2243     VTableThunks(new VTableThunkTy[NumVTableThunks]),
2244     AddressPoints(AddressPoints),
2245     IsMicrosoftABI(IsMicrosoftABI) {
2246   std::copy(VTableComponents, VTableComponents+NumVTableComponents,
2247             this->VTableComponents.get());
2248   std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2249             this->VTableThunks.get());
2250   std::sort(this->VTableThunks.get(),
2251             this->VTableThunks.get() + NumVTableThunks,
2252             [](const VTableLayout::VTableThunkTy &LHS,
2253                const VTableLayout::VTableThunkTy &RHS) {
2254     assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2255            "Different thunks should have unique indices!");
2256     return LHS.first < RHS.first;
2257   });
2258 }
2259 
2260 VTableLayout::~VTableLayout() { }
2261 
2262 ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
2263     : VTableContextBase(/*MS=*/false) {}
2264 
2265 ItaniumVTableContext::~ItaniumVTableContext() {
2266   llvm::DeleteContainerSeconds(VTableLayouts);
2267 }
2268 
2269 uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
2270   MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2271   if (I != MethodVTableIndices.end())
2272     return I->second;
2273 
2274   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2275 
2276   computeVTableRelatedInformation(RD);
2277 
2278   I = MethodVTableIndices.find(GD);
2279   assert(I != MethodVTableIndices.end() && "Did not find index!");
2280   return I->second;
2281 }
2282 
2283 CharUnits
2284 ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2285                                                  const CXXRecordDecl *VBase) {
2286   ClassPairTy ClassPair(RD, VBase);
2287 
2288   VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2289     VirtualBaseClassOffsetOffsets.find(ClassPair);
2290   if (I != VirtualBaseClassOffsetOffsets.end())
2291     return I->second;
2292 
2293   VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2294                                      BaseSubobject(RD, CharUnits::Zero()),
2295                                      /*BaseIsVirtual=*/false,
2296                                      /*OffsetInLayoutClass=*/CharUnits::Zero());
2297 
2298   for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2299        Builder.getVBaseOffsetOffsets().begin(),
2300        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2301     // Insert all types.
2302     ClassPairTy ClassPair(RD, I->first);
2303 
2304     VirtualBaseClassOffsetOffsets.insert(
2305         std::make_pair(ClassPair, I->second));
2306   }
2307 
2308   I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2309   assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2310 
2311   return I->second;
2312 }
2313 
2314 static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
2315   SmallVector<VTableLayout::VTableThunkTy, 1>
2316     VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2317 
2318   return new VTableLayout(Builder.getNumVTableComponents(),
2319                           Builder.vtable_component_begin(),
2320                           VTableThunks.size(),
2321                           VTableThunks.data(),
2322                           Builder.getAddressPoints(),
2323                           /*IsMicrosoftABI=*/false);
2324 }
2325 
2326 void
2327 ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
2328   const VTableLayout *&Entry = VTableLayouts[RD];
2329 
2330   // Check if we've computed this information before.
2331   if (Entry)
2332     return;
2333 
2334   ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2335                                /*MostDerivedClassIsVirtual=*/0, RD);
2336   Entry = CreateVTableLayout(Builder);
2337 
2338   MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2339                              Builder.vtable_indices_end());
2340 
2341   // Add the known thunks.
2342   Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2343 
2344   // If we don't have the vbase information for this class, insert it.
2345   // getVirtualBaseOffsetOffset will compute it separately without computing
2346   // the rest of the vtable related information.
2347   if (!RD->getNumVBases())
2348     return;
2349 
2350   const CXXRecordDecl *VBase =
2351     RD->vbases_begin()->getType()->getAsCXXRecordDecl();
2352 
2353   if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2354     return;
2355 
2356   for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2357            I = Builder.getVBaseOffsetOffsets().begin(),
2358            E = Builder.getVBaseOffsetOffsets().end();
2359        I != E; ++I) {
2360     // Insert all types.
2361     ClassPairTy ClassPair(RD, I->first);
2362 
2363     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2364   }
2365 }
2366 
2367 VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2368     const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2369     bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2370   ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2371                                MostDerivedClassIsVirtual, LayoutClass);
2372   return CreateVTableLayout(Builder);
2373 }
2374 
2375 namespace {
2376 
2377 // Vtables in the Microsoft ABI are different from the Itanium ABI.
2378 //
2379 // The main differences are:
2380 //  1. Separate vftable and vbtable.
2381 //
2382 //  2. Each subobject with a vfptr gets its own vftable rather than an address
2383 //     point in a single vtable shared between all the subobjects.
2384 //     Each vftable is represented by a separate section and virtual calls
2385 //     must be done using the vftable which has a slot for the function to be
2386 //     called.
2387 //
2388 //  3. Virtual method definitions expect their 'this' parameter to point to the
2389 //     first vfptr whose table provides a compatible overridden method.  In many
2390 //     cases, this permits the original vf-table entry to directly call
2391 //     the method instead of passing through a thunk.
2392 //
2393 //     A compatible overridden method is one which does not have a non-trivial
2394 //     covariant-return adjustment.
2395 //
2396 //     The first vfptr is the one with the lowest offset in the complete-object
2397 //     layout of the defining class, and the method definition will subtract
2398 //     that constant offset from the parameter value to get the real 'this'
2399 //     value.  Therefore, if the offset isn't really constant (e.g. if a virtual
2400 //     function defined in a virtual base is overridden in a more derived
2401 //     virtual base and these bases have a reverse order in the complete
2402 //     object), the vf-table may require a this-adjustment thunk.
2403 //
2404 //  4. vftables do not contain new entries for overrides that merely require
2405 //     this-adjustment.  Together with #3, this keeps vf-tables smaller and
2406 //     eliminates the need for this-adjustment thunks in many cases, at the cost
2407 //     of often requiring redundant work to adjust the "this" pointer.
2408 //
2409 //  5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2410 //     Vtordisps are emitted into the class layout if a class has
2411 //      a) a user-defined ctor/dtor
2412 //     and
2413 //      b) a method overriding a method in a virtual base.
2414 
2415 class VFTableBuilder {
2416 public:
2417   typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
2418 
2419   typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2420     MethodVFTableLocationsTy;
2421 
2422   typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2423     method_locations_range;
2424 
2425 private:
2426   /// VTables - Global vtable information.
2427   MicrosoftVTableContext &VTables;
2428 
2429   /// Context - The ASTContext which we will use for layout information.
2430   ASTContext &Context;
2431 
2432   /// MostDerivedClass - The most derived class for which we're building this
2433   /// vtable.
2434   const CXXRecordDecl *MostDerivedClass;
2435 
2436   const ASTRecordLayout &MostDerivedClassLayout;
2437 
2438   const VPtrInfo &WhichVFPtr;
2439 
2440   /// FinalOverriders - The final overriders of the most derived class.
2441   const FinalOverriders Overriders;
2442 
2443   /// Components - The components of the vftable being built.
2444   SmallVector<VTableComponent, 64> Components;
2445 
2446   MethodVFTableLocationsTy MethodVFTableLocations;
2447 
2448   /// MethodInfo - Contains information about a method in a vtable.
2449   /// (Used for computing 'this' pointer adjustment thunks.
2450   struct MethodInfo {
2451     /// VBTableIndex - The nonzero index in the vbtable that
2452     /// this method's base has, or zero.
2453     const uint64_t VBTableIndex;
2454 
2455     /// VFTableIndex - The index in the vftable that this method has.
2456     const uint64_t VFTableIndex;
2457 
2458     /// Shadowed - Indicates if this vftable slot is shadowed by
2459     /// a slot for a covariant-return override. If so, it shouldn't be printed
2460     /// or used for vcalls in the most derived class.
2461     bool Shadowed;
2462 
2463     MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2464         : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2465           Shadowed(false) {}
2466 
2467     MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
2468   };
2469 
2470   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2471 
2472   /// MethodInfoMap - The information for all methods in the vftable we're
2473   /// currently building.
2474   MethodInfoMapTy MethodInfoMap;
2475 
2476   typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2477 
2478   /// VTableThunks - The thunks by vftable index in the vftable currently being
2479   /// built.
2480   VTableThunksMapTy VTableThunks;
2481 
2482   typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2483   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2484 
2485   /// Thunks - A map that contains all the thunks needed for all methods in the
2486   /// most derived class for which the vftable is currently being built.
2487   ThunksMapTy Thunks;
2488 
2489   /// AddThunk - Add a thunk for the given method.
2490   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2491     SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2492 
2493     // Check if we have this thunk already.
2494     if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2495         ThunksVector.end())
2496       return;
2497 
2498     ThunksVector.push_back(Thunk);
2499   }
2500 
2501   /// ComputeThisOffset - Returns the 'this' argument offset for the given
2502   /// method, relative to the beginning of the MostDerivedClass.
2503   CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
2504 
2505   void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2506                                    CharUnits ThisOffset, ThisAdjustment &TA);
2507 
2508   /// AddMethod - Add a single virtual member function to the vftable
2509   /// components vector.
2510   void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
2511     if (!TI.isEmpty()) {
2512       VTableThunks[Components.size()] = TI;
2513       AddThunk(MD, TI);
2514     }
2515     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2516       assert(TI.Return.isEmpty() &&
2517              "Destructor can't have return adjustment!");
2518       Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2519     } else {
2520       Components.push_back(VTableComponent::MakeFunction(MD));
2521     }
2522   }
2523 
2524   bool NeedsReturnAdjustingThunk(const CXXMethodDecl *MD);
2525 
2526   /// AddMethods - Add the methods of this base subobject and the relevant
2527   /// subbases to the vftable we're currently laying out.
2528   void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2529                   const CXXRecordDecl *LastVBase,
2530                   BasesSetVectorTy &VisitedBases);
2531 
2532   void LayoutVFTable() {
2533     // FIXME: add support for RTTI when we have proper LLVM support for symbols
2534     // pointing to the middle of a section.
2535 
2536     BasesSetVectorTy VisitedBases;
2537     AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2538                VisitedBases);
2539     assert(Components.size() && "vftable can't be empty");
2540 
2541     assert(MethodVFTableLocations.empty());
2542     for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2543          E = MethodInfoMap.end(); I != E; ++I) {
2544       const CXXMethodDecl *MD = I->first;
2545       const MethodInfo &MI = I->second;
2546       // Skip the methods that the MostDerivedClass didn't override
2547       // and the entries shadowed by return adjusting thunks.
2548       if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2549         continue;
2550       MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2551                                 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
2552       if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2553         MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2554       } else {
2555         MethodVFTableLocations[MD] = Loc;
2556       }
2557     }
2558   }
2559 
2560   void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2561     clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2562     unsigned DiagID = Diags.getCustomDiagID(
2563         DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2564     Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2565   }
2566 
2567 public:
2568   VFTableBuilder(MicrosoftVTableContext &VTables,
2569                  const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
2570       : VTables(VTables),
2571         Context(MostDerivedClass->getASTContext()),
2572         MostDerivedClass(MostDerivedClass),
2573         MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2574         WhichVFPtr(*Which),
2575         Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2576     LayoutVFTable();
2577 
2578     if (Context.getLangOpts().DumpVTableLayouts)
2579       dumpLayout(llvm::outs());
2580   }
2581 
2582   uint64_t getNumThunks() const { return Thunks.size(); }
2583 
2584   ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2585 
2586   ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2587 
2588   method_locations_range vtable_locations() const {
2589     return method_locations_range(MethodVFTableLocations.begin(),
2590                                   MethodVFTableLocations.end());
2591   }
2592 
2593   uint64_t getNumVTableComponents() const { return Components.size(); }
2594 
2595   const VTableComponent *vtable_component_begin() const {
2596     return Components.begin();
2597   }
2598 
2599   const VTableComponent *vtable_component_end() const {
2600     return Components.end();
2601   }
2602 
2603   VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2604     return VTableThunks.begin();
2605   }
2606 
2607   VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2608     return VTableThunks.end();
2609   }
2610 
2611   void dumpLayout(raw_ostream &);
2612 };
2613 
2614 } // end namespace
2615 
2616 /// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2617 /// that define the given method.
2618 struct InitialOverriddenDefinitionCollector {
2619   BasesSetVectorTy Bases;
2620   OverriddenMethodsSetTy VisitedOverriddenMethods;
2621 
2622   bool visit(const CXXMethodDecl *OverriddenMD) {
2623     if (OverriddenMD->size_overridden_methods() == 0)
2624       Bases.insert(OverriddenMD->getParent());
2625     // Don't recurse on this method if we've already collected it.
2626     return VisitedOverriddenMethods.insert(OverriddenMD);
2627   }
2628 };
2629 
2630 static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2631                       CXXBasePath &Path, void *BasesSet) {
2632   BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2633   return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2634 }
2635 
2636 CharUnits
2637 VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
2638   InitialOverriddenDefinitionCollector Collector;
2639   visitAllOverriddenMethods(Overrider.Method, Collector);
2640 
2641   // If there are no overrides then 'this' is located
2642   // in the base that defines the method.
2643   if (Collector.Bases.size() == 0)
2644     return Overrider.Offset;
2645 
2646   CXXBasePaths Paths;
2647   Overrider.Method->getParent()->lookupInBases(BaseInSet, &Collector.Bases,
2648                                                Paths);
2649 
2650   // This will hold the smallest this offset among overridees of MD.
2651   // This implies that an offset of a non-virtual base will dominate an offset
2652   // of a virtual base to potentially reduce the number of thunks required
2653   // in the derived classes that inherit this method.
2654   CharUnits Ret;
2655   bool First = true;
2656 
2657   const ASTRecordLayout &OverriderRDLayout =
2658       Context.getASTRecordLayout(Overrider.Method->getParent());
2659   for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2660        I != E; ++I) {
2661     const CXXBasePath &Path = (*I);
2662     CharUnits ThisOffset = Overrider.Offset;
2663     CharUnits LastVBaseOffset;
2664 
2665     // For each path from the overrider to the parents of the overridden methods,
2666     // traverse the path, calculating the this offset in the most derived class.
2667     for (int J = 0, F = Path.size(); J != F; ++J) {
2668       const CXXBasePathElement &Element = Path[J];
2669       QualType CurTy = Element.Base->getType();
2670       const CXXRecordDecl *PrevRD = Element.Class,
2671                           *CurRD = CurTy->getAsCXXRecordDecl();
2672       const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2673 
2674       if (Element.Base->isVirtual()) {
2675         // The interesting things begin when you have virtual inheritance.
2676         // The final overrider will use a static adjustment equal to the offset
2677         // of the vbase in the final overrider class.
2678         // For example, if the final overrider is in a vbase B of the most
2679         // derived class and it overrides a method of the B's own vbase A,
2680         // it uses A* as "this".  In its prologue, it can cast A* to B* with
2681         // a static offset.  This offset is used regardless of the actual
2682         // offset of A from B in the most derived class, requiring an
2683         // this-adjusting thunk in the vftable if A and B are laid out
2684         // differently in the most derived class.
2685         LastVBaseOffset = ThisOffset =
2686             Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
2687       } else {
2688         ThisOffset += Layout.getBaseClassOffset(CurRD);
2689       }
2690     }
2691 
2692     if (isa<CXXDestructorDecl>(Overrider.Method)) {
2693       if (LastVBaseOffset.isZero()) {
2694         // If a "Base" class has at least one non-virtual base with a virtual
2695         // destructor, the "Base" virtual destructor will take the address
2696         // of the "Base" subobject as the "this" argument.
2697         ThisOffset = Overrider.Offset;
2698       } else {
2699         // A virtual destructor of a virtual base takes the address of the
2700         // virtual base subobject as the "this" argument.
2701         ThisOffset = LastVBaseOffset;
2702       }
2703     }
2704 
2705     if (Ret > ThisOffset || First) {
2706       First = false;
2707       Ret = ThisOffset;
2708     }
2709   }
2710 
2711   assert(!First && "Method not found in the given subobject?");
2712   return Ret;
2713 }
2714 
2715 void VFTableBuilder::CalculateVtordispAdjustment(
2716     FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2717     ThisAdjustment &TA) {
2718   const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2719       MostDerivedClassLayout.getVBaseOffsetsMap();
2720   const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
2721       VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
2722   assert(VBaseMapEntry != VBaseMap.end());
2723 
2724   // If there's no vtordisp or the final overrider is defined in the same vbase
2725   // as the initial declaration, we don't need any vtordisp adjustment.
2726   if (!VBaseMapEntry->second.hasVtorDisp() ||
2727       Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
2728     return;
2729 
2730   // OK, now we know we need to use a vtordisp thunk.
2731   // The implicit vtordisp field is located right before the vbase.
2732   CharUnits VFPtrVBaseOffset = VBaseMapEntry->second.VBaseOffset;
2733   TA.Virtual.Microsoft.VtordispOffset =
2734       (VFPtrVBaseOffset - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
2735 
2736   // A simple vtordisp thunk will suffice if the final overrider is defined
2737   // in either the most derived class or its non-virtual base.
2738   if (Overrider.Method->getParent() == MostDerivedClass ||
2739       !Overrider.VirtualBase)
2740     return;
2741 
2742   // Otherwise, we need to do use the dynamic offset of the final overrider
2743   // in order to get "this" adjustment right.
2744   TA.Virtual.Microsoft.VBPtrOffset =
2745       (VFPtrVBaseOffset + WhichVFPtr.NonVirtualOffset -
2746        MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2747   TA.Virtual.Microsoft.VBOffsetOffset =
2748       Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2749       VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
2750 
2751   TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2752 }
2753 
2754 static void GroupNewVirtualOverloads(
2755     const CXXRecordDecl *RD,
2756     SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2757   // Put the virtual methods into VirtualMethods in the proper order:
2758   // 1) Group overloads by declaration name. New groups are added to the
2759   //    vftable in the order of their first declarations in this class
2760   //    (including overrides and non-virtual methods).
2761   // 2) In each group, new overloads appear in the reverse order of declaration.
2762   typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2763   SmallVector<MethodGroup, 10> Groups;
2764   typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2765   VisitedGroupIndicesTy VisitedGroupIndices;
2766   for (const auto *MD : RD->methods()) {
2767     VisitedGroupIndicesTy::iterator J;
2768     bool Inserted;
2769     std::tie(J, Inserted) = VisitedGroupIndices.insert(
2770         std::make_pair(MD->getDeclName(), Groups.size()));
2771     if (Inserted)
2772       Groups.push_back(MethodGroup());
2773     if (MD->isVirtual())
2774       Groups[J->second].push_back(MD);
2775   }
2776 
2777   for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2778     VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2779 }
2780 
2781 /// We need a return adjusting thunk for this method if its return type is
2782 /// not trivially convertible to the return type of any of its overridden
2783 /// methods.
2784 bool VFTableBuilder::NeedsReturnAdjustingThunk(const CXXMethodDecl *MD) {
2785   OverriddenMethodsSetTy OverriddenMethods;
2786   ComputeAllOverriddenMethods(MD, OverriddenMethods);
2787   for (OverriddenMethodsSetTy::iterator I = OverriddenMethods.begin(),
2788                                         E = OverriddenMethods.end();
2789        I != E; ++I) {
2790     const CXXMethodDecl *OverriddenMD = *I;
2791     BaseOffset Adjustment =
2792         ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD);
2793     if (!Adjustment.isEmpty())
2794       return true;
2795   }
2796   return false;
2797 }
2798 
2799 static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2800   for (const auto &B : RD->bases()) {
2801     if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2802       return true;
2803   }
2804   return false;
2805 }
2806 
2807 void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2808                                 const CXXRecordDecl *LastVBase,
2809                                 BasesSetVectorTy &VisitedBases) {
2810   const CXXRecordDecl *RD = Base.getBase();
2811   if (!RD->isPolymorphic())
2812     return;
2813 
2814   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2815 
2816   // See if this class expands a vftable of the base we look at, which is either
2817   // the one defined by the vfptr base path or the primary base of the current class.
2818   const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2819   CharUnits NextBaseOffset;
2820   if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2821     NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
2822     if (isDirectVBase(NextBase, RD)) {
2823       NextLastVBase = NextBase;
2824       NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2825     } else {
2826       NextBaseOffset =
2827           Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2828     }
2829   } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2830     assert(!Layout.isPrimaryBaseVirtual() &&
2831            "No primary virtual bases in this ABI");
2832     NextBase = PrimaryBase;
2833     NextBaseOffset = Base.getBaseOffset();
2834   }
2835 
2836   if (NextBase) {
2837     AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2838                NextLastVBase, VisitedBases);
2839     if (!VisitedBases.insert(NextBase))
2840       llvm_unreachable("Found a duplicate primary base!");
2841   }
2842 
2843   SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2844   // Put virtual methods in the proper order.
2845   GroupNewVirtualOverloads(RD, VirtualMethods);
2846 
2847   // Now go through all virtual member functions and add them to the current
2848   // vftable. This is done by
2849   //  - replacing overridden methods in their existing slots, as long as they
2850   //    don't require return adjustment; calculating This adjustment if needed.
2851   //  - adding new slots for methods of the current base not present in any
2852   //    sub-bases;
2853   //  - adding new slots for methods that require Return adjustment.
2854   // We keep track of the methods visited in the sub-bases in MethodInfoMap.
2855   for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2856     const CXXMethodDecl *MD = VirtualMethods[I];
2857 
2858     FinalOverriders::OverriderInfo Overrider =
2859         Overriders.getOverrider(MD, Base.getBaseOffset());
2860     const CXXMethodDecl *OverriderMD = Overrider.Method;
2861     const CXXMethodDecl *OverriddenMD =
2862         FindNearestOverriddenMethod(MD, VisitedBases);
2863 
2864     ThisAdjustment ThisAdjustmentOffset;
2865     bool ReturnAdjustingThunk = false;
2866     CharUnits ThisOffset = ComputeThisOffset(Overrider);
2867     ThisAdjustmentOffset.NonVirtual =
2868         (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
2869     if ((OverriddenMD || OverriderMD != MD) &&
2870         WhichVFPtr.getVBaseWithVPtr())
2871       CalculateVtordispAdjustment(Overrider, ThisOffset, ThisAdjustmentOffset);
2872 
2873     if (OverriddenMD) {
2874       // If MD overrides anything in this vftable, we need to update the entries.
2875       MethodInfoMapTy::iterator OverriddenMDIterator =
2876           MethodInfoMap.find(OverriddenMD);
2877 
2878       // If the overridden method went to a different vftable, skip it.
2879       if (OverriddenMDIterator == MethodInfoMap.end())
2880         continue;
2881 
2882       MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2883 
2884       if (!NeedsReturnAdjustingThunk(MD)) {
2885         // No return adjustment needed - just replace the overridden method info
2886         // with the current info.
2887         MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2888                       OverriddenMethodInfo.VFTableIndex);
2889         MethodInfoMap.erase(OverriddenMDIterator);
2890 
2891         assert(!MethodInfoMap.count(MD) &&
2892                "Should not have method info for this method yet!");
2893         MethodInfoMap.insert(std::make_pair(MD, MI));
2894         continue;
2895       }
2896 
2897       // In case we need a return adjustment, we'll add a new slot for
2898       // the overrider. Mark the overriden method as shadowed by the new slot.
2899       OverriddenMethodInfo.Shadowed = true;
2900 
2901       // Force a special name mangling for a return-adjusting thunk
2902       // unless the method is the final overrider without this adjustment.
2903       ReturnAdjustingThunk =
2904           !(MD == OverriderMD && ThisAdjustmentOffset.isEmpty());
2905     } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
2906                MD->size_overridden_methods()) {
2907       // Skip methods that don't belong to the vftable of the current class,
2908       // e.g. each method that wasn't seen in any of the visited sub-bases
2909       // but overrides multiple methods of other sub-bases.
2910       continue;
2911     }
2912 
2913     // If we got here, MD is a method not seen in any of the sub-bases or
2914     // it requires return adjustment. Insert the method info for this method.
2915     unsigned VBIndex =
2916         LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
2917     MethodInfo MI(VBIndex, Components.size());
2918 
2919     assert(!MethodInfoMap.count(MD) &&
2920            "Should not have method info for this method yet!");
2921     MethodInfoMap.insert(std::make_pair(MD, MI));
2922 
2923     // Check if this overrider needs a return adjustment.
2924     // We don't want to do this for pure virtual member functions.
2925     BaseOffset ReturnAdjustmentOffset;
2926     ReturnAdjustment ReturnAdjustment;
2927     if (!OverriderMD->isPure()) {
2928       ReturnAdjustmentOffset =
2929           ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2930     }
2931     if (!ReturnAdjustmentOffset.isEmpty()) {
2932       ReturnAdjustingThunk = true;
2933       ReturnAdjustment.NonVirtual =
2934           ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2935       if (ReturnAdjustmentOffset.VirtualBase) {
2936         const ASTRecordLayout &DerivedLayout =
2937             Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
2938         ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
2939             DerivedLayout.getVBPtrOffset().getQuantity();
2940         ReturnAdjustment.Virtual.Microsoft.VBIndex =
2941             VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2942                                     ReturnAdjustmentOffset.VirtualBase);
2943       }
2944     }
2945 
2946     AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
2947                                      ReturnAdjustingThunk ? MD : 0));
2948   }
2949 }
2950 
2951 static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
2952   for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
2953        E = Path.rend(); I != E; ++I) {
2954     Out << "'";
2955     (*I)->printQualifiedName(Out);
2956     Out << "' in ";
2957   }
2958 }
2959 
2960 static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
2961                                          bool ContinueFirstLine) {
2962   const ReturnAdjustment &R = TI.Return;
2963   bool Multiline = false;
2964   const char *LinePrefix = "\n       ";
2965   if (!R.isEmpty() || TI.Method) {
2966     if (!ContinueFirstLine)
2967       Out << LinePrefix;
2968     Out << "[return adjustment (to type '"
2969         << TI.Method->getReturnType().getCanonicalType().getAsString()
2970         << "'): ";
2971     if (R.Virtual.Microsoft.VBPtrOffset)
2972       Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
2973     if (R.Virtual.Microsoft.VBIndex)
2974       Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
2975     Out << R.NonVirtual << " non-virtual]";
2976     Multiline = true;
2977   }
2978 
2979   const ThisAdjustment &T = TI.This;
2980   if (!T.isEmpty()) {
2981     if (Multiline || !ContinueFirstLine)
2982       Out << LinePrefix;
2983     Out << "[this adjustment: ";
2984     if (!TI.This.Virtual.isEmpty()) {
2985       assert(T.Virtual.Microsoft.VtordispOffset < 0);
2986       Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
2987       if (T.Virtual.Microsoft.VBPtrOffset) {
2988         Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
2989             << " to the left,";
2990         assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
2991         Out << LinePrefix << " vboffset at "
2992             << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
2993       }
2994     }
2995     Out << T.NonVirtual << " non-virtual]";
2996   }
2997 }
2998 
2999 void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3000   Out << "VFTable for ";
3001   PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
3002   Out << "'";
3003   MostDerivedClass->printQualifiedName(Out);
3004   Out << "' (" << Components.size()
3005       << (Components.size() == 1 ? " entry" : " entries") << ").\n";
3006 
3007   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3008     Out << llvm::format("%4d | ", I);
3009 
3010     const VTableComponent &Component = Components[I];
3011 
3012     // Dump the component.
3013     switch (Component.getKind()) {
3014     case VTableComponent::CK_RTTI:
3015       Component.getRTTIDecl()->printQualifiedName(Out);
3016       Out << " RTTI";
3017       break;
3018 
3019     case VTableComponent::CK_FunctionPointer: {
3020       const CXXMethodDecl *MD = Component.getFunctionDecl();
3021 
3022       // FIXME: Figure out how to print the real thunk type, since they can
3023       // differ in the return type.
3024       std::string Str = PredefinedExpr::ComputeName(
3025           PredefinedExpr::PrettyFunctionNoVirtual, MD);
3026       Out << Str;
3027       if (MD->isPure())
3028         Out << " [pure]";
3029 
3030       if (MD->isDeleted()) {
3031         ErrorUnsupported("deleted methods", MD->getLocation());
3032         Out << " [deleted]";
3033       }
3034 
3035       ThunkInfo Thunk = VTableThunks.lookup(I);
3036       if (!Thunk.isEmpty())
3037         dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3038 
3039       break;
3040     }
3041 
3042     case VTableComponent::CK_DeletingDtorPointer: {
3043       const CXXDestructorDecl *DD = Component.getDestructorDecl();
3044 
3045       DD->printQualifiedName(Out);
3046       Out << "() [scalar deleting]";
3047 
3048       if (DD->isPure())
3049         Out << " [pure]";
3050 
3051       ThunkInfo Thunk = VTableThunks.lookup(I);
3052       if (!Thunk.isEmpty()) {
3053         assert(Thunk.Return.isEmpty() &&
3054                "No return adjustment needed for destructors!");
3055         dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3056       }
3057 
3058       break;
3059     }
3060 
3061     default:
3062       DiagnosticsEngine &Diags = Context.getDiagnostics();
3063       unsigned DiagID = Diags.getCustomDiagID(
3064           DiagnosticsEngine::Error,
3065           "Unexpected vftable component type %0 for component number %1");
3066       Diags.Report(MostDerivedClass->getLocation(), DiagID)
3067           << I << Component.getKind();
3068     }
3069 
3070     Out << '\n';
3071   }
3072 
3073   Out << '\n';
3074 
3075   if (!Thunks.empty()) {
3076     // We store the method names in a map to get a stable order.
3077     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3078 
3079     for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3080          I != E; ++I) {
3081       const CXXMethodDecl *MD = I->first;
3082       std::string MethodName = PredefinedExpr::ComputeName(
3083           PredefinedExpr::PrettyFunctionNoVirtual, MD);
3084 
3085       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3086     }
3087 
3088     for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3089              I = MethodNamesAndDecls.begin(),
3090              E = MethodNamesAndDecls.end();
3091          I != E; ++I) {
3092       const std::string &MethodName = I->first;
3093       const CXXMethodDecl *MD = I->second;
3094 
3095       ThunkInfoVectorTy ThunksVector = Thunks[MD];
3096       std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
3097                        [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3098         // Keep different thunks with the same adjustments in the order they
3099         // were put into the vector.
3100         return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
3101       });
3102 
3103       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3104       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3105 
3106       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3107         const ThunkInfo &Thunk = ThunksVector[I];
3108 
3109         Out << llvm::format("%4d | ", I);
3110         dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
3111         Out << '\n';
3112       }
3113 
3114       Out << '\n';
3115     }
3116   }
3117 
3118   Out.flush();
3119 }
3120 
3121 static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3122                           const llvm::ArrayRef<const CXXRecordDecl *> &B) {
3123   for (llvm::ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(),
3124                                                        E = B.end();
3125        I != E; ++I) {
3126     if (A.count(*I))
3127       return true;
3128   }
3129   return false;
3130 }
3131 
3132 static bool rebucketPaths(VPtrInfoVector &Paths);
3133 
3134 /// Produces MSVC-compatible vbtable data.  The symbols produced by this
3135 /// algorithm match those produced by MSVC 2012 and newer, which is different
3136 /// from MSVC 2010.
3137 ///
3138 /// MSVC 2012 appears to minimize the vbtable names using the following
3139 /// algorithm.  First, walk the class hierarchy in the usual order, depth first,
3140 /// left to right, to find all of the subobjects which contain a vbptr field.
3141 /// Visiting each class node yields a list of inheritance paths to vbptrs.  Each
3142 /// record with a vbptr creates an initially empty path.
3143 ///
3144 /// To combine paths from child nodes, the paths are compared to check for
3145 /// ambiguity.  Paths are "ambiguous" if multiple paths have the same set of
3146 /// components in the same order.  Each group of ambiguous paths is extended by
3147 /// appending the class of the base from which it came.  If the current class
3148 /// node produced an ambiguous path, its path is extended with the current class.
3149 /// After extending paths, MSVC again checks for ambiguity, and extends any
3150 /// ambiguous path which wasn't already extended.  Because each node yields an
3151 /// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3152 /// to produce an unambiguous set of paths.
3153 ///
3154 /// TODO: Presumably vftables use the same algorithm.
3155 void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3156                                                 const CXXRecordDecl *RD,
3157                                                 VPtrInfoVector &Paths) {
3158   assert(Paths.empty());
3159   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3160 
3161   // Base case: this subobject has its own vptr.
3162   if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3163     Paths.push_back(new VPtrInfo(RD));
3164 
3165   // Recursive case: get all the vbtables from our bases and remove anything
3166   // that shares a virtual base.
3167   llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
3168   for (const auto &B : RD->bases()) {
3169     const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3170     if (B.isVirtual() && VBasesSeen.count(Base))
3171       continue;
3172 
3173     if (!Base->isDynamicClass())
3174       continue;
3175 
3176     const VPtrInfoVector &BasePaths =
3177         ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3178 
3179     for (VPtrInfo *BaseInfo : BasePaths) {
3180       // Don't include the path if it goes through a virtual base that we've
3181       // already included.
3182       if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
3183         continue;
3184 
3185       // Copy the path and adjust it as necessary.
3186       VPtrInfo *P = new VPtrInfo(*BaseInfo);
3187 
3188       // We mangle Base into the path if the path would've been ambiguous and it
3189       // wasn't already extended with Base.
3190       if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3191         P->NextBaseToMangle = Base;
3192 
3193       // Keep track of the full path.
3194       // FIXME: Why do we need this?
3195       P->PathToBaseWithVPtr.insert(P->PathToBaseWithVPtr.begin(), Base);
3196 
3197       // Keep track of which vtable the derived class is going to extend with
3198       // new methods or bases.  We append to either the vftable of our primary
3199       // base, or the first non-virtual base that has a vbtable.
3200       if (P->ReusingBase == Base &&
3201           Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3202                                : Layout.getPrimaryBase()))
3203         P->ReusingBase = RD;
3204 
3205       // Keep track of the full adjustment from the MDC to this vtable.  The
3206       // adjustment is captured by an optional vbase and a non-virtual offset.
3207       if (B.isVirtual())
3208         P->ContainingVBases.push_back(Base);
3209       else if (P->ContainingVBases.empty())
3210         P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3211 
3212       // Update the full offset in the MDC.
3213       P->FullOffsetInMDC = P->NonVirtualOffset;
3214       if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3215         P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3216 
3217       Paths.push_back(P);
3218     }
3219 
3220     if (B.isVirtual())
3221       VBasesSeen.insert(Base);
3222 
3223     // After visiting any direct base, we've transitively visited all of its
3224     // morally virtual bases.
3225     for (const auto &VB : Base->vbases())
3226       VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
3227   }
3228 
3229   // Sort the paths into buckets, and if any of them are ambiguous, extend all
3230   // paths in ambiguous buckets.
3231   bool Changed = true;
3232   while (Changed)
3233     Changed = rebucketPaths(Paths);
3234 }
3235 
3236 static bool extendPath(VPtrInfo *P) {
3237   if (P->NextBaseToMangle) {
3238     P->MangledPath.push_back(P->NextBaseToMangle);
3239     P->NextBaseToMangle = 0;  // Prevent the path from being extended twice.
3240     return true;
3241   }
3242   return false;
3243 }
3244 
3245 static bool rebucketPaths(VPtrInfoVector &Paths) {
3246   // What we're essentially doing here is bucketing together ambiguous paths.
3247   // Any bucket with more than one path in it gets extended by NextBase, which
3248   // is usually the direct base of the inherited the vbptr.  This code uses a
3249   // sorted vector to implement a multiset to form the buckets.  Note that the
3250   // ordering is based on pointers, but it doesn't change our output order.  The
3251   // current algorithm is designed to match MSVC 2012's names.
3252   VPtrInfoVector PathsSorted(Paths);
3253   std::sort(PathsSorted.begin(), PathsSorted.end(),
3254             [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3255     return LHS->MangledPath < RHS->MangledPath;
3256   });
3257   bool Changed = false;
3258   for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3259     // Scan forward to find the end of the bucket.
3260     size_t BucketStart = I;
3261     do {
3262       ++I;
3263     } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3264                            PathsSorted[I]->MangledPath);
3265 
3266     // If this bucket has multiple paths, extend them all.
3267     if (I - BucketStart > 1) {
3268       for (size_t II = BucketStart; II != I; ++II)
3269         Changed |= extendPath(PathsSorted[II]);
3270       assert(Changed && "no paths were extended to fix ambiguity");
3271     }
3272   }
3273   return Changed;
3274 }
3275 
3276 MicrosoftVTableContext::~MicrosoftVTableContext() {
3277   llvm::DeleteContainerSeconds(VFPtrLocations);
3278   llvm::DeleteContainerSeconds(VFTableLayouts);
3279   llvm::DeleteContainerSeconds(VBaseInfo);
3280 }
3281 
3282 void MicrosoftVTableContext::computeVTableRelatedInformation(
3283     const CXXRecordDecl *RD) {
3284   assert(RD->isDynamicClass());
3285 
3286   // Check if we've computed this information before.
3287   if (VFPtrLocations.count(RD))
3288     return;
3289 
3290   const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3291 
3292   VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3293   computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3294   VFPtrLocations[RD] = VFPtrs;
3295 
3296   MethodVFTableLocationsTy NewMethodLocations;
3297   for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
3298        I != E; ++I) {
3299     VFTableBuilder Builder(*this, RD, *I);
3300 
3301     VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
3302     assert(VFTableLayouts.count(id) == 0);
3303     SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3304         Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
3305     VFTableLayouts[id] = new VTableLayout(
3306         Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3307         VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3308     Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3309 
3310     for (const auto &Loc : Builder.vtable_locations()) {
3311       GlobalDecl GD = Loc.first;
3312       MethodVFTableLocation NewLoc = Loc.second;
3313       auto M = NewMethodLocations.find(GD);
3314       if (M == NewMethodLocations.end() || NewLoc < M->second)
3315         NewMethodLocations[GD] = NewLoc;
3316     }
3317   }
3318 
3319   MethodVFTableLocations.insert(NewMethodLocations.begin(),
3320                                 NewMethodLocations.end());
3321   if (Context.getLangOpts().DumpVTableLayouts)
3322     dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
3323 }
3324 
3325 void MicrosoftVTableContext::dumpMethodLocations(
3326     const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3327     raw_ostream &Out) {
3328   // Compute the vtable indices for all the member functions.
3329   // Store them in a map keyed by the location so we'll get a sorted table.
3330   std::map<MethodVFTableLocation, std::string> IndicesMap;
3331   bool HasNonzeroOffset = false;
3332 
3333   for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3334        E = NewMethods.end(); I != E; ++I) {
3335     const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3336     assert(MD->isVirtual());
3337 
3338     std::string MethodName = PredefinedExpr::ComputeName(
3339         PredefinedExpr::PrettyFunctionNoVirtual, MD);
3340 
3341     if (isa<CXXDestructorDecl>(MD)) {
3342       IndicesMap[I->second] = MethodName + " [scalar deleting]";
3343     } else {
3344       IndicesMap[I->second] = MethodName;
3345     }
3346 
3347     if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
3348       HasNonzeroOffset = true;
3349   }
3350 
3351   // Print the vtable indices for all the member functions.
3352   if (!IndicesMap.empty()) {
3353     Out << "VFTable indices for ";
3354     Out << "'";
3355     RD->printQualifiedName(Out);
3356     Out << "' (" << IndicesMap.size()
3357         << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
3358 
3359     CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3360     uint64_t LastVBIndex = 0;
3361     for (std::map<MethodVFTableLocation, std::string>::const_iterator
3362              I = IndicesMap.begin(),
3363              E = IndicesMap.end();
3364          I != E; ++I) {
3365       CharUnits VFPtrOffset = I->first.VFPtrOffset;
3366       uint64_t VBIndex = I->first.VBTableIndex;
3367       if (HasNonzeroOffset &&
3368           (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3369         assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3370         Out << " -- accessible via ";
3371         if (VBIndex)
3372           Out << "vbtable index " << VBIndex << ", ";
3373         Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3374         LastVFPtrOffset = VFPtrOffset;
3375         LastVBIndex = VBIndex;
3376       }
3377 
3378       uint64_t VTableIndex = I->first.Index;
3379       const std::string &MethodName = I->second;
3380       Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3381     }
3382     Out << '\n';
3383   }
3384 
3385   Out.flush();
3386 }
3387 
3388 const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
3389     const CXXRecordDecl *RD) {
3390   VirtualBaseInfo *VBI;
3391 
3392   {
3393     // Get or create a VBI for RD.  Don't hold a reference to the DenseMap cell,
3394     // as it may be modified and rehashed under us.
3395     VirtualBaseInfo *&Entry = VBaseInfo[RD];
3396     if (Entry)
3397       return Entry;
3398     Entry = VBI = new VirtualBaseInfo();
3399   }
3400 
3401   computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
3402 
3403   // First, see if the Derived class shared the vbptr with a non-virtual base.
3404   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3405   if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
3406     // If the Derived class shares the vbptr with a non-virtual base, the shared
3407     // virtual bases come first so that the layout is the same.
3408     const VirtualBaseInfo *BaseInfo =
3409         computeVBTableRelatedInformation(VBPtrBase);
3410     VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3411                                BaseInfo->VBTableIndices.end());
3412   }
3413 
3414   // New vbases are added to the end of the vbtable.
3415   // Skip the self entry and vbases visited in the non-virtual base, if any.
3416   unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
3417   for (const auto &VB : RD->vbases()) {
3418     const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
3419     if (!VBI->VBTableIndices.count(CurVBase))
3420       VBI->VBTableIndices[CurVBase] = VBTableIndex++;
3421   }
3422 
3423   return VBI;
3424 }
3425 
3426 unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3427                                                  const CXXRecordDecl *VBase) {
3428   const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3429   assert(VBInfo->VBTableIndices.count(VBase));
3430   return VBInfo->VBTableIndices.find(VBase)->second;
3431 }
3432 
3433 const VPtrInfoVector &
3434 MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
3435   return computeVBTableRelatedInformation(RD)->VBPtrPaths;
3436 }
3437 
3438 const VPtrInfoVector &
3439 MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3440   computeVTableRelatedInformation(RD);
3441 
3442   assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3443   return *VFPtrLocations[RD];
3444 }
3445 
3446 const VTableLayout &
3447 MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3448                                          CharUnits VFPtrOffset) {
3449   computeVTableRelatedInformation(RD);
3450 
3451   VFTableIdTy id(RD, VFPtrOffset);
3452   assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3453   return *VFTableLayouts[id];
3454 }
3455 
3456 const MicrosoftVTableContext::MethodVFTableLocation &
3457 MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3458   assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3459          "Only use this method for virtual methods or dtors");
3460   if (isa<CXXDestructorDecl>(GD.getDecl()))
3461     assert(GD.getDtorType() == Dtor_Deleting);
3462 
3463   MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3464   if (I != MethodVFTableLocations.end())
3465     return I->second;
3466 
3467   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3468 
3469   computeVTableRelatedInformation(RD);
3470 
3471   I = MethodVFTableLocations.find(GD);
3472   assert(I != MethodVFTableLocations.end() && "Did not find index!");
3473   return I->second;
3474 }
3475