Coverage Report

Created: 2024-01-17 10:31

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