CGVTables.cpp revision 82abeaed0b565e819407b523ed73aa5a4185b27f
1//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "CGCXXABI.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Frontend/CodeGenOptions.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/SetVector.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/Format.h"
24#include <algorithm>
25#include <cstdio>
26
27using namespace clang;
28using namespace CodeGen;
29
30namespace {
31
32/// BaseOffset - Represents an offset from a derived class to a direct or
33/// indirect base class.
34struct BaseOffset {
35  /// DerivedClass - The derived class.
36  const CXXRecordDecl *DerivedClass;
37
38  /// VirtualBase - If the path from the derived class to the base class
39  /// involves a virtual base class, this holds its declaration.
40  const CXXRecordDecl *VirtualBase;
41
42  /// NonVirtualOffset - The offset from the derived class to the base class.
43  /// (Or the offset from the virtual base class to the base class, if the
44  /// path from the derived class to the base class involves a virtual base
45  /// class.
46  int64_t NonVirtualOffset;
47
48  BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { }
49  BaseOffset(const CXXRecordDecl *DerivedClass,
50             const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset)
51    : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
52    NonVirtualOffset(NonVirtualOffset) { }
53
54  bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; }
55};
56
57/// FinalOverriders - Contains the final overrider member functions for all
58/// member functions in the base subobjects of a class.
59class FinalOverriders {
60public:
61  /// OverriderInfo - Information about a final overrider.
62  struct OverriderInfo {
63    /// Method - The method decl of the overrider.
64    const CXXMethodDecl *Method;
65
66    /// Offset - the base offset of the overrider in the layout class.
67    CharUnits Offset;
68
69    OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
70  };
71
72private:
73  /// MostDerivedClass - The most derived class for which the final overriders
74  /// are stored.
75  const CXXRecordDecl *MostDerivedClass;
76
77  /// MostDerivedClassOffset - If we're building final overriders for a
78  /// construction vtable, this holds the offset from the layout class to the
79  /// most derived class.
80  const uint64_t MostDerivedClassOffset;
81
82  /// LayoutClass - The class we're using for layout information. Will be
83  /// different than the most derived class if the final overriders are for a
84  /// construction vtable.
85  const CXXRecordDecl *LayoutClass;
86
87  ASTContext &Context;
88
89  /// MostDerivedClassLayout - the AST record layout of the most derived class.
90  const ASTRecordLayout &MostDerivedClassLayout;
91
92  /// MethodBaseOffsetPairTy - Uniquely identifies a member function
93  /// in a base subobject.
94  typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
95
96  typedef llvm::DenseMap<MethodBaseOffsetPairTy,
97                         OverriderInfo> OverridersMapTy;
98
99  /// OverridersMap - The final overriders for all virtual member functions of
100  /// all the base subobjects of the most derived class.
101  OverridersMapTy OverridersMap;
102
103  /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
104  /// as a record decl and a subobject number) and its offsets in the most
105  /// derived class as well as the layout class.
106  typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
107                         CharUnits> SubobjectOffsetMapTy;
108
109  typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
110
111  /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
112  /// given base.
113  void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
114                          CharUnits OffsetInLayoutClass,
115                          SubobjectOffsetMapTy &SubobjectOffsets,
116                          SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
117                          SubobjectCountMapTy &SubobjectCounts);
118
119  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
120
121  /// dump - dump the final overriders for a base subobject, and all its direct
122  /// and indirect base subobjects.
123  void dump(llvm::raw_ostream &Out, BaseSubobject Base,
124            VisitedVirtualBasesSetTy& VisitedVirtualBases);
125
126public:
127  FinalOverriders(const CXXRecordDecl *MostDerivedClass,
128                  uint64_t MostDerivedClassOffset,
129                  const CXXRecordDecl *LayoutClass);
130
131  /// getOverrider - Get the final overrider for the given method declaration in
132  /// the subobject with the given base offset.
133  OverriderInfo getOverrider(const CXXMethodDecl *MD,
134                             CharUnits BaseOffset) const {
135    assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
136           "Did not find overrider!");
137
138    return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
139  }
140
141  /// dump - dump the final overriders.
142  void dump() {
143    VisitedVirtualBasesSetTy VisitedVirtualBases;
144    dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
145         VisitedVirtualBases);
146  }
147
148};
149
150#define DUMP_OVERRIDERS 0
151
152FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
153                                 uint64_t MostDerivedClassOffset,
154                                 const CXXRecordDecl *LayoutClass)
155  : MostDerivedClass(MostDerivedClass),
156  MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
157  Context(MostDerivedClass->getASTContext()),
158  MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
159
160  // Compute base offsets.
161  SubobjectOffsetMapTy SubobjectOffsets;
162  SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
163  SubobjectCountMapTy SubobjectCounts;
164  ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
165                     /*IsVirtual=*/false,
166                     Context.toCharUnitsFromBits(MostDerivedClassOffset),
167                     SubobjectOffsets, SubobjectLayoutClassOffsets,
168                     SubobjectCounts);
169
170  // Get the the final overriders.
171  CXXFinalOverriderMap FinalOverriders;
172  MostDerivedClass->getFinalOverriders(FinalOverriders);
173
174  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
175       E = FinalOverriders.end(); I != E; ++I) {
176    const CXXMethodDecl *MD = I->first;
177    const OverridingMethods& Methods = I->second;
178
179    for (OverridingMethods::const_iterator I = Methods.begin(),
180         E = Methods.end(); I != E; ++I) {
181      unsigned SubobjectNumber = I->first;
182      assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
183                                                   SubobjectNumber)) &&
184             "Did not find subobject offset!");
185
186      CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
187                                                            SubobjectNumber)];
188
189      assert(I->second.size() == 1 && "Final overrider is not unique!");
190      const UniqueVirtualMethod &Method = I->second.front();
191
192      const CXXRecordDecl *OverriderRD = Method.Method->getParent();
193      assert(SubobjectLayoutClassOffsets.count(
194             std::make_pair(OverriderRD, Method.Subobject))
195             && "Did not find subobject offset!");
196      CharUnits OverriderOffset =
197        SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
198                                                   Method.Subobject)];
199
200      OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
201      assert(!Overrider.Method && "Overrider should not exist yet!");
202
203      Overrider.Offset = OverriderOffset;
204      Overrider.Method = Method.Method;
205    }
206  }
207
208#if DUMP_OVERRIDERS
209  // And dump them (for now).
210  dump();
211#endif
212}
213
214static BaseOffset ComputeBaseOffset(ASTContext &Context,
215                                    const CXXRecordDecl *DerivedRD,
216                                    const CXXBasePath &Path) {
217  int64_t NonVirtualOffset = 0;
218
219  unsigned NonVirtualStart = 0;
220  const CXXRecordDecl *VirtualBase = 0;
221
222  // First, look for the virtual base class.
223  for (unsigned I = 0, E = Path.size(); I != E; ++I) {
224    const CXXBasePathElement &Element = Path[I];
225
226    if (Element.Base->isVirtual()) {
227      // FIXME: Can we break when we find the first virtual base?
228      // (If we can't, can't we just iterate over the path in reverse order?)
229      NonVirtualStart = I + 1;
230      QualType VBaseType = Element.Base->getType();
231      VirtualBase =
232        cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
233    }
234  }
235
236  // Now compute the non-virtual offset.
237  for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
238    const CXXBasePathElement &Element = Path[I];
239
240    // Check the base class offset.
241    const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
242
243    const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
244    const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
245
246    NonVirtualOffset += Layout.getBaseClassOffsetInBits(Base);
247  }
248
249  // FIXME: This should probably use CharUnits or something. Maybe we should
250  // even change the base offsets in ASTRecordLayout to be specified in
251  // CharUnits.
252  return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8);
253
254}
255
256static BaseOffset ComputeBaseOffset(ASTContext &Context,
257                                    const CXXRecordDecl *BaseRD,
258                                    const CXXRecordDecl *DerivedRD) {
259  CXXBasePaths Paths(/*FindAmbiguities=*/false,
260                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
261
262  if (!const_cast<CXXRecordDecl *>(DerivedRD)->
263      isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
264    assert(false && "Class must be derived from the passed in base class!");
265    return BaseOffset();
266  }
267
268  return ComputeBaseOffset(Context, DerivedRD, Paths.front());
269}
270
271static BaseOffset
272ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
273                                  const CXXMethodDecl *DerivedMD,
274                                  const CXXMethodDecl *BaseMD) {
275  const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
276  const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
277
278  // Canonicalize the return types.
279  CanQualType CanDerivedReturnType =
280    Context.getCanonicalType(DerivedFT->getResultType());
281  CanQualType CanBaseReturnType =
282    Context.getCanonicalType(BaseFT->getResultType());
283
284  assert(CanDerivedReturnType->getTypeClass() ==
285         CanBaseReturnType->getTypeClass() &&
286         "Types must have same type class!");
287
288  if (CanDerivedReturnType == CanBaseReturnType) {
289    // No adjustment needed.
290    return BaseOffset();
291  }
292
293  if (isa<ReferenceType>(CanDerivedReturnType)) {
294    CanDerivedReturnType =
295      CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
296    CanBaseReturnType =
297      CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
298  } else if (isa<PointerType>(CanDerivedReturnType)) {
299    CanDerivedReturnType =
300      CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
301    CanBaseReturnType =
302      CanBaseReturnType->getAs<PointerType>()->getPointeeType();
303  } else {
304    assert(false && "Unexpected return type!");
305  }
306
307  // We need to compare unqualified types here; consider
308  //   const T *Base::foo();
309  //   T *Derived::foo();
310  if (CanDerivedReturnType.getUnqualifiedType() ==
311      CanBaseReturnType.getUnqualifiedType()) {
312    // No adjustment needed.
313    return BaseOffset();
314  }
315
316  const CXXRecordDecl *DerivedRD =
317    cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
318
319  const CXXRecordDecl *BaseRD =
320    cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
321
322  return ComputeBaseOffset(Context, BaseRD, DerivedRD);
323}
324
325void
326FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
327                              CharUnits OffsetInLayoutClass,
328                              SubobjectOffsetMapTy &SubobjectOffsets,
329                              SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
330                              SubobjectCountMapTy &SubobjectCounts) {
331  const CXXRecordDecl *RD = Base.getBase();
332
333  unsigned SubobjectNumber = 0;
334  if (!IsVirtual)
335    SubobjectNumber = ++SubobjectCounts[RD];
336
337  // Set up the subobject to offset mapping.
338  assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
339         && "Subobject offset already exists!");
340  assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
341         && "Subobject offset already exists!");
342
343  SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
344  SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
345    OffsetInLayoutClass;
346
347  // Traverse our bases.
348  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
349       E = RD->bases_end(); I != E; ++I) {
350    const CXXRecordDecl *BaseDecl =
351      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
352
353    CharUnits BaseOffset;
354    CharUnits BaseOffsetInLayoutClass;
355    if (I->isVirtual()) {
356      // Check if we've visited this virtual base before.
357      if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
358        continue;
359
360      const ASTRecordLayout &LayoutClassLayout =
361        Context.getASTRecordLayout(LayoutClass);
362
363      BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
364      BaseOffsetInLayoutClass =
365        LayoutClassLayout.getVBaseClassOffset(BaseDecl);
366    } else {
367      const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
368      CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
369
370      BaseOffset = Base.getBaseOffset() + Offset;
371      BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
372    }
373
374    ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
375                       I->isVirtual(), BaseOffsetInLayoutClass,
376                       SubobjectOffsets, SubobjectLayoutClassOffsets,
377                       SubobjectCounts);
378  }
379}
380
381void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base,
382                           VisitedVirtualBasesSetTy &VisitedVirtualBases) {
383  const CXXRecordDecl *RD = Base.getBase();
384  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
385
386  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
387       E = RD->bases_end(); I != E; ++I) {
388    const CXXRecordDecl *BaseDecl =
389      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
390
391    // Ignore bases that don't have any virtual member functions.
392    if (!BaseDecl->isPolymorphic())
393      continue;
394
395    CharUnits BaseOffset;
396    if (I->isVirtual()) {
397      if (!VisitedVirtualBases.insert(BaseDecl)) {
398        // We've visited this base before.
399        continue;
400      }
401
402      BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
403    } else {
404      BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
405    }
406
407    dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
408  }
409
410  Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
411  Out << Base.getBaseOffset().getQuantity() << ")\n";
412
413  // Now dump the overriders for this base subobject.
414  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
415       E = RD->method_end(); I != E; ++I) {
416    const CXXMethodDecl *MD = *I;
417
418    if (!MD->isVirtual())
419      continue;
420
421    OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
422
423    Out << "  " << MD->getQualifiedNameAsString() << " - (";
424    Out << Overrider.Method->getQualifiedNameAsString();
425    Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
426
427    BaseOffset Offset;
428    if (!Overrider.Method->isPure())
429      Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
430
431    if (!Offset.isEmpty()) {
432      Out << " [ret-adj: ";
433      if (Offset.VirtualBase)
434        Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
435
436      Out << Offset.NonVirtualOffset << " nv]";
437    }
438
439    Out << "\n";
440  }
441}
442
443/// VTableComponent - Represents a single component in a vtable.
444class VTableComponent {
445public:
446  enum Kind {
447    CK_VCallOffset,
448    CK_VBaseOffset,
449    CK_OffsetToTop,
450    CK_RTTI,
451    CK_FunctionPointer,
452
453    /// CK_CompleteDtorPointer - A pointer to the complete destructor.
454    CK_CompleteDtorPointer,
455
456    /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
457    CK_DeletingDtorPointer,
458
459    /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
460    /// will end up never being called. Such vtable function pointers are
461    /// represented as a CK_UnusedFunctionPointer.
462    CK_UnusedFunctionPointer
463  };
464
465  static VTableComponent MakeVCallOffset(int64_t Offset) {
466    return VTableComponent(CK_VCallOffset, Offset);
467  }
468
469  static VTableComponent MakeVBaseOffset(int64_t Offset) {
470    return VTableComponent(CK_VBaseOffset, Offset);
471  }
472
473  static VTableComponent MakeOffsetToTop(int64_t Offset) {
474    return VTableComponent(CK_OffsetToTop, Offset);
475  }
476
477  static VTableComponent MakeRTTI(const CXXRecordDecl *RD) {
478    return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
479  }
480
481  static VTableComponent MakeFunction(const CXXMethodDecl *MD) {
482    assert(!isa<CXXDestructorDecl>(MD) &&
483           "Don't use MakeFunction with destructors!");
484
485    return VTableComponent(CK_FunctionPointer,
486                           reinterpret_cast<uintptr_t>(MD));
487  }
488
489  static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
490    return VTableComponent(CK_CompleteDtorPointer,
491                           reinterpret_cast<uintptr_t>(DD));
492  }
493
494  static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
495    return VTableComponent(CK_DeletingDtorPointer,
496                           reinterpret_cast<uintptr_t>(DD));
497  }
498
499  static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
500    assert(!isa<CXXDestructorDecl>(MD) &&
501           "Don't use MakeUnusedFunction with destructors!");
502    return VTableComponent(CK_UnusedFunctionPointer,
503                           reinterpret_cast<uintptr_t>(MD));
504  }
505
506  static VTableComponent getFromOpaqueInteger(uint64_t I) {
507    return VTableComponent(I);
508  }
509
510  /// getKind - Get the kind of this vtable component.
511  Kind getKind() const {
512    return (Kind)(Value & 0x7);
513  }
514
515  int64_t getVCallOffset() const {
516    assert(getKind() == CK_VCallOffset && "Invalid component kind!");
517
518    return getOffset();
519  }
520
521  int64_t getVBaseOffset() const {
522    assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
523
524    return getOffset();
525  }
526
527  int64_t getOffsetToTop() const {
528    assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
529
530    return getOffset();
531  }
532
533  const CXXRecordDecl *getRTTIDecl() const {
534    assert(getKind() == CK_RTTI && "Invalid component kind!");
535
536    return reinterpret_cast<CXXRecordDecl *>(getPointer());
537  }
538
539  const CXXMethodDecl *getFunctionDecl() const {
540    assert(getKind() == CK_FunctionPointer);
541
542    return reinterpret_cast<CXXMethodDecl *>(getPointer());
543  }
544
545  const CXXDestructorDecl *getDestructorDecl() const {
546    assert((getKind() == CK_CompleteDtorPointer ||
547            getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
548
549    return reinterpret_cast<CXXDestructorDecl *>(getPointer());
550  }
551
552  const CXXMethodDecl *getUnusedFunctionDecl() const {
553    assert(getKind() == CK_UnusedFunctionPointer);
554
555    return reinterpret_cast<CXXMethodDecl *>(getPointer());
556  }
557
558private:
559  VTableComponent(Kind ComponentKind, int64_t Offset) {
560    assert((ComponentKind == CK_VCallOffset ||
561            ComponentKind == CK_VBaseOffset ||
562            ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
563    assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
564
565    Value = ((Offset << 3) | ComponentKind);
566  }
567
568  VTableComponent(Kind ComponentKind, uintptr_t Ptr) {
569    assert((ComponentKind == CK_RTTI ||
570            ComponentKind == CK_FunctionPointer ||
571            ComponentKind == CK_CompleteDtorPointer ||
572            ComponentKind == CK_DeletingDtorPointer ||
573            ComponentKind == CK_UnusedFunctionPointer) &&
574            "Invalid component kind!");
575
576    assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
577
578    Value = Ptr | ComponentKind;
579  }
580
581  int64_t getOffset() const {
582    assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
583            getKind() == CK_OffsetToTop) && "Invalid component kind!");
584
585    return Value >> 3;
586  }
587
588  uintptr_t getPointer() const {
589    assert((getKind() == CK_RTTI ||
590            getKind() == CK_FunctionPointer ||
591            getKind() == CK_CompleteDtorPointer ||
592            getKind() == CK_DeletingDtorPointer ||
593            getKind() == CK_UnusedFunctionPointer) &&
594           "Invalid component kind!");
595
596    return static_cast<uintptr_t>(Value & ~7ULL);
597  }
598
599  explicit VTableComponent(uint64_t Value)
600    : Value(Value) { }
601
602  /// The kind is stored in the lower 3 bits of the value. For offsets, we
603  /// make use of the facts that classes can't be larger than 2^55 bytes,
604  /// so we store the offset in the lower part of the 61 bytes that remain.
605  /// (The reason that we're not simply using a PointerIntPair here is that we
606  /// need the offsets to be 64-bit, even when on a 32-bit machine).
607  int64_t Value;
608};
609
610/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
611struct VCallOffsetMap {
612
613  typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy;
614
615  /// Offsets - Keeps track of methods and their offsets.
616  // FIXME: This should be a real map and not a vector.
617  llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets;
618
619  /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
620  /// can share the same vcall offset.
621  static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
622                                         const CXXMethodDecl *RHS);
623
624public:
625  /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
626  /// add was successful, or false if there was already a member function with
627  /// the same signature in the map.
628  bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset);
629
630  /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
631  /// vtable address point) for the given virtual member function.
632  int64_t getVCallOffsetOffset(const CXXMethodDecl *MD);
633
634  // empty - Return whether the offset map is empty or not.
635  bool empty() const { return Offsets.empty(); }
636};
637
638static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
639                                    const CXXMethodDecl *RHS) {
640  ASTContext &C = LHS->getASTContext(); // TODO: thread this down
641  CanQual<FunctionProtoType>
642    LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
643    RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
644
645  // Fast-path matches in the canonical types.
646  if (LT == RT) return true;
647
648  // Force the signatures to match.  We can't rely on the overrides
649  // list here because there isn't necessarily an inheritance
650  // relationship between the two methods.
651  if (LT.getQualifiers() != RT.getQualifiers() ||
652      LT->getNumArgs() != RT->getNumArgs())
653    return false;
654  for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
655    if (LT->getArgType(I) != RT->getArgType(I))
656      return false;
657  return true;
658}
659
660bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
661                                                const CXXMethodDecl *RHS) {
662  assert(LHS->isVirtual() && "LHS must be virtual!");
663  assert(RHS->isVirtual() && "LHS must be virtual!");
664
665  // A destructor can share a vcall offset with another destructor.
666  if (isa<CXXDestructorDecl>(LHS))
667    return isa<CXXDestructorDecl>(RHS);
668
669  // FIXME: We need to check more things here.
670
671  // The methods must have the same name.
672  DeclarationName LHSName = LHS->getDeclName();
673  DeclarationName RHSName = RHS->getDeclName();
674  if (LHSName != RHSName)
675    return false;
676
677  // And the same signatures.
678  return HasSameVirtualSignature(LHS, RHS);
679}
680
681bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
682                                    int64_t OffsetOffset) {
683  // Check if we can reuse an offset.
684  for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
685    if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
686      return false;
687  }
688
689  // Add the offset.
690  Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
691  return true;
692}
693
694int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
695  // Look for an offset.
696  for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
697    if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
698      return Offsets[I].second;
699  }
700
701  assert(false && "Should always find a vcall offset offset!");
702  return 0;
703}
704
705/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
706class VCallAndVBaseOffsetBuilder {
707public:
708  typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
709    VBaseOffsetOffsetsMapTy;
710
711private:
712  /// MostDerivedClass - The most derived class for which we're building vcall
713  /// and vbase offsets.
714  const CXXRecordDecl *MostDerivedClass;
715
716  /// LayoutClass - The class we're using for layout information. Will be
717  /// different than the most derived class if we're building a construction
718  /// vtable.
719  const CXXRecordDecl *LayoutClass;
720
721  /// Context - The ASTContext which we will use for layout information.
722  ASTContext &Context;
723
724  /// Components - vcall and vbase offset components
725  typedef llvm::SmallVector<VTableComponent, 64> VTableComponentVectorTy;
726  VTableComponentVectorTy Components;
727
728  /// VisitedVirtualBases - Visited virtual bases.
729  llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
730
731  /// VCallOffsets - Keeps track of vcall offsets.
732  VCallOffsetMap VCallOffsets;
733
734
735  /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
736  /// relative to the address point.
737  VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
738
739  /// FinalOverriders - The final overriders of the most derived class.
740  /// (Can be null when we're not building a vtable of the most derived class).
741  const FinalOverriders *Overriders;
742
743  /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
744  /// given base subobject.
745  void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
746                               uint64_t RealBaseOffset);
747
748  /// AddVCallOffsets - Add vcall offsets for the given base subobject.
749  void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
750
751  /// AddVBaseOffsets - Add vbase offsets for the given class.
752  void AddVBaseOffsets(const CXXRecordDecl *Base, uint64_t OffsetInLayoutClass);
753
754  /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
755  /// bytes, relative to the vtable address point.
756  int64_t getCurrentOffsetOffset() const;
757
758public:
759  VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
760                             const CXXRecordDecl *LayoutClass,
761                             const FinalOverriders *Overriders,
762                             BaseSubobject Base, bool BaseIsVirtual,
763                             uint64_t OffsetInLayoutClass)
764    : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
765    Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
766
767    // Add vcall and vbase offsets.
768    AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
769  }
770
771  /// Methods for iterating over the components.
772  typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
773  const_iterator components_begin() const { return Components.rbegin(); }
774  const_iterator components_end() const { return Components.rend(); }
775
776  const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
777  const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
778    return VBaseOffsetOffsets;
779  }
780};
781
782void
783VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
784                                                    bool BaseIsVirtual,
785                                                    uint64_t RealBaseOffset) {
786  const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
787
788  // Itanium C++ ABI 2.5.2:
789  //   ..in classes sharing a virtual table with a primary base class, the vcall
790  //   and vbase offsets added by the derived class all come before the vcall
791  //   and vbase offsets required by the base class, so that the latter may be
792  //   laid out as required by the base class without regard to additions from
793  //   the derived class(es).
794
795  // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
796  // emit them for the primary base first).
797  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
798    bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
799
800    CharUnits PrimaryBaseOffset;
801
802    // Get the base offset of the primary base.
803    if (PrimaryBaseIsVirtual) {
804      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
805             "Primary vbase should have a zero offset!");
806
807      const ASTRecordLayout &MostDerivedClassLayout =
808        Context.getASTRecordLayout(MostDerivedClass);
809
810      PrimaryBaseOffset =
811        MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
812    } else {
813      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
814             "Primary base should have a zero offset!");
815
816      PrimaryBaseOffset = Base.getBaseOffset();
817    }
818
819    AddVCallAndVBaseOffsets(
820      BaseSubobject(PrimaryBase,PrimaryBaseOffset),
821      PrimaryBaseIsVirtual, RealBaseOffset);
822  }
823
824  AddVBaseOffsets(Base.getBase(), RealBaseOffset);
825
826  // We only want to add vcall offsets for virtual bases.
827  if (BaseIsVirtual)
828    AddVCallOffsets(Base, RealBaseOffset);
829}
830
831int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
832  // OffsetIndex is the index of this vcall or vbase offset, relative to the
833  // vtable address point. (We subtract 3 to account for the information just
834  // above the address point, the RTTI info, the offset to top, and the
835  // vcall offset itself).
836  int64_t OffsetIndex = -(int64_t)(3 + Components.size());
837
838  // FIXME: We shouldn't use / 8 here.
839  int64_t OffsetOffset = OffsetIndex *
840    (int64_t)Context.Target.getPointerWidth(0) / 8;
841
842  return OffsetOffset;
843}
844
845void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
846                                                 uint64_t VBaseOffset) {
847  const CXXRecordDecl *RD = Base.getBase();
848  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
849
850  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
851
852  // Handle the primary base first.
853  // We only want to add vcall offsets if the base is non-virtual; a virtual
854  // primary base will have its vcall and vbase offsets emitted already.
855  if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
856    // Get the base offset of the primary base.
857    assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
858           "Primary base should have a zero offset!");
859
860    AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
861                    VBaseOffset);
862  }
863
864  // Add the vcall offsets.
865  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
866       E = RD->method_end(); I != E; ++I) {
867    const CXXMethodDecl *MD = *I;
868
869    if (!MD->isVirtual())
870      continue;
871
872    int64_t OffsetOffset = getCurrentOffsetOffset();
873
874    // Don't add a vcall offset if we already have one for this member function
875    // signature.
876    if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
877      continue;
878
879    int64_t Offset = 0;
880
881    if (Overriders) {
882      // Get the final overrider.
883      FinalOverriders::OverriderInfo Overrider =
884        Overriders->getOverrider(MD, Base.getBaseOffset());
885
886      /// The vcall offset is the offset from the virtual base to the object
887      /// where the function was overridden.
888      // FIXME: We should not use / 8 here.
889      Offset = (int64_t)(Context.toBits(Overrider.Offset) - VBaseOffset) / 8;
890    }
891
892    Components.push_back(VTableComponent::MakeVCallOffset(Offset));
893  }
894
895  // And iterate over all non-virtual bases (ignoring the primary base).
896  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
897       E = RD->bases_end(); I != E; ++I) {
898
899    if (I->isVirtual())
900      continue;
901
902    const CXXRecordDecl *BaseDecl =
903      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
904    if (BaseDecl == PrimaryBase)
905      continue;
906
907    // Get the base offset of this base.
908    CharUnits BaseOffset = Base.getBaseOffset() +
909      Layout.getBaseClassOffset(BaseDecl);
910
911    AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
912                    VBaseOffset);
913  }
914}
915
916void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
917                                                 uint64_t OffsetInLayoutClass) {
918  const ASTRecordLayout &LayoutClassLayout =
919    Context.getASTRecordLayout(LayoutClass);
920
921  // Add vbase offsets.
922  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
923       E = RD->bases_end(); I != E; ++I) {
924    const CXXRecordDecl *BaseDecl =
925      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
926
927    // Check if this is a virtual base that we haven't visited before.
928    if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
929      // FIXME: We shouldn't use / 8 here.
930      int64_t Offset =
931        (int64_t)(LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl) -
932                  OffsetInLayoutClass) / 8;
933
934      // Add the vbase offset offset.
935      assert(!VBaseOffsetOffsets.count(BaseDecl) &&
936             "vbase offset offset already exists!");
937
938      int64_t VBaseOffsetOffset = getCurrentOffsetOffset();
939      VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset));
940
941      Components.push_back(VTableComponent::MakeVBaseOffset(Offset));
942    }
943
944    // Check the base class looking for more vbase offsets.
945    AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
946  }
947}
948
949/// VTableBuilder - Class for building vtable layout information.
950class VTableBuilder {
951public:
952  /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
953  /// primary bases.
954  typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
955    PrimaryBasesSetVectorTy;
956
957  typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
958    VBaseOffsetOffsetsMapTy;
959
960  typedef llvm::DenseMap<BaseSubobject, uint64_t>
961    AddressPointsMapTy;
962
963private:
964  /// VTables - Global vtable information.
965  CodeGenVTables &VTables;
966
967  /// MostDerivedClass - The most derived class for which we're building this
968  /// vtable.
969  const CXXRecordDecl *MostDerivedClass;
970
971  /// MostDerivedClassOffset - If we're building a construction vtable, this
972  /// holds the offset from the layout class to the most derived class.
973  const uint64_t MostDerivedClassOffset;
974
975  /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
976  /// base. (This only makes sense when building a construction vtable).
977  bool MostDerivedClassIsVirtual;
978
979  /// LayoutClass - The class we're using for layout information. Will be
980  /// different than the most derived class if we're building a construction
981  /// vtable.
982  const CXXRecordDecl *LayoutClass;
983
984  /// Context - The ASTContext which we will use for layout information.
985  ASTContext &Context;
986
987  /// FinalOverriders - The final overriders of the most derived class.
988  const FinalOverriders Overriders;
989
990  /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
991  /// bases in this vtable.
992  llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
993
994  /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
995  /// the most derived class.
996  VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
997
998  /// Components - The components of the vtable being built.
999  llvm::SmallVector<VTableComponent, 64> Components;
1000
1001  /// AddressPoints - Address points for the vtable being built.
1002  AddressPointsMapTy AddressPoints;
1003
1004  /// MethodInfo - Contains information about a method in a vtable.
1005  /// (Used for computing 'this' pointer adjustment thunks.
1006  struct MethodInfo {
1007    /// BaseOffset - The base offset of this method.
1008    const CharUnits BaseOffset;
1009
1010    /// BaseOffsetInLayoutClass - The base offset in the layout class of this
1011    /// method.
1012    const CharUnits BaseOffsetInLayoutClass;
1013
1014    /// VTableIndex - The index in the vtable that this method has.
1015    /// (For destructors, this is the index of the complete destructor).
1016    const uint64_t VTableIndex;
1017
1018    MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
1019               uint64_t VTableIndex)
1020      : BaseOffset(BaseOffset),
1021      BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
1022      VTableIndex(VTableIndex) { }
1023
1024    MethodInfo()
1025      : BaseOffset(CharUnits::Zero()),
1026      BaseOffsetInLayoutClass(CharUnits::Zero()),
1027      VTableIndex(0) { }
1028  };
1029
1030  typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
1031
1032  /// MethodInfoMap - The information for all methods in the vtable we're
1033  /// currently building.
1034  MethodInfoMapTy MethodInfoMap;
1035
1036  typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
1037
1038  /// VTableThunks - The thunks by vtable index in the vtable currently being
1039  /// built.
1040  VTableThunksMapTy VTableThunks;
1041
1042  typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
1043  typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
1044
1045  /// Thunks - A map that contains all the thunks needed for all methods in the
1046  /// most derived class for which the vtable is currently being built.
1047  ThunksMapTy Thunks;
1048
1049  /// AddThunk - Add a thunk for the given method.
1050  void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
1051
1052  /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
1053  /// part of the vtable we're currently building.
1054  void ComputeThisAdjustments();
1055
1056  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1057
1058  /// PrimaryVirtualBases - All known virtual bases who are a primary base of
1059  /// some other base.
1060  VisitedVirtualBasesSetTy PrimaryVirtualBases;
1061
1062  /// ComputeReturnAdjustment - Compute the return adjustment given a return
1063  /// adjustment base offset.
1064  ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
1065
1066  /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
1067  /// the 'this' pointer from the base subobject to the derived subobject.
1068  BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1069                                             BaseSubobject Derived) const;
1070
1071  /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
1072  /// given virtual member function, its offset in the layout class and its
1073  /// final overrider.
1074  ThisAdjustment
1075  ComputeThisAdjustment(const CXXMethodDecl *MD,
1076                        uint64_t BaseOffsetInLayoutClass,
1077                        FinalOverriders::OverriderInfo Overrider);
1078
1079  /// AddMethod - Add a single virtual member function to the vtable
1080  /// components vector.
1081  void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
1082
1083  /// IsOverriderUsed - Returns whether the overrider will ever be used in this
1084  /// part of the vtable.
1085  ///
1086  /// Itanium C++ ABI 2.5.2:
1087  ///
1088  ///   struct A { virtual void f(); };
1089  ///   struct B : virtual public A { int i; };
1090  ///   struct C : virtual public A { int j; };
1091  ///   struct D : public B, public C {};
1092  ///
1093  ///   When B and C are declared, A is a primary base in each case, so although
1094  ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
1095  ///   adjustment is required and no thunk is generated. However, inside D
1096  ///   objects, A is no longer a primary base of C, so if we allowed calls to
1097  ///   C::f() to use the copy of A's vtable in the C subobject, we would need
1098  ///   to adjust this from C* to B::A*, which would require a third-party
1099  ///   thunk. Since we require that a call to C::f() first convert to A*,
1100  ///   C-in-D's copy of A's vtable is never referenced, so this is not
1101  ///   necessary.
1102  bool IsOverriderUsed(const CXXMethodDecl *Overrider,
1103                       uint64_t BaseOffsetInLayoutClass,
1104                       const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1105                       uint64_t FirstBaseOffsetInLayoutClass) const;
1106
1107
1108  /// AddMethods - Add the methods of this base subobject and all its
1109  /// primary bases to the vtable components vector.
1110  void AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,
1111                  const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1112                  uint64_t FirstBaseOffsetInLayoutClass,
1113                  PrimaryBasesSetVectorTy &PrimaryBases);
1114
1115  // LayoutVTable - Layout the vtable for the given base class, including its
1116  // secondary vtables and any vtables for virtual bases.
1117  void LayoutVTable();
1118
1119  /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
1120  /// given base subobject, as well as all its secondary vtables.
1121  ///
1122  /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1123  /// or a direct or indirect base of a virtual base.
1124  ///
1125  /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
1126  /// in the layout class.
1127  void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1128                                        bool BaseIsMorallyVirtual,
1129                                        bool BaseIsVirtualInLayoutClass,
1130                                        uint64_t OffsetInLayoutClass);
1131
1132  /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
1133  /// subobject.
1134  ///
1135  /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1136  /// or a direct or indirect base of a virtual base.
1137  void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
1138                              uint64_t OffsetInLayoutClass);
1139
1140  /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
1141  /// class hierarchy.
1142  void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1143                                    uint64_t OffsetInLayoutClass,
1144                                    VisitedVirtualBasesSetTy &VBases);
1145
1146  /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
1147  /// given base (excluding any primary bases).
1148  void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1149                                    VisitedVirtualBasesSetTy &VBases);
1150
1151  /// isBuildingConstructionVTable - Return whether this vtable builder is
1152  /// building a construction vtable.
1153  bool isBuildingConstructorVTable() const {
1154    return MostDerivedClass != LayoutClass;
1155  }
1156
1157public:
1158  VTableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass,
1159                uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual,
1160                const CXXRecordDecl *LayoutClass)
1161    : VTables(VTables), MostDerivedClass(MostDerivedClass),
1162    MostDerivedClassOffset(MostDerivedClassOffset),
1163    MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1164    LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1165    Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1166
1167    LayoutVTable();
1168  }
1169
1170  ThunksMapTy::const_iterator thunks_begin() const {
1171    return Thunks.begin();
1172  }
1173
1174  ThunksMapTy::const_iterator thunks_end() const {
1175    return Thunks.end();
1176  }
1177
1178  const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1179    return VBaseOffsetOffsets;
1180  }
1181
1182  /// getNumVTableComponents - Return the number of components in the vtable
1183  /// currently built.
1184  uint64_t getNumVTableComponents() const {
1185    return Components.size();
1186  }
1187
1188  const uint64_t *vtable_components_data_begin() const {
1189    return reinterpret_cast<const uint64_t *>(Components.begin());
1190  }
1191
1192  const uint64_t *vtable_components_data_end() const {
1193    return reinterpret_cast<const uint64_t *>(Components.end());
1194  }
1195
1196  AddressPointsMapTy::const_iterator address_points_begin() const {
1197    return AddressPoints.begin();
1198  }
1199
1200  AddressPointsMapTy::const_iterator address_points_end() const {
1201    return AddressPoints.end();
1202  }
1203
1204  VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1205    return VTableThunks.begin();
1206  }
1207
1208  VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1209    return VTableThunks.end();
1210  }
1211
1212  /// dumpLayout - Dump the vtable layout.
1213  void dumpLayout(llvm::raw_ostream&);
1214};
1215
1216void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1217  assert(!isBuildingConstructorVTable() &&
1218         "Can't add thunks for construction vtable");
1219
1220  llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1221
1222  // Check if we have this thunk already.
1223  if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1224      ThunksVector.end())
1225    return;
1226
1227  ThunksVector.push_back(Thunk);
1228}
1229
1230typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1231
1232/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1233/// the overridden methods that the function decl overrides.
1234static void
1235ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1236                            OverriddenMethodsSetTy& OverriddenMethods) {
1237  assert(MD->isVirtual() && "Method is not virtual!");
1238
1239  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1240       E = MD->end_overridden_methods(); I != E; ++I) {
1241    const CXXMethodDecl *OverriddenMD = *I;
1242
1243    OverriddenMethods.insert(OverriddenMD);
1244
1245    ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1246  }
1247}
1248
1249void VTableBuilder::ComputeThisAdjustments() {
1250  // Now go through the method info map and see if any of the methods need
1251  // 'this' pointer adjustments.
1252  for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1253       E = MethodInfoMap.end(); I != E; ++I) {
1254    const CXXMethodDecl *MD = I->first;
1255    const MethodInfo &MethodInfo = I->second;
1256
1257    // Ignore adjustments for unused function pointers.
1258    uint64_t VTableIndex = MethodInfo.VTableIndex;
1259    if (Components[VTableIndex].getKind() ==
1260        VTableComponent::CK_UnusedFunctionPointer)
1261      continue;
1262
1263    // Get the final overrider for this method.
1264    FinalOverriders::OverriderInfo Overrider =
1265      Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1266
1267    // Check if we need an adjustment at all.
1268    if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1269      // When a return thunk is needed by a derived class that overrides a
1270      // virtual base, gcc uses a virtual 'this' adjustment as well.
1271      // While the thunk itself might be needed by vtables in subclasses or
1272      // in construction vtables, there doesn't seem to be a reason for using
1273      // the thunk in this vtable. Still, we do so to match gcc.
1274      if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1275        continue;
1276    }
1277
1278    ThisAdjustment ThisAdjustment =
1279      ComputeThisAdjustment(MD,
1280          Context.toBits(MethodInfo.BaseOffsetInLayoutClass), Overrider);
1281
1282    if (ThisAdjustment.isEmpty())
1283      continue;
1284
1285    // Add it.
1286    VTableThunks[VTableIndex].This = ThisAdjustment;
1287
1288    if (isa<CXXDestructorDecl>(MD)) {
1289      // Add an adjustment for the deleting destructor as well.
1290      VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1291    }
1292  }
1293
1294  /// Clear the method info map.
1295  MethodInfoMap.clear();
1296
1297  if (isBuildingConstructorVTable()) {
1298    // We don't need to store thunk information for construction vtables.
1299    return;
1300  }
1301
1302  for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1303       E = VTableThunks.end(); I != E; ++I) {
1304    const VTableComponent &Component = Components[I->first];
1305    const ThunkInfo &Thunk = I->second;
1306    const CXXMethodDecl *MD;
1307
1308    switch (Component.getKind()) {
1309    default:
1310      llvm_unreachable("Unexpected vtable component kind!");
1311    case VTableComponent::CK_FunctionPointer:
1312      MD = Component.getFunctionDecl();
1313      break;
1314    case VTableComponent::CK_CompleteDtorPointer:
1315      MD = Component.getDestructorDecl();
1316      break;
1317    case VTableComponent::CK_DeletingDtorPointer:
1318      // We've already added the thunk when we saw the complete dtor pointer.
1319      continue;
1320    }
1321
1322    if (MD->getParent() == MostDerivedClass)
1323      AddThunk(MD, Thunk);
1324  }
1325}
1326
1327ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1328  ReturnAdjustment Adjustment;
1329
1330  if (!Offset.isEmpty()) {
1331    if (Offset.VirtualBase) {
1332      // Get the virtual base offset offset.
1333      if (Offset.DerivedClass == MostDerivedClass) {
1334        // We can get the offset offset directly from our map.
1335        Adjustment.VBaseOffsetOffset =
1336          VBaseOffsetOffsets.lookup(Offset.VirtualBase);
1337      } else {
1338        Adjustment.VBaseOffsetOffset =
1339          VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1340                                             Offset.VirtualBase);
1341      }
1342    }
1343
1344    Adjustment.NonVirtual = Offset.NonVirtualOffset;
1345  }
1346
1347  return Adjustment;
1348}
1349
1350BaseOffset
1351VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1352                                               BaseSubobject Derived) const {
1353  const CXXRecordDecl *BaseRD = Base.getBase();
1354  const CXXRecordDecl *DerivedRD = Derived.getBase();
1355
1356  CXXBasePaths Paths(/*FindAmbiguities=*/true,
1357                     /*RecordPaths=*/true, /*DetectVirtual=*/true);
1358
1359  if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1360      isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1361    assert(false && "Class must be derived from the passed in base class!");
1362    return BaseOffset();
1363  }
1364
1365  // We have to go through all the paths, and see which one leads us to the
1366  // right base subobject.
1367  for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1368       I != E; ++I) {
1369    BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1370
1371    CharUnits OffsetToBaseSubobject =
1372      CharUnits::fromQuantity(Offset.NonVirtualOffset);
1373
1374    if (Offset.VirtualBase) {
1375      // If we have a virtual base class, the non-virtual offset is relative
1376      // to the virtual base class offset.
1377      const ASTRecordLayout &LayoutClassLayout =
1378        Context.getASTRecordLayout(LayoutClass);
1379
1380      /// Get the virtual base offset, relative to the most derived class
1381      /// layout.
1382      OffsetToBaseSubobject +=
1383        LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1384    } else {
1385      // Otherwise, the non-virtual offset is relative to the derived class
1386      // offset.
1387      OffsetToBaseSubobject += Derived.getBaseOffset();
1388    }
1389
1390    // Check if this path gives us the right base subobject.
1391    if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1392      // Since we're going from the base class _to_ the derived class, we'll
1393      // invert the non-virtual offset here.
1394      Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1395      return Offset;
1396    }
1397  }
1398
1399  return BaseOffset();
1400}
1401
1402ThisAdjustment
1403VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1404                                     uint64_t BaseOffsetInLayoutClass,
1405                                     FinalOverriders::OverriderInfo Overrider) {
1406  // Ignore adjustments for pure virtual member functions.
1407  if (Overrider.Method->isPure())
1408    return ThisAdjustment();
1409
1410  BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1411                                        Context.toCharUnitsFromBits(
1412                                          BaseOffsetInLayoutClass));
1413
1414  BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1415                                       Overrider.Offset);
1416
1417  // Compute the adjustment offset.
1418  BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1419                                                      OverriderBaseSubobject);
1420  if (Offset.isEmpty())
1421    return ThisAdjustment();
1422
1423  ThisAdjustment Adjustment;
1424
1425  if (Offset.VirtualBase) {
1426    // Get the vcall offset map for this virtual base.
1427    VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1428
1429    if (VCallOffsets.empty()) {
1430      // We don't have vcall offsets for this virtual base, go ahead and
1431      // build them.
1432      VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1433                                         /*FinalOverriders=*/0,
1434                                         BaseSubobject(Offset.VirtualBase,
1435                                                       CharUnits::Zero()),
1436                                         /*BaseIsVirtual=*/true,
1437                                         /*OffsetInLayoutClass=*/0);
1438
1439      VCallOffsets = Builder.getVCallOffsets();
1440    }
1441
1442    Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
1443  }
1444
1445  // Set the non-virtual part of the adjustment.
1446  Adjustment.NonVirtual = Offset.NonVirtualOffset;
1447
1448  return Adjustment;
1449}
1450
1451void
1452VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1453                         ReturnAdjustment ReturnAdjustment) {
1454  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1455    assert(ReturnAdjustment.isEmpty() &&
1456           "Destructor can't have return adjustment!");
1457
1458    // Add both the complete destructor and the deleting destructor.
1459    Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1460    Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1461  } else {
1462    // Add the return adjustment if necessary.
1463    if (!ReturnAdjustment.isEmpty())
1464      VTableThunks[Components.size()].Return = ReturnAdjustment;
1465
1466    // Add the function.
1467    Components.push_back(VTableComponent::MakeFunction(MD));
1468  }
1469}
1470
1471/// OverridesIndirectMethodInBase - Return whether the given member function
1472/// overrides any methods in the set of given bases.
1473/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1474/// For example, if we have:
1475///
1476/// struct A { virtual void f(); }
1477/// struct B : A { virtual void f(); }
1478/// struct C : B { virtual void f(); }
1479///
1480/// OverridesIndirectMethodInBase will return true if given C::f as the method
1481/// and { A } as the set of bases.
1482static bool
1483OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1484                               VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1485  if (Bases.count(MD->getParent()))
1486    return true;
1487
1488  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1489       E = MD->end_overridden_methods(); I != E; ++I) {
1490    const CXXMethodDecl *OverriddenMD = *I;
1491
1492    // Check "indirect overriders".
1493    if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1494      return true;
1495  }
1496
1497  return false;
1498}
1499
1500bool
1501VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1502                               uint64_t BaseOffsetInLayoutClass,
1503                               const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1504                               uint64_t FirstBaseOffsetInLayoutClass) const {
1505  // If the base and the first base in the primary base chain have the same
1506  // offsets, then this overrider will be used.
1507  if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1508   return true;
1509
1510  // We know now that Base (or a direct or indirect base of it) is a primary
1511  // base in part of the class hierarchy, but not a primary base in the most
1512  // derived class.
1513
1514  // If the overrider is the first base in the primary base chain, we know
1515  // that the overrider will be used.
1516  if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1517    return true;
1518
1519  VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1520
1521  const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1522  PrimaryBases.insert(RD);
1523
1524  // Now traverse the base chain, starting with the first base, until we find
1525  // the base that is no longer a primary base.
1526  while (true) {
1527    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1528    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1529
1530    if (!PrimaryBase)
1531      break;
1532
1533    if (Layout.isPrimaryBaseVirtual()) {
1534      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1535             "Primary base should always be at offset 0!");
1536
1537      const ASTRecordLayout &LayoutClassLayout =
1538        Context.getASTRecordLayout(LayoutClass);
1539
1540      // Now check if this is the primary base that is not a primary base in the
1541      // most derived class.
1542      if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
1543          FirstBaseOffsetInLayoutClass) {
1544        // We found it, stop walking the chain.
1545        break;
1546      }
1547    } else {
1548      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1549             "Primary base should always be at offset 0!");
1550    }
1551
1552    if (!PrimaryBases.insert(PrimaryBase))
1553      assert(false && "Found a duplicate primary base!");
1554
1555    RD = PrimaryBase;
1556  }
1557
1558  // If the final overrider is an override of one of the primary bases,
1559  // then we know that it will be used.
1560  return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1561}
1562
1563/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1564/// from the nearest base. Returns null if no method was found.
1565static const CXXMethodDecl *
1566FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1567                            VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1568  OverriddenMethodsSetTy OverriddenMethods;
1569  ComputeAllOverriddenMethods(MD, OverriddenMethods);
1570
1571  for (int I = Bases.size(), E = 0; I != E; --I) {
1572    const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1573
1574    // Now check the overriden methods.
1575    for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1576         E = OverriddenMethods.end(); I != E; ++I) {
1577      const CXXMethodDecl *OverriddenMD = *I;
1578
1579      // We found our overridden method.
1580      if (OverriddenMD->getParent() == PrimaryBase)
1581        return OverriddenMD;
1582    }
1583  }
1584
1585  return 0;
1586}
1587
1588void
1589VTableBuilder::AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,
1590                          const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1591                          uint64_t FirstBaseOffsetInLayoutClass,
1592                          PrimaryBasesSetVectorTy &PrimaryBases) {
1593  const CXXRecordDecl *RD = Base.getBase();
1594  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1595
1596  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1597    CharUnits PrimaryBaseOffset;
1598    uint64_t PrimaryBaseOffsetInLayoutClass;
1599    if (Layout.isPrimaryBaseVirtual()) {
1600      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1601             "Primary vbase should have a zero offset!");
1602
1603      const ASTRecordLayout &MostDerivedClassLayout =
1604        Context.getASTRecordLayout(MostDerivedClass);
1605
1606      PrimaryBaseOffset =
1607        MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1608
1609      const ASTRecordLayout &LayoutClassLayout =
1610        Context.getASTRecordLayout(LayoutClass);
1611
1612      PrimaryBaseOffsetInLayoutClass =
1613        LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
1614    } else {
1615      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1616             "Primary base should have a zero offset!");
1617
1618      PrimaryBaseOffset = Base.getBaseOffset();
1619      PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1620    }
1621
1622    AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1623               PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1624               FirstBaseOffsetInLayoutClass, PrimaryBases);
1625
1626    if (!PrimaryBases.insert(PrimaryBase))
1627      assert(false && "Found a duplicate primary base!");
1628  }
1629
1630  // Now go through all virtual member functions and add them.
1631  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1632       E = RD->method_end(); I != E; ++I) {
1633    const CXXMethodDecl *MD = *I;
1634
1635    if (!MD->isVirtual())
1636      continue;
1637
1638    // Get the final overrider.
1639    FinalOverriders::OverriderInfo Overrider =
1640      Overriders.getOverrider(MD, Base.getBaseOffset());
1641
1642    // Check if this virtual member function overrides a method in a primary
1643    // base. If this is the case, and the return type doesn't require adjustment
1644    // then we can just use the member function from the primary base.
1645    if (const CXXMethodDecl *OverriddenMD =
1646          FindNearestOverriddenMethod(MD, PrimaryBases)) {
1647      if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1648                                            OverriddenMD).isEmpty()) {
1649        // Replace the method info of the overridden method with our own
1650        // method.
1651        assert(MethodInfoMap.count(OverriddenMD) &&
1652               "Did not find the overridden method!");
1653        MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1654
1655        MethodInfo MethodInfo(Base.getBaseOffset(),
1656                          Context.toCharUnitsFromBits(BaseOffsetInLayoutClass),
1657                          OverriddenMethodInfo.VTableIndex);
1658
1659        assert(!MethodInfoMap.count(MD) &&
1660               "Should not have method info for this method yet!");
1661
1662        MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1663        MethodInfoMap.erase(OverriddenMD);
1664
1665        // If the overridden method exists in a virtual base class or a direct
1666        // or indirect base class of a virtual base class, we need to emit a
1667        // thunk if we ever have a class hierarchy where the base class is not
1668        // a primary base in the complete object.
1669        if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1670          // Compute the this adjustment.
1671          ThisAdjustment ThisAdjustment =
1672            ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1673                                  Overrider);
1674
1675          if (ThisAdjustment.VCallOffsetOffset &&
1676              Overrider.Method->getParent() == MostDerivedClass) {
1677
1678            // There's no return adjustment from OverriddenMD and MD,
1679            // but that doesn't mean there isn't one between MD and
1680            // the final overrider.
1681            BaseOffset ReturnAdjustmentOffset =
1682              ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1683            ReturnAdjustment ReturnAdjustment =
1684              ComputeReturnAdjustment(ReturnAdjustmentOffset);
1685
1686            // This is a virtual thunk for the most derived class, add it.
1687            AddThunk(Overrider.Method,
1688                     ThunkInfo(ThisAdjustment, ReturnAdjustment));
1689          }
1690        }
1691
1692        continue;
1693      }
1694    }
1695
1696    // Insert the method info for this method.
1697    MethodInfo MethodInfo(Base.getBaseOffset(),
1698                          Context.toCharUnitsFromBits(BaseOffsetInLayoutClass),
1699                          Components.size());
1700
1701    assert(!MethodInfoMap.count(MD) &&
1702           "Should not have method info for this method yet!");
1703    MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1704
1705    // Check if this overrider is going to be used.
1706    const CXXMethodDecl *OverriderMD = Overrider.Method;
1707    if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1708                         FirstBaseInPrimaryBaseChain,
1709                         FirstBaseOffsetInLayoutClass)) {
1710      Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1711      continue;
1712    }
1713
1714    // Check if this overrider needs a return adjustment.
1715    // We don't want to do this for pure virtual member functions.
1716    BaseOffset ReturnAdjustmentOffset;
1717    if (!OverriderMD->isPure()) {
1718      ReturnAdjustmentOffset =
1719        ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1720    }
1721
1722    ReturnAdjustment ReturnAdjustment =
1723      ComputeReturnAdjustment(ReturnAdjustmentOffset);
1724
1725    AddMethod(Overrider.Method, ReturnAdjustment);
1726  }
1727}
1728
1729void VTableBuilder::LayoutVTable() {
1730  LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1731                                                 CharUnits::Zero()),
1732                                   /*BaseIsMorallyVirtual=*/false,
1733                                   MostDerivedClassIsVirtual,
1734                                   MostDerivedClassOffset);
1735
1736  VisitedVirtualBasesSetTy VBases;
1737
1738  // Determine the primary virtual bases.
1739  DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1740                               VBases);
1741  VBases.clear();
1742
1743  LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1744}
1745
1746void
1747VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1748                                                bool BaseIsMorallyVirtual,
1749                                                bool BaseIsVirtualInLayoutClass,
1750                                                uint64_t OffsetInLayoutClass) {
1751  assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1752
1753  // Add vcall and vbase offsets for this vtable.
1754  VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1755                                     Base, BaseIsVirtualInLayoutClass,
1756                                     OffsetInLayoutClass);
1757  Components.append(Builder.components_begin(), Builder.components_end());
1758
1759  // Check if we need to add these vcall offsets.
1760  if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1761    VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1762
1763    if (VCallOffsets.empty())
1764      VCallOffsets = Builder.getVCallOffsets();
1765  }
1766
1767  // If we're laying out the most derived class we want to keep track of the
1768  // virtual base class offset offsets.
1769  if (Base.getBase() == MostDerivedClass)
1770    VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1771
1772  // Add the offset to top.
1773  // FIXME: We should not use / 8 here.
1774  int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
1775                                   MostDerivedClassOffset) / 8;
1776  Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1777
1778  // Next, add the RTTI.
1779  Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1780
1781  uint64_t AddressPoint = Components.size();
1782
1783  // Now go through all virtual member functions and add them.
1784  PrimaryBasesSetVectorTy PrimaryBases;
1785  AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass,
1786             PrimaryBases);
1787
1788  // Compute 'this' pointer adjustments.
1789  ComputeThisAdjustments();
1790
1791  // Add all address points.
1792  const CXXRecordDecl *RD = Base.getBase();
1793  while (true) {
1794    AddressPoints.insert(std::make_pair(
1795      BaseSubobject(RD, Context.toCharUnitsFromBits(OffsetInLayoutClass)),
1796      AddressPoint));
1797
1798    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1799    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1800
1801    if (!PrimaryBase)
1802      break;
1803
1804    if (Layout.isPrimaryBaseVirtual()) {
1805      // Check if this virtual primary base is a primary base in the layout
1806      // class. If it's not, we don't want to add it.
1807      const ASTRecordLayout &LayoutClassLayout =
1808        Context.getASTRecordLayout(LayoutClass);
1809
1810      if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
1811          OffsetInLayoutClass) {
1812        // We don't want to add this class (or any of its primary bases).
1813        break;
1814      }
1815    }
1816
1817    RD = PrimaryBase;
1818  }
1819
1820  // Layout secondary vtables.
1821  LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1822}
1823
1824void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1825                                           bool BaseIsMorallyVirtual,
1826                                           uint64_t OffsetInLayoutClass) {
1827  // Itanium C++ ABI 2.5.2:
1828  //   Following the primary virtual table of a derived class are secondary
1829  //   virtual tables for each of its proper base classes, except any primary
1830  //   base(s) with which it shares its primary virtual table.
1831
1832  const CXXRecordDecl *RD = Base.getBase();
1833  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1834  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1835
1836  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1837       E = RD->bases_end(); I != E; ++I) {
1838    // Ignore virtual bases, we'll emit them later.
1839    if (I->isVirtual())
1840      continue;
1841
1842    const CXXRecordDecl *BaseDecl =
1843      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1844
1845    // Ignore bases that don't have a vtable.
1846    if (!BaseDecl->isDynamicClass())
1847      continue;
1848
1849    if (isBuildingConstructorVTable()) {
1850      // Itanium C++ ABI 2.6.4:
1851      //   Some of the base class subobjects may not need construction virtual
1852      //   tables, which will therefore not be present in the construction
1853      //   virtual table group, even though the subobject virtual tables are
1854      //   present in the main virtual table group for the complete object.
1855      if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1856        continue;
1857    }
1858
1859    // Get the base offset of this base.
1860    CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1861    CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1862
1863    CharUnits BaseOffsetInLayoutClass =
1864      Context.toCharUnitsFromBits(OffsetInLayoutClass) + RelativeBaseOffset;
1865
1866    // Don't emit a secondary vtable for a primary base. We might however want
1867    // to emit secondary vtables for other bases of this base.
1868    if (BaseDecl == PrimaryBase) {
1869      LayoutSecondaryVTables(
1870        BaseSubobject(BaseDecl, BaseOffset),
1871        BaseIsMorallyVirtual, Context.toBits(BaseOffsetInLayoutClass));
1872      continue;
1873    }
1874
1875    // Layout the primary vtable (and any secondary vtables) for this base.
1876    LayoutPrimaryAndSecondaryVTables(
1877      BaseSubobject(BaseDecl, BaseOffset),
1878      BaseIsMorallyVirtual,
1879      /*BaseIsVirtualInLayoutClass=*/false,
1880      Context.toBits(BaseOffsetInLayoutClass));
1881  }
1882}
1883
1884void
1885VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1886                                            uint64_t OffsetInLayoutClass,
1887                                            VisitedVirtualBasesSetTy &VBases) {
1888  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1889
1890  // Check if this base has a primary base.
1891  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1892
1893    // Check if it's virtual.
1894    if (Layout.isPrimaryBaseVirtual()) {
1895      bool IsPrimaryVirtualBase = true;
1896
1897      if (isBuildingConstructorVTable()) {
1898        // Check if the base is actually a primary base in the class we use for
1899        // layout.
1900        const ASTRecordLayout &LayoutClassLayout =
1901          Context.getASTRecordLayout(LayoutClass);
1902
1903        uint64_t PrimaryBaseOffsetInLayoutClass =
1904          LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
1905
1906        // We know that the base is not a primary base in the layout class if
1907        // the base offsets are different.
1908        if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1909          IsPrimaryVirtualBase = false;
1910      }
1911
1912      if (IsPrimaryVirtualBase)
1913        PrimaryVirtualBases.insert(PrimaryBase);
1914    }
1915  }
1916
1917  // Traverse bases, looking for more primary virtual bases.
1918  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1919       E = RD->bases_end(); I != E; ++I) {
1920    const CXXRecordDecl *BaseDecl =
1921      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1922
1923    uint64_t BaseOffsetInLayoutClass;
1924
1925    if (I->isVirtual()) {
1926      if (!VBases.insert(BaseDecl))
1927        continue;
1928
1929      const ASTRecordLayout &LayoutClassLayout =
1930        Context.getASTRecordLayout(LayoutClass);
1931
1932      BaseOffsetInLayoutClass =
1933        LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
1934    } else {
1935      BaseOffsetInLayoutClass =
1936        OffsetInLayoutClass + Layout.getBaseClassOffsetInBits(BaseDecl);
1937    }
1938
1939    DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1940  }
1941}
1942
1943void
1944VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1945                                            VisitedVirtualBasesSetTy &VBases) {
1946  // Itanium C++ ABI 2.5.2:
1947  //   Then come the virtual base virtual tables, also in inheritance graph
1948  //   order, and again excluding primary bases (which share virtual tables with
1949  //   the classes for which they are primary).
1950  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1951       E = RD->bases_end(); I != E; ++I) {
1952    const CXXRecordDecl *BaseDecl =
1953      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1954
1955    // Check if this base needs a vtable. (If it's virtual, not a primary base
1956    // of some other class, and we haven't visited it before).
1957    if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1958        !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1959      const ASTRecordLayout &MostDerivedClassLayout =
1960        Context.getASTRecordLayout(MostDerivedClass);
1961      uint64_t BaseOffset =
1962        MostDerivedClassLayout.getVBaseClassOffsetInBits(BaseDecl);
1963
1964      const ASTRecordLayout &LayoutClassLayout =
1965        Context.getASTRecordLayout(LayoutClass);
1966      uint64_t BaseOffsetInLayoutClass =
1967        LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
1968
1969      LayoutPrimaryAndSecondaryVTables(
1970        BaseSubobject(BaseDecl, Context.toCharUnitsFromBits(BaseOffset)),
1971        /*BaseIsMorallyVirtual=*/true,
1972        /*BaseIsVirtualInLayoutClass=*/true,
1973        BaseOffsetInLayoutClass);
1974    }
1975
1976    // We only need to check the base for virtual base vtables if it actually
1977    // has virtual bases.
1978    if (BaseDecl->getNumVBases())
1979      LayoutVTablesForVirtualBases(BaseDecl, VBases);
1980  }
1981}
1982
1983/// dumpLayout - Dump the vtable layout.
1984void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) {
1985
1986  if (isBuildingConstructorVTable()) {
1987    Out << "Construction vtable for ('";
1988    Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1989    // FIXME: Don't use / 8 .
1990    Out << MostDerivedClassOffset / 8 << ") in '";
1991    Out << LayoutClass->getQualifiedNameAsString();
1992  } else {
1993    Out << "Vtable for '";
1994    Out << MostDerivedClass->getQualifiedNameAsString();
1995  }
1996  Out << "' (" << Components.size() << " entries).\n";
1997
1998  // Iterate through the address points and insert them into a new map where
1999  // they are keyed by the index and not the base object.
2000  // Since an address point can be shared by multiple subobjects, we use an
2001  // STL multimap.
2002  std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
2003  for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
2004       E = AddressPoints.end(); I != E; ++I) {
2005    const BaseSubobject& Base = I->first;
2006    uint64_t Index = I->second;
2007
2008    AddressPointsByIndex.insert(std::make_pair(Index, Base));
2009  }
2010
2011  for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2012    uint64_t Index = I;
2013
2014    Out << llvm::format("%4d | ", I);
2015
2016    const VTableComponent &Component = Components[I];
2017
2018    // Dump the component.
2019    switch (Component.getKind()) {
2020
2021    case VTableComponent::CK_VCallOffset:
2022      Out << "vcall_offset (" << Component.getVCallOffset() << ")";
2023      break;
2024
2025    case VTableComponent::CK_VBaseOffset:
2026      Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
2027      break;
2028
2029    case VTableComponent::CK_OffsetToTop:
2030      Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
2031      break;
2032
2033    case VTableComponent::CK_RTTI:
2034      Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2035      break;
2036
2037    case VTableComponent::CK_FunctionPointer: {
2038      const CXXMethodDecl *MD = Component.getFunctionDecl();
2039
2040      std::string Str =
2041        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2042                                    MD);
2043      Out << Str;
2044      if (MD->isPure())
2045        Out << " [pure]";
2046
2047      ThunkInfo Thunk = VTableThunks.lookup(I);
2048      if (!Thunk.isEmpty()) {
2049        // If this function pointer has a return adjustment, dump it.
2050        if (!Thunk.Return.isEmpty()) {
2051          Out << "\n       [return adjustment: ";
2052          Out << Thunk.Return.NonVirtual << " non-virtual";
2053
2054          if (Thunk.Return.VBaseOffsetOffset) {
2055            Out << ", " << Thunk.Return.VBaseOffsetOffset;
2056            Out << " vbase offset offset";
2057          }
2058
2059          Out << ']';
2060        }
2061
2062        // If this function pointer has a 'this' pointer adjustment, dump it.
2063        if (!Thunk.This.isEmpty()) {
2064          Out << "\n       [this adjustment: ";
2065          Out << Thunk.This.NonVirtual << " non-virtual";
2066
2067          if (Thunk.This.VCallOffsetOffset) {
2068            Out << ", " << Thunk.This.VCallOffsetOffset;
2069            Out << " vcall offset offset";
2070          }
2071
2072          Out << ']';
2073        }
2074      }
2075
2076      break;
2077    }
2078
2079    case VTableComponent::CK_CompleteDtorPointer:
2080    case VTableComponent::CK_DeletingDtorPointer: {
2081      bool IsComplete =
2082        Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2083
2084      const CXXDestructorDecl *DD = Component.getDestructorDecl();
2085
2086      Out << DD->getQualifiedNameAsString();
2087      if (IsComplete)
2088        Out << "() [complete]";
2089      else
2090        Out << "() [deleting]";
2091
2092      if (DD->isPure())
2093        Out << " [pure]";
2094
2095      ThunkInfo Thunk = VTableThunks.lookup(I);
2096      if (!Thunk.isEmpty()) {
2097        // If this destructor has a 'this' pointer adjustment, dump it.
2098        if (!Thunk.This.isEmpty()) {
2099          Out << "\n       [this adjustment: ";
2100          Out << Thunk.This.NonVirtual << " non-virtual";
2101
2102          if (Thunk.This.VCallOffsetOffset) {
2103            Out << ", " << Thunk.This.VCallOffsetOffset;
2104            Out << " vcall offset offset";
2105          }
2106
2107          Out << ']';
2108        }
2109      }
2110
2111      break;
2112    }
2113
2114    case VTableComponent::CK_UnusedFunctionPointer: {
2115      const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2116
2117      std::string Str =
2118        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2119                                    MD);
2120      Out << "[unused] " << Str;
2121      if (MD->isPure())
2122        Out << " [pure]";
2123    }
2124
2125    }
2126
2127    Out << '\n';
2128
2129    // Dump the next address point.
2130    uint64_t NextIndex = Index + 1;
2131    if (AddressPointsByIndex.count(NextIndex)) {
2132      if (AddressPointsByIndex.count(NextIndex) == 1) {
2133        const BaseSubobject &Base =
2134          AddressPointsByIndex.find(NextIndex)->second;
2135
2136        // FIXME: Instead of dividing by 8, we should be using CharUnits.
2137        Out << "       -- (" << Base.getBase()->getQualifiedNameAsString();
2138        Out << ", " << Base.getBaseOffset().getQuantity();
2139        Out << ") vtable address --\n";
2140      } else {
2141        CharUnits BaseOffset =
2142          AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2143
2144        // We store the class names in a set to get a stable order.
2145        std::set<std::string> ClassNames;
2146        for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2147             AddressPointsByIndex.lower_bound(NextIndex), E =
2148             AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2149          assert(I->second.getBaseOffset() == BaseOffset &&
2150                 "Invalid base offset!");
2151          const CXXRecordDecl *RD = I->second.getBase();
2152          ClassNames.insert(RD->getQualifiedNameAsString());
2153        }
2154
2155        for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2156             E = ClassNames.end(); I != E; ++I) {
2157          Out << "       -- (" << *I;
2158          Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2159        }
2160      }
2161    }
2162  }
2163
2164  Out << '\n';
2165
2166  if (isBuildingConstructorVTable())
2167    return;
2168
2169  if (MostDerivedClass->getNumVBases()) {
2170    // We store the virtual base class names and their offsets in a map to get
2171    // a stable order.
2172
2173    std::map<std::string, int64_t> ClassNamesAndOffsets;
2174    for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2175         E = VBaseOffsetOffsets.end(); I != E; ++I) {
2176      std::string ClassName = I->first->getQualifiedNameAsString();
2177      int64_t OffsetOffset = I->second;
2178      ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2179    }
2180
2181    Out << "Virtual base offset offsets for '";
2182    Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2183    Out << ClassNamesAndOffsets.size();
2184    Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2185
2186    for (std::map<std::string, int64_t>::const_iterator I =
2187         ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2188         I != E; ++I)
2189      Out << "   " << I->first << " | " << I->second << '\n';
2190
2191    Out << "\n";
2192  }
2193
2194  if (!Thunks.empty()) {
2195    // We store the method names in a map to get a stable order.
2196    std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2197
2198    for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2199         I != E; ++I) {
2200      const CXXMethodDecl *MD = I->first;
2201      std::string MethodName =
2202        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2203                                    MD);
2204
2205      MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2206    }
2207
2208    for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2209         MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2210         I != E; ++I) {
2211      const std::string &MethodName = I->first;
2212      const CXXMethodDecl *MD = I->second;
2213
2214      ThunkInfoVectorTy ThunksVector = Thunks[MD];
2215      std::sort(ThunksVector.begin(), ThunksVector.end());
2216
2217      Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2218      Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2219
2220      for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2221        const ThunkInfo &Thunk = ThunksVector[I];
2222
2223        Out << llvm::format("%4d | ", I);
2224
2225        // If this function pointer has a return pointer adjustment, dump it.
2226        if (!Thunk.Return.isEmpty()) {
2227          Out << "return adjustment: " << Thunk.This.NonVirtual;
2228          Out << " non-virtual";
2229          if (Thunk.Return.VBaseOffsetOffset) {
2230            Out << ", " << Thunk.Return.VBaseOffsetOffset;
2231            Out << " vbase offset offset";
2232          }
2233
2234          if (!Thunk.This.isEmpty())
2235            Out << "\n       ";
2236        }
2237
2238        // If this function pointer has a 'this' pointer adjustment, dump it.
2239        if (!Thunk.This.isEmpty()) {
2240          Out << "this adjustment: ";
2241          Out << Thunk.This.NonVirtual << " non-virtual";
2242
2243          if (Thunk.This.VCallOffsetOffset) {
2244            Out << ", " << Thunk.This.VCallOffsetOffset;
2245            Out << " vcall offset offset";
2246          }
2247        }
2248
2249        Out << '\n';
2250      }
2251
2252      Out << '\n';
2253
2254    }
2255  }
2256}
2257
2258}
2259
2260static void
2261CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2262                    VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2263  while (RD) {
2264    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2265    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2266    if (PrimaryBase)
2267      PrimaryBases.insert(PrimaryBase);
2268
2269    RD = PrimaryBase;
2270  }
2271}
2272
2273void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2274
2275  // Itanium C++ ABI 2.5.2:
2276  //   The order of the virtual function pointers in a virtual table is the
2277  //   order of declaration of the corresponding member functions in the class.
2278  //
2279  //   There is an entry for any virtual function declared in a class,
2280  //   whether it is a new function or overrides a base class function,
2281  //   unless it overrides a function from the primary base, and conversion
2282  //   between their return types does not require an adjustment.
2283
2284  int64_t CurrentIndex = 0;
2285
2286  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2287  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2288
2289  if (PrimaryBase) {
2290    assert(PrimaryBase->isDefinition() &&
2291           "Should have the definition decl of the primary base!");
2292
2293    // Since the record decl shares its vtable pointer with the primary base
2294    // we need to start counting at the end of the primary base's vtable.
2295    CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2296  }
2297
2298  // Collect all the primary bases, so we can check whether methods override
2299  // a method from the base.
2300  VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2301  CollectPrimaryBases(RD, CGM.getContext(), PrimaryBases);
2302
2303  const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2304
2305  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2306       e = RD->method_end(); i != e; ++i) {
2307    const CXXMethodDecl *MD = *i;
2308
2309    // We only want virtual methods.
2310    if (!MD->isVirtual())
2311      continue;
2312
2313    // Check if this method overrides a method in the primary base.
2314    if (const CXXMethodDecl *OverriddenMD =
2315          FindNearestOverriddenMethod(MD, PrimaryBases)) {
2316      // Check if converting from the return type of the method to the
2317      // return type of the overridden method requires conversion.
2318      if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
2319                                            OverriddenMD).isEmpty()) {
2320        // This index is shared between the index in the vtable of the primary
2321        // base class.
2322        if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2323          const CXXDestructorDecl *OverriddenDD =
2324            cast<CXXDestructorDecl>(OverriddenMD);
2325
2326          // Add both the complete and deleting entries.
2327          MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2328            getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2329          MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2330            getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2331        } else {
2332          MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2333        }
2334
2335        // We don't need to add an entry for this method.
2336        continue;
2337      }
2338    }
2339
2340    if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2341      if (MD->isImplicit()) {
2342        assert(!ImplicitVirtualDtor &&
2343               "Did already see an implicit virtual dtor!");
2344        ImplicitVirtualDtor = DD;
2345        continue;
2346      }
2347
2348      // Add the complete dtor.
2349      MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2350
2351      // Add the deleting dtor.
2352      MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2353    } else {
2354      // Add the entry.
2355      MethodVTableIndices[MD] = CurrentIndex++;
2356    }
2357  }
2358
2359  if (ImplicitVirtualDtor) {
2360    // Itanium C++ ABI 2.5.2:
2361    //   If a class has an implicitly-defined virtual destructor,
2362    //   its entries come after the declared virtual function pointers.
2363
2364    // Add the complete dtor.
2365    MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2366      CurrentIndex++;
2367
2368    // Add the deleting dtor.
2369    MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2370      CurrentIndex++;
2371  }
2372
2373  NumVirtualFunctionPointers[RD] = CurrentIndex;
2374}
2375
2376bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
2377  assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
2378
2379  TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2380  if (TSK == TSK_ExplicitInstantiationDeclaration)
2381    return false;
2382
2383  const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
2384  if (!KeyFunction)
2385    return true;
2386
2387  // Itanium C++ ABI, 5.2.6 Instantiated Templates:
2388  //    An instantiation of a class template requires:
2389  //        - In the object where instantiated, the virtual table...
2390  if (TSK == TSK_ImplicitInstantiation ||
2391      TSK == TSK_ExplicitInstantiationDefinition)
2392    return true;
2393
2394  // If we're building with optimization, we always emit VTables since that
2395  // allows for virtual function calls to be devirtualized.
2396  // (We don't want to do this in -fapple-kext mode however).
2397  if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext)
2398    return true;
2399
2400  return KeyFunction->hasBody();
2401}
2402
2403uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2404  llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2405    NumVirtualFunctionPointers.find(RD);
2406  if (I != NumVirtualFunctionPointers.end())
2407    return I->second;
2408
2409  ComputeMethodVTableIndices(RD);
2410
2411  I = NumVirtualFunctionPointers.find(RD);
2412  assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2413  return I->second;
2414}
2415
2416uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) {
2417  MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2418  if (I != MethodVTableIndices.end())
2419    return I->second;
2420
2421  const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2422
2423  ComputeMethodVTableIndices(RD);
2424
2425  I = MethodVTableIndices.find(GD);
2426  assert(I != MethodVTableIndices.end() && "Did not find index!");
2427  return I->second;
2428}
2429
2430int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2431                                                   const CXXRecordDecl *VBase) {
2432  ClassPairTy ClassPair(RD, VBase);
2433
2434  VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2435    VirtualBaseClassOffsetOffsets.find(ClassPair);
2436  if (I != VirtualBaseClassOffsetOffsets.end())
2437    return I->second;
2438
2439  VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2440                                     BaseSubobject(RD, CharUnits::Zero()),
2441                                     /*BaseIsVirtual=*/false,
2442                                     /*OffsetInLayoutClass=*/0);
2443
2444  for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2445       Builder.getVBaseOffsetOffsets().begin(),
2446       E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2447    // Insert all types.
2448    ClassPairTy ClassPair(RD, I->first);
2449
2450    VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2451  }
2452
2453  I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2454  assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2455
2456  return I->second;
2457}
2458
2459uint64_t
2460CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
2461  assert(AddressPoints.count(std::make_pair(RD, Base)) &&
2462         "Did not find address point!");
2463
2464  uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
2465  assert(AddressPoint && "Address point must not be zero!");
2466
2467  return AddressPoint;
2468}
2469
2470llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
2471                                              const ThunkInfo &Thunk) {
2472  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2473
2474  // Compute the mangled name.
2475  llvm::SmallString<256> Name;
2476  llvm::raw_svector_ostream Out(Name);
2477  if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
2478    getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
2479                                                      Thunk.This, Out);
2480  else
2481    getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
2482  Out.flush();
2483
2484  const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
2485  return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
2486}
2487
2488static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
2489                                          llvm::Value *Ptr,
2490                                          int64_t NonVirtualAdjustment,
2491                                          int64_t VirtualAdjustment) {
2492  if (!NonVirtualAdjustment && !VirtualAdjustment)
2493    return Ptr;
2494
2495  const llvm::Type *Int8PtrTy =
2496    llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2497
2498  llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
2499
2500  if (NonVirtualAdjustment) {
2501    // Do the non-virtual adjustment.
2502    V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
2503  }
2504
2505  if (VirtualAdjustment) {
2506    const llvm::Type *PtrDiffTy =
2507      CGF.ConvertType(CGF.getContext().getPointerDiffType());
2508
2509    // Do the virtual adjustment.
2510    llvm::Value *VTablePtrPtr =
2511      CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
2512
2513    llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
2514
2515    llvm::Value *OffsetPtr =
2516      CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
2517
2518    OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
2519
2520    // Load the adjustment offset from the vtable.
2521    llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
2522
2523    // Adjust our pointer.
2524    V = CGF.Builder.CreateInBoundsGEP(V, Offset);
2525  }
2526
2527  // Cast back to the original type.
2528  return CGF.Builder.CreateBitCast(V, Ptr->getType());
2529}
2530
2531static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
2532                               const ThunkInfo &Thunk, llvm::Function *Fn) {
2533  CGM.setGlobalVisibility(Fn, MD);
2534
2535  if (!CGM.getCodeGenOpts().HiddenWeakVTables)
2536    return;
2537
2538  // If the thunk has weak/linkonce linkage, but the function must be
2539  // emitted in every translation unit that references it, then we can
2540  // emit its thunks with hidden visibility, since its thunks must be
2541  // emitted when the function is.
2542
2543  // This follows CodeGenModule::setTypeVisibility; see the comments
2544  // there for explanation.
2545
2546  if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
2547       Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
2548      Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
2549    return;
2550
2551  if (MD->getExplicitVisibility())
2552    return;
2553
2554  switch (MD->getTemplateSpecializationKind()) {
2555  case TSK_ExplicitInstantiationDefinition:
2556  case TSK_ExplicitInstantiationDeclaration:
2557    return;
2558
2559  case TSK_Undeclared:
2560    break;
2561
2562  case TSK_ExplicitSpecialization:
2563  case TSK_ImplicitInstantiation:
2564    if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
2565      return;
2566    break;
2567  }
2568
2569  // If there's an explicit definition, and that definition is
2570  // out-of-line, then we can't assume that all users will have a
2571  // definition to emit.
2572  const FunctionDecl *Def = 0;
2573  if (MD->hasBody(Def) && Def->isOutOfLine())
2574    return;
2575
2576  Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2577}
2578
2579#ifndef NDEBUG
2580static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
2581                    const ABIArgInfo &infoR, CanQualType typeR) {
2582  return (infoL.getKind() == infoR.getKind() &&
2583          (typeL == typeR ||
2584           (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
2585           (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
2586}
2587#endif
2588
2589void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
2590                                    const CGFunctionInfo &FnInfo,
2591                                    GlobalDecl GD, const ThunkInfo &Thunk) {
2592  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2593  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
2594  QualType ResultType = FPT->getResultType();
2595  QualType ThisType = MD->getThisType(getContext());
2596
2597  FunctionArgList FunctionArgs;
2598
2599  // FIXME: It would be nice if more of this code could be shared with
2600  // CodeGenFunction::GenerateCode.
2601
2602  // Create the implicit 'this' parameter declaration.
2603  CurGD = GD;
2604  CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
2605
2606  // Add the rest of the parameters.
2607  for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2608       E = MD->param_end(); I != E; ++I) {
2609    ParmVarDecl *Param = *I;
2610
2611    FunctionArgs.push_back(Param);
2612  }
2613
2614  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
2615                SourceLocation());
2616
2617  CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2618
2619  // Adjust the 'this' pointer if necessary.
2620  llvm::Value *AdjustedThisPtr =
2621    PerformTypeAdjustment(*this, LoadCXXThis(),
2622                          Thunk.This.NonVirtual,
2623                          Thunk.This.VCallOffsetOffset);
2624
2625  CallArgList CallArgs;
2626
2627  // Add our adjusted 'this' pointer.
2628  CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
2629
2630  // Add the rest of the parameters.
2631  for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2632       E = MD->param_end(); I != E; ++I) {
2633    ParmVarDecl *param = *I;
2634    EmitDelegateCallArg(CallArgs, param);
2635  }
2636
2637  // Get our callee.
2638  const llvm::Type *Ty =
2639    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
2640                                   FPT->isVariadic());
2641  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
2642
2643#ifndef NDEBUG
2644  const CGFunctionInfo &CallFnInfo =
2645    CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo());
2646  assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
2647         CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
2648         CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
2649  assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
2650                 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
2651  assert(CallFnInfo.arg_size() == FnInfo.arg_size());
2652  for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
2653    assert(similar(CallFnInfo.arg_begin()[i].info,
2654                   CallFnInfo.arg_begin()[i].type,
2655                   FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
2656#endif
2657
2658  // Determine whether we have a return value slot to use.
2659  ReturnValueSlot Slot;
2660  if (!ResultType->isVoidType() &&
2661      FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2662      hasAggregateLLVMType(CurFnInfo->getReturnType()))
2663    Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
2664
2665  // Now emit our call.
2666  RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
2667
2668  if (!Thunk.Return.isEmpty()) {
2669    // Emit the return adjustment.
2670    bool NullCheckValue = !ResultType->isReferenceType();
2671
2672    llvm::BasicBlock *AdjustNull = 0;
2673    llvm::BasicBlock *AdjustNotNull = 0;
2674    llvm::BasicBlock *AdjustEnd = 0;
2675
2676    llvm::Value *ReturnValue = RV.getScalarVal();
2677
2678    if (NullCheckValue) {
2679      AdjustNull = createBasicBlock("adjust.null");
2680      AdjustNotNull = createBasicBlock("adjust.notnull");
2681      AdjustEnd = createBasicBlock("adjust.end");
2682
2683      llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
2684      Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
2685      EmitBlock(AdjustNotNull);
2686    }
2687
2688    ReturnValue = PerformTypeAdjustment(*this, ReturnValue,
2689                                        Thunk.Return.NonVirtual,
2690                                        Thunk.Return.VBaseOffsetOffset);
2691
2692    if (NullCheckValue) {
2693      Builder.CreateBr(AdjustEnd);
2694      EmitBlock(AdjustNull);
2695      Builder.CreateBr(AdjustEnd);
2696      EmitBlock(AdjustEnd);
2697
2698      llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType());
2699      PHI->reserveOperandSpace(2);
2700      PHI->addIncoming(ReturnValue, AdjustNotNull);
2701      PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
2702                       AdjustNull);
2703      ReturnValue = PHI;
2704    }
2705
2706    RV = RValue::get(ReturnValue);
2707  }
2708
2709  if (!ResultType->isVoidType() && Slot.isNull())
2710    CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
2711
2712  FinishFunction();
2713
2714  // Set the right linkage.
2715  CGM.setFunctionLinkage(MD, Fn);
2716
2717  // Set the right visibility.
2718  setThunkVisibility(CGM, MD, Thunk, Fn);
2719}
2720
2721void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
2722                               bool UseAvailableExternallyLinkage)
2723{
2724  const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD);
2725
2726  // FIXME: re-use FnInfo in this computation.
2727  llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
2728
2729  // Strip off a bitcast if we got one back.
2730  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2731    assert(CE->getOpcode() == llvm::Instruction::BitCast);
2732    Entry = CE->getOperand(0);
2733  }
2734
2735  // There's already a declaration with the same name, check if it has the same
2736  // type or if we need to replace it.
2737  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
2738      CGM.getTypes().GetFunctionTypeForVTable(GD)) {
2739    llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
2740
2741    // If the types mismatch then we have to rewrite the definition.
2742    assert(OldThunkFn->isDeclaration() &&
2743           "Shouldn't replace non-declaration");
2744
2745    // Remove the name from the old thunk function and get a new thunk.
2746    OldThunkFn->setName(llvm::StringRef());
2747    Entry = CGM.GetAddrOfThunk(GD, Thunk);
2748
2749    // If needed, replace the old thunk with a bitcast.
2750    if (!OldThunkFn->use_empty()) {
2751      llvm::Constant *NewPtrForOldDecl =
2752        llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
2753      OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
2754    }
2755
2756    // Remove the old thunk.
2757    OldThunkFn->eraseFromParent();
2758  }
2759
2760  llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
2761
2762  if (!ThunkFn->isDeclaration()) {
2763    if (UseAvailableExternallyLinkage) {
2764      // There is already a thunk emitted for this function, do nothing.
2765      return;
2766    }
2767
2768    // If a function has a body, it should have available_externally linkage.
2769    assert(ThunkFn->hasAvailableExternallyLinkage() &&
2770           "Function should have available_externally linkage!");
2771
2772    // Change the linkage.
2773    CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
2774    return;
2775  }
2776
2777  // Actually generate the thunk body.
2778  CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
2779
2780  if (UseAvailableExternallyLinkage)
2781    ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2782}
2783
2784void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
2785                                                       const ThunkInfo &Thunk) {
2786  // We only want to do this when building with optimizations.
2787  if (!CGM.getCodeGenOpts().OptimizationLevel)
2788    return;
2789
2790  // We can't emit thunks for member functions with incomplete types.
2791  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2792  if (CGM.getTypes().VerifyFuncTypeComplete(MD->getType().getTypePtr()))
2793    return;
2794
2795  EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
2796}
2797
2798void CodeGenVTables::EmitThunks(GlobalDecl GD)
2799{
2800  const CXXMethodDecl *MD =
2801    cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
2802
2803  // We don't need to generate thunks for the base destructor.
2804  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2805    return;
2806
2807  const CXXRecordDecl *RD = MD->getParent();
2808
2809  // Compute VTable related info for this class.
2810  ComputeVTableRelatedInformation(RD, false);
2811
2812  ThunksMapTy::const_iterator I = Thunks.find(MD);
2813  if (I == Thunks.end()) {
2814    // We did not find a thunk for this method.
2815    return;
2816  }
2817
2818  const ThunkInfoVectorTy &ThunkInfoVector = I->second;
2819  for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
2820    EmitThunk(GD, ThunkInfoVector[I], /*UseAvailableExternallyLinkage=*/false);
2821}
2822
2823void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD,
2824                                                     bool RequireVTable) {
2825  VTableLayoutData &Entry = VTableLayoutMap[RD];
2826
2827  // We may need to generate a definition for this vtable.
2828  if (RequireVTable && !Entry.getInt()) {
2829    if (ShouldEmitVTableInThisTU(RD))
2830      CGM.DeferredVTables.push_back(RD);
2831
2832    Entry.setInt(true);
2833  }
2834
2835  // Check if we've computed this information before.
2836  if (Entry.getPointer())
2837    return;
2838
2839  VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
2840
2841  // Add the VTable layout.
2842  uint64_t NumVTableComponents = Builder.getNumVTableComponents();
2843  // -fapple-kext adds an extra entry at end of vtbl.
2844  bool IsAppleKext = CGM.getContext().getLangOptions().AppleKext;
2845  if (IsAppleKext)
2846    NumVTableComponents += 1;
2847
2848  uint64_t *LayoutData = new uint64_t[NumVTableComponents + 1];
2849  if (IsAppleKext)
2850    LayoutData[NumVTableComponents] = 0;
2851  Entry.setPointer(LayoutData);
2852
2853  // Store the number of components.
2854  LayoutData[0] = NumVTableComponents;
2855
2856  // Store the components.
2857  std::copy(Builder.vtable_components_data_begin(),
2858            Builder.vtable_components_data_end(),
2859            &LayoutData[1]);
2860
2861  // Add the known thunks.
2862  Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2863
2864  // Add the thunks needed in this vtable.
2865  assert(!VTableThunksMap.count(RD) &&
2866         "Thunks already exists for this vtable!");
2867
2868  VTableThunksTy &VTableThunks = VTableThunksMap[RD];
2869  VTableThunks.append(Builder.vtable_thunks_begin(),
2870                      Builder.vtable_thunks_end());
2871
2872  // Sort them.
2873  std::sort(VTableThunks.begin(), VTableThunks.end());
2874
2875  // Add the address points.
2876  for (VTableBuilder::AddressPointsMapTy::const_iterator I =
2877       Builder.address_points_begin(), E = Builder.address_points_end();
2878       I != E; ++I) {
2879
2880    uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
2881
2882    // Check if we already have the address points for this base.
2883    assert(!AddressPoint && "Address point already exists for this base!");
2884
2885    AddressPoint = I->second;
2886  }
2887
2888  // If we don't have the vbase information for this class, insert it.
2889  // getVirtualBaseOffsetOffset will compute it separately without computing
2890  // the rest of the vtable related information.
2891  if (!RD->getNumVBases())
2892    return;
2893
2894  const RecordType *VBaseRT =
2895    RD->vbases_begin()->getType()->getAs<RecordType>();
2896  const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2897
2898  if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2899    return;
2900
2901  for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2902       Builder.getVBaseOffsetOffsets().begin(),
2903       E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2904    // Insert all types.
2905    ClassPairTy ClassPair(RD, I->first);
2906
2907    VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2908  }
2909}
2910
2911llvm::Constant *
2912CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
2913                                        const uint64_t *Components,
2914                                        unsigned NumComponents,
2915                                        const VTableThunksTy &VTableThunks) {
2916  llvm::SmallVector<llvm::Constant *, 64> Inits;
2917
2918  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
2919
2920  const llvm::Type *PtrDiffTy =
2921    CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2922
2923  QualType ClassType = CGM.getContext().getTagDeclType(RD);
2924  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
2925
2926  unsigned NextVTableThunkIndex = 0;
2927
2928  llvm::Constant* PureVirtualFn = 0;
2929
2930  for (unsigned I = 0; I != NumComponents; ++I) {
2931    VTableComponent Component =
2932      VTableComponent::getFromOpaqueInteger(Components[I]);
2933
2934    llvm::Constant *Init = 0;
2935
2936    switch (Component.getKind()) {
2937    case VTableComponent::CK_VCallOffset:
2938      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
2939      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2940      break;
2941    case VTableComponent::CK_VBaseOffset:
2942      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
2943      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2944      break;
2945    case VTableComponent::CK_OffsetToTop:
2946      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
2947      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2948      break;
2949    case VTableComponent::CK_RTTI:
2950      Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
2951      break;
2952    case VTableComponent::CK_FunctionPointer:
2953    case VTableComponent::CK_CompleteDtorPointer:
2954    case VTableComponent::CK_DeletingDtorPointer: {
2955      GlobalDecl GD;
2956
2957      // Get the right global decl.
2958      switch (Component.getKind()) {
2959      default:
2960        llvm_unreachable("Unexpected vtable component kind");
2961      case VTableComponent::CK_FunctionPointer:
2962        GD = Component.getFunctionDecl();
2963        break;
2964      case VTableComponent::CK_CompleteDtorPointer:
2965        GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
2966        break;
2967      case VTableComponent::CK_DeletingDtorPointer:
2968        GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
2969        break;
2970      }
2971
2972      if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
2973        // We have a pure virtual member function.
2974        if (!PureVirtualFn) {
2975          const llvm::FunctionType *Ty =
2976            llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2977                                    /*isVarArg=*/false);
2978          PureVirtualFn =
2979            CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
2980          PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
2981                                                         Int8PtrTy);
2982        }
2983
2984        Init = PureVirtualFn;
2985      } else {
2986        // Check if we should use a thunk.
2987        if (NextVTableThunkIndex < VTableThunks.size() &&
2988            VTableThunks[NextVTableThunkIndex].first == I) {
2989          const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
2990
2991          Init = CGM.GetAddrOfThunk(GD, Thunk);
2992          MaybeEmitThunkAvailableExternally(GD, Thunk);
2993
2994          NextVTableThunkIndex++;
2995        } else {
2996          const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
2997
2998          Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
2999        }
3000
3001        Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
3002      }
3003      break;
3004    }
3005
3006    case VTableComponent::CK_UnusedFunctionPointer:
3007      Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
3008      break;
3009    };
3010
3011    Inits.push_back(Init);
3012  }
3013
3014  llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
3015  return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
3016}
3017
3018llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
3019  llvm::SmallString<256> OutName;
3020  llvm::raw_svector_ostream Out(OutName);
3021  CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
3022  Out.flush();
3023  llvm::StringRef Name = OutName.str();
3024
3025  ComputeVTableRelatedInformation(RD, true);
3026
3027  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
3028  llvm::ArrayType *ArrayType =
3029    llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
3030
3031  llvm::GlobalVariable *GV =
3032    CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
3033                                          llvm::GlobalValue::ExternalLinkage);
3034  GV->setUnnamedAddr(true);
3035  return GV;
3036}
3037
3038void
3039CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
3040                                     llvm::GlobalVariable::LinkageTypes Linkage,
3041                                     const CXXRecordDecl *RD) {
3042  // Dump the vtable layout if necessary.
3043  if (CGM.getLangOptions().DumpVTableLayouts) {
3044    VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
3045
3046    Builder.dumpLayout(llvm::errs());
3047  }
3048
3049  assert(VTableThunksMap.count(RD) &&
3050         "No thunk status for this record decl!");
3051
3052  const VTableThunksTy& Thunks = VTableThunksMap[RD];
3053
3054  // Create and set the initializer.
3055  llvm::Constant *Init =
3056    CreateVTableInitializer(RD, getVTableComponentsData(RD),
3057                            getNumVTableComponents(RD), Thunks);
3058  VTable->setInitializer(Init);
3059
3060  // Set the correct linkage.
3061  VTable->setLinkage(Linkage);
3062
3063  // Set the right visibility.
3064  CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
3065}
3066
3067llvm::GlobalVariable *
3068CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
3069                                      const BaseSubobject &Base,
3070                                      bool BaseIsVirtual,
3071                                   llvm::GlobalVariable::LinkageTypes Linkage,
3072                                      VTableAddressPointsMapTy& AddressPoints) {
3073  VTableBuilder Builder(*this, Base.getBase(),
3074                        CGM.getContext().toBits(Base.getBaseOffset()),
3075                        /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
3076
3077  // Dump the vtable layout if necessary.
3078  if (CGM.getLangOptions().DumpVTableLayouts)
3079    Builder.dumpLayout(llvm::errs());
3080
3081  // Add the address points.
3082  AddressPoints.insert(Builder.address_points_begin(),
3083                       Builder.address_points_end());
3084
3085  // Get the mangled construction vtable name.
3086  llvm::SmallString<256> OutName;
3087  llvm::raw_svector_ostream Out(OutName);
3088  CGM.getCXXABI().getMangleContext().
3089    mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
3090                        Out);
3091  Out.flush();
3092  llvm::StringRef Name = OutName.str();
3093
3094  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
3095  llvm::ArrayType *ArrayType =
3096    llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
3097
3098  // Create the variable that will hold the construction vtable.
3099  llvm::GlobalVariable *VTable =
3100    CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
3101  CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
3102
3103  // V-tables are always unnamed_addr.
3104  VTable->setUnnamedAddr(true);
3105
3106  // Add the thunks.
3107  VTableThunksTy VTableThunks;
3108  VTableThunks.append(Builder.vtable_thunks_begin(),
3109                      Builder.vtable_thunks_end());
3110
3111  // Sort them.
3112  std::sort(VTableThunks.begin(), VTableThunks.end());
3113
3114  // Create and set the initializer.
3115  llvm::Constant *Init =
3116    CreateVTableInitializer(Base.getBase(),
3117                            Builder.vtable_components_data_begin(),
3118                            Builder.getNumVTableComponents(), VTableThunks);
3119  VTable->setInitializer(Init);
3120
3121  return VTable;
3122}
3123
3124void
3125CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
3126                                  const CXXRecordDecl *RD) {
3127  llvm::GlobalVariable *&VTable = VTables[RD];
3128  if (VTable) {
3129    assert(VTable->getInitializer() && "VTable doesn't have a definition!");
3130    return;
3131  }
3132
3133  VTable = GetAddrOfVTable(RD);
3134  EmitVTableDefinition(VTable, Linkage, RD);
3135
3136  if (RD->getNumVBases()) {
3137    llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
3138    EmitVTTDefinition(VTT, Linkage, RD);
3139  }
3140
3141  // If this is the magic class __cxxabiv1::__fundamental_type_info,
3142  // we will emit the typeinfo for the fundamental types. This is the
3143  // same behaviour as GCC.
3144  const DeclContext *DC = RD->getDeclContext();
3145  if (RD->getIdentifier() &&
3146      RD->getIdentifier()->isStr("__fundamental_type_info") &&
3147      isa<NamespaceDecl>(DC) &&
3148      cast<NamespaceDecl>(DC)->getIdentifier() &&
3149      cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
3150      DC->getParent()->isTranslationUnit())
3151    CGM.EmitFundamentalRTTIDescriptors();
3152}
3153