Coverage Report

Created: 2020-12-01 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
10
// The class in this file generates structures that follow the Microsoft
11
// Visual C++ ABI, which is actually not very well documented at all outside
12
// of Microsoft.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#include "CGCXXABI.h"
17
#include "CGCleanup.h"
18
#include "CGVTables.h"
19
#include "CodeGenModule.h"
20
#include "CodeGenTypes.h"
21
#include "TargetInfo.h"
22
#include "clang/AST/Attr.h"
23
#include "clang/AST/CXXInheritance.h"
24
#include "clang/AST/Decl.h"
25
#include "clang/AST/DeclCXX.h"
26
#include "clang/AST/StmtCXX.h"
27
#include "clang/AST/VTableBuilder.h"
28
#include "clang/CodeGen/ConstantInitBuilder.h"
29
#include "llvm/ADT/StringExtras.h"
30
#include "llvm/ADT/StringSet.h"
31
#include "llvm/IR/Intrinsics.h"
32
33
using namespace clang;
34
using namespace CodeGen;
35
36
namespace {
37
38
/// Holds all the vbtable globals for a given class.
39
struct VBTableGlobals {
40
  const VPtrInfoVector *VBTables;
41
  SmallVector<llvm::GlobalVariable *, 2> Globals;
42
};
43
44
class MicrosoftCXXABI : public CGCXXABI {
45
public:
46
  MicrosoftCXXABI(CodeGenModule &CGM)
47
      : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
48
        ClassHierarchyDescriptorType(nullptr),
49
        CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
50
723
        ThrowInfoType(nullptr) {}
51
52
  bool HasThisReturn(GlobalDecl GD) const override;
53
  bool hasMostDerivedReturn(GlobalDecl GD) const override;
54
55
  bool classifyReturnType(CGFunctionInfo &FI) const override;
56
57
  RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
58
59
0
  bool isSRetParameterAfterThis() const override { return true; }
60
61
858
  bool isThisCompleteObject(GlobalDecl GD) const override {
62
    // The Microsoft ABI doesn't use separate complete-object vs.
63
    // base-object variants of constructors, but it does of destructors.
64
858
    if (isa<CXXDestructorDecl>(GD.getDecl())) {
65
307
      switch (GD.getDtorType()) {
66
243
      case Dtor_Complete:
67
243
      case Dtor_Deleting:
68
243
        return true;
69
70
64
      case Dtor_Base:
71
64
        return false;
72
73
0
      case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
74
0
      }
75
0
      llvm_unreachable("bad dtor kind");
76
0
    }
77
78
    // No other kinds.
79
551
    return false;
80
551
  }
81
82
  size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
83
130
                              FunctionArgList &Args) const override {
84
130
    assert(Args.size() >= 2 &&
85
130
           "expected the arglist to have at least two args!");
86
    // The 'most_derived' parameter goes second if the ctor is variadic and
87
    // has v-bases.
88
130
    if (CD->getParent()->getNumVBases() > 0 &&
89
17
        CD->getType()->castAs<FunctionProtoType>()->isVariadic())
90
0
      return 2;
91
130
    return 1;
92
130
  }
93
94
4
  std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
95
4
    std::vector<CharUnits> VBPtrOffsets;
96
4
    const ASTContext &Context = getContext();
97
4
    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
98
99
4
    const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
100
6
    for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
101
6
      const ASTRecordLayout &SubobjectLayout =
102
6
          Context.getASTRecordLayout(VBT->IntroducingObject);
103
6
      CharUnits Offs = VBT->NonVirtualOffset;
104
6
      Offs += SubobjectLayout.getVBPtrOffset();
105
6
      if (VBT->getVBaseWithVPtr())
106
2
        Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
107
6
      VBPtrOffsets.push_back(Offs);
108
6
    }
109
4
    llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
110
4
    return VBPtrOffsets;
111
4
  }
112
113
12
  StringRef GetPureVirtualCallName() override { return "_purecall"; }
114
1
  StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
115
116
  void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
117
                               Address Ptr, QualType ElementType,
118
                               const CXXDestructorDecl *Dtor) override;
119
120
  void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
121
  void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
122
123
  void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
124
125
  llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
126
                                                   const VPtrInfo &Info);
127
128
  llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
129
  CatchTypeInfo
130
  getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
131
132
  /// MSVC needs an extra flag to indicate a catchall.
133
11
  CatchTypeInfo getCatchAllTypeInfo() override {
134
11
    return CatchTypeInfo{nullptr, 0x40};
135
11
  }
136
137
  bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
138
  void EmitBadTypeidCall(CodeGenFunction &CGF) override;
139
  llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
140
                          Address ThisPtr,
141
                          llvm::Type *StdTypeInfoPtrTy) override;
142
143
  bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
144
                                          QualType SrcRecordTy) override;
145
146
  llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
147
                                   QualType SrcRecordTy, QualType DestTy,
148
                                   QualType DestRecordTy,
149
                                   llvm::BasicBlock *CastEnd) override;
150
151
  llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
152
                                     QualType SrcRecordTy,
153
                                     QualType DestTy) override;
154
155
  bool EmitBadCastCall(CodeGenFunction &CGF) override;
156
88
  bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
157
88
    return false;
158
88
  }
159
160
  llvm::Value *
161
  GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
162
                            const CXXRecordDecl *ClassDecl,
163
                            const CXXRecordDecl *BaseClassDecl) override;
164
165
  llvm::BasicBlock *
166
  EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
167
                                const CXXRecordDecl *RD) override;
168
169
  llvm::BasicBlock *
170
  EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
171
172
  void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
173
                                              const CXXRecordDecl *RD) override;
174
175
  void EmitCXXConstructors(const CXXConstructorDecl *D) override;
176
177
  // Background on MSVC destructors
178
  // ==============================
179
  //
180
  // Both Itanium and MSVC ABIs have destructor variants.  The variant names
181
  // roughly correspond in the following way:
182
  //   Itanium       Microsoft
183
  //   Base       -> no name, just ~Class
184
  //   Complete   -> vbase destructor
185
  //   Deleting   -> scalar deleting destructor
186
  //                 vector deleting destructor
187
  //
188
  // The base and complete destructors are the same as in Itanium, although the
189
  // complete destructor does not accept a VTT parameter when there are virtual
190
  // bases.  A separate mechanism involving vtordisps is used to ensure that
191
  // virtual methods of destroyed subobjects are not called.
192
  //
193
  // The deleting destructors accept an i32 bitfield as a second parameter.  Bit
194
  // 1 indicates if the memory should be deleted.  Bit 2 indicates if the this
195
  // pointer points to an array.  The scalar deleting destructor assumes that
196
  // bit 2 is zero, and therefore does not contain a loop.
197
  //
198
  // For virtual destructors, only one entry is reserved in the vftable, and it
199
  // always points to the vector deleting destructor.  The vector deleting
200
  // destructor is the most general, so it can be used to destroy objects in
201
  // place, delete single heap objects, or delete arrays.
202
  //
203
  // A TU defining a non-inline destructor is only guaranteed to emit a base
204
  // destructor, and all of the other variants are emitted on an as-needed basis
205
  // in COMDATs.  Because a non-base destructor can be emitted in a TU that
206
  // lacks a definition for the destructor, non-base destructors must always
207
  // delegate to or alias the base destructor.
208
209
  AddedStructorArgCounts
210
  buildStructorSignature(GlobalDecl GD,
211
                         SmallVectorImpl<CanQualType> &ArgTys) override;
212
213
  /// Non-base dtors should be emitted as delegating thunks in this ABI.
214
  bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
215
716
                              CXXDtorType DT) const override {
216
716
    return DT != Dtor_Base;
217
716
  }
218
219
  void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
220
                                  const CXXDestructorDecl *Dtor,
221
                                  CXXDtorType DT) const override;
222
223
  llvm::GlobalValue::LinkageTypes
224
  getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
225
                          CXXDtorType DT) const override;
226
227
  void EmitCXXDestructors(const CXXDestructorDecl *D) override;
228
229
  const CXXRecordDecl *
230
8.18k
  getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
231
8.18k
    if (MD->isVirtual() && 
!isa<CXXDestructorDecl>(MD)3.20k
) {
232
2.62k
      MethodVFTableLocation ML =
233
2.62k
          CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
234
      // The vbases might be ordered differently in the final overrider object
235
      // and the complete object, so the "this" argument may sometimes point to
236
      // memory that has no particular type (e.g. past the complete object).
237
      // In this case, we just use a generic pointer type.
238
      // FIXME: might want to have a more precise type in the non-virtual
239
      // multiple inheritance case.
240
2.62k
      if (ML.VBase || 
!ML.VFPtrOffset.isZero()2.05k
)
241
688
        return nullptr;
242
7.49k
    }
243
7.49k
    return MD->getParent();
244
7.49k
  }
245
246
  Address
247
  adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
248
                                           Address This,
249
                                           bool VirtualCall) override;
250
251
  void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
252
                                 FunctionArgList &Params) override;
253
254
  void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
255
256
  AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
257
                                               const CXXConstructorDecl *D,
258
                                               CXXCtorType Type,
259
                                               bool ForVirtualBase,
260
                                               bool Delegating) override;
261
262
  llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
263
                                             const CXXDestructorDecl *DD,
264
                                             CXXDtorType Type,
265
                                             bool ForVirtualBase,
266
                                             bool Delegating) override;
267
268
  void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
269
                          CXXDtorType Type, bool ForVirtualBase,
270
                          bool Delegating, Address This,
271
                          QualType ThisTy) override;
272
273
  void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
274
                              llvm::GlobalVariable *VTable);
275
276
  void emitVTableDefinitions(CodeGenVTables &CGVT,
277
                             const CXXRecordDecl *RD) override;
278
279
  bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
280
                                           CodeGenFunction::VPtr Vptr) override;
281
282
  /// Don't initialize vptrs if dynamic class
283
  /// is marked with with the 'novtable' attribute.
284
853
  bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
285
853
    return !VTableClass->hasAttr<MSNoVTableAttr>();
286
853
  }
287
288
  llvm::Constant *
289
  getVTableAddressPoint(BaseSubobject Base,
290
                        const CXXRecordDecl *VTableClass) override;
291
292
  llvm::Value *getVTableAddressPointInStructor(
293
      CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
294
      BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
295
296
  llvm::Constant *
297
  getVTableAddressPointForConstExpr(BaseSubobject Base,
298
                                    const CXXRecordDecl *VTableClass) override;
299
300
  llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
301
                                        CharUnits VPtrOffset) override;
302
303
  CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
304
                                     Address This, llvm::Type *Ty,
305
                                     SourceLocation Loc) override;
306
307
  llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
308
                                         const CXXDestructorDecl *Dtor,
309
                                         CXXDtorType DtorType, Address This,
310
                                         DeleteOrMemberCallExpr E) override;
311
312
  void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
313
94
                                        CallArgList &CallArgs) override {
314
94
    assert(GD.getDtorType() == Dtor_Deleting &&
315
94
           "Only deleting destructor thunks are available in this ABI");
316
94
    CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
317
94
                 getContext().IntTy);
318
94
  }
319
320
  void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
321
322
  llvm::GlobalVariable *
323
  getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
324
                   llvm::GlobalVariable::LinkageTypes Linkage);
325
326
  llvm::GlobalVariable *
327
  getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
328
4
                                  const CXXRecordDecl *DstRD) {
329
4
    SmallString<256> OutName;
330
4
    llvm::raw_svector_ostream Out(OutName);
331
4
    getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
332
4
    StringRef MangledName = OutName.str();
333
334
4
    if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
335
0
      return VDispMap;
336
337
4
    MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
338
4
    unsigned NumEntries = 1 + SrcRD->getNumVBases();
339
4
    SmallVector<llvm::Constant *, 4> Map(NumEntries,
340
4
                                         llvm::UndefValue::get(CGM.IntTy));
341
4
    Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
342
4
    bool AnyDifferent = false;
343
4
    for (const auto &I : SrcRD->vbases()) {
344
4
      const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
345
4
      if (!DstRD->isVirtuallyDerivedFrom(VBase))
346
0
        continue;
347
348
4
      unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
349
4
      unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
350
4
      Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
351
4
      AnyDifferent |= SrcVBIndex != DstVBIndex;
352
4
    }
353
    // This map would be useless, don't use it.
354
4
    if (!AnyDifferent)
355
4
      return nullptr;
356
357
0
    llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
358
0
    llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
359
0
    llvm::GlobalValue::LinkageTypes Linkage =
360
0
        SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
361
0
            ? llvm::GlobalValue::LinkOnceODRLinkage
362
0
            : llvm::GlobalValue::InternalLinkage;
363
0
    auto *VDispMap = new llvm::GlobalVariable(
364
0
        CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
365
0
        /*Initializer=*/Init, MangledName);
366
0
    return VDispMap;
367
0
  }
368
369
  void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
370
                             llvm::GlobalVariable *GV) const;
371
372
  void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
373
269
                       GlobalDecl GD, bool ReturnAdjustment) override {
374
269
    GVALinkage Linkage =
375
269
        getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
376
377
269
    if (Linkage == GVA_Internal)
378
7
      Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
379
262
    else if (ReturnAdjustment)
380
38
      Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
381
224
    else
382
224
      Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
383
269
  }
384
385
269
  bool exportThunk() override { return false; }
386
387
  llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
388
                                     const ThisAdjustment &TA) override;
389
390
  llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
391
                                       const ReturnAdjustment &RA) override;
392
393
  void EmitThreadLocalInitFuncs(
394
      CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
395
      ArrayRef<llvm::Function *> CXXThreadLocalInits,
396
      ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
397
398
10
  bool usesThreadWrapperFunction(const VarDecl *VD) const override {
399
10
    return false;
400
10
  }
401
  LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
402
                                      QualType LValType) override;
403
404
  void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
405
                       llvm::GlobalVariable *DeclPtr,
406
                       bool PerformInit) override;
407
  void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
408
                          llvm::FunctionCallee Dtor,
409
                          llvm::Constant *Addr) override;
410
411
  // ==== Notes on array cookies =========
412
  //
413
  // MSVC seems to only use cookies when the class has a destructor; a
414
  // two-argument usual array deallocation function isn't sufficient.
415
  //
416
  // For example, this code prints "100" and "1":
417
  //   struct A {
418
  //     char x;
419
  //     void *operator new[](size_t sz) {
420
  //       printf("%u\n", sz);
421
  //       return malloc(sz);
422
  //     }
423
  //     void operator delete[](void *p, size_t sz) {
424
  //       printf("%u\n", sz);
425
  //       free(p);
426
  //     }
427
  //   };
428
  //   int main() {
429
  //     A *p = new A[100];
430
  //     delete[] p;
431
  //   }
432
  // Whereas it prints "104" and "104" if you give A a destructor.
433
434
  bool requiresArrayCookie(const CXXDeleteExpr *expr,
435
                           QualType elementType) override;
436
  bool requiresArrayCookie(const CXXNewExpr *expr) override;
437
  CharUnits getArrayCookieSizeImpl(QualType type) override;
438
  Address InitializeArrayCookie(CodeGenFunction &CGF,
439
                                Address NewPtr,
440
                                llvm::Value *NumElements,
441
                                const CXXNewExpr *expr,
442
                                QualType ElementType) override;
443
  llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
444
                                   Address allocPtr,
445
                                   CharUnits cookieSize) override;
446
447
  friend struct MSRTTIBuilder;
448
449
3.93k
  bool isImageRelative() const {
450
3.93k
    return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64;
451
3.93k
  }
452
453
  // 5 routines for constructing the llvm types for MS RTTI structs.
454
352
  llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
455
352
    llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
456
352
    TDTypeName += llvm::utostr(TypeInfoString.size());
457
352
    llvm::StructType *&TypeDescriptorType =
458
352
        TypeDescriptorTypeMap[TypeInfoString.size()];
459
352
    if (TypeDescriptorType)
460
178
      return TypeDescriptorType;
461
174
    llvm::Type *FieldTypes[] = {
462
174
        CGM.Int8PtrPtrTy,
463
174
        CGM.Int8PtrTy,
464
174
        llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
465
174
    TypeDescriptorType =
466
174
        llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
467
174
    return TypeDescriptorType;
468
174
  }
469
470
802
  llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
471
802
    if (!isImageRelative())
472
444
      return PtrType;
473
358
    return CGM.IntTy;
474
358
  }
475
476
699
  llvm::StructType *getBaseClassDescriptorType() {
477
699
    if (BaseClassDescriptorType)
478
634
      return BaseClassDescriptorType;
479
65
    llvm::Type *FieldTypes[] = {
480
65
        getImageRelativeType(CGM.Int8PtrTy),
481
65
        CGM.IntTy,
482
65
        CGM.IntTy,
483
65
        CGM.IntTy,
484
65
        CGM.IntTy,
485
65
        CGM.IntTy,
486
65
        getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
487
65
    };
488
65
    BaseClassDescriptorType = llvm::StructType::create(
489
65
        CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
490
65
    return BaseClassDescriptorType;
491
65
  }
492
493
395
  llvm::StructType *getClassHierarchyDescriptorType() {
494
395
    if (ClassHierarchyDescriptorType)
495
330
      return ClassHierarchyDescriptorType;
496
    // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
497
65
    ClassHierarchyDescriptorType = llvm::StructType::create(
498
65
        CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
499
65
    llvm::Type *FieldTypes[] = {
500
65
        CGM.IntTy,
501
65
        CGM.IntTy,
502
65
        CGM.IntTy,
503
65
        getImageRelativeType(
504
65
            getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
505
65
    };
506
65
    ClassHierarchyDescriptorType->setBody(FieldTypes);
507
65
    return ClassHierarchyDescriptorType;
508
65
  }
509
510
251
  llvm::StructType *getCompleteObjectLocatorType() {
511
251
    if (CompleteObjectLocatorType)
512
186
      return CompleteObjectLocatorType;
513
65
    CompleteObjectLocatorType = llvm::StructType::create(
514
65
        CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
515
65
    llvm::Type *FieldTypes[] = {
516
65
        CGM.IntTy,
517
65
        CGM.IntTy,
518
65
        CGM.IntTy,
519
65
        getImageRelativeType(CGM.Int8PtrTy),
520
65
        getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
521
65
        getImageRelativeType(CompleteObjectLocatorType),
522
65
    };
523
65
    llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
524
65
    if (!isImageRelative())
525
33
      FieldTypesRef = FieldTypesRef.drop_back();
526
65
    CompleteObjectLocatorType->setBody(FieldTypesRef);
527
65
    return CompleteObjectLocatorType;
528
65
  }
529
530
1.31k
  llvm::GlobalVariable *getImageBase() {
531
1.31k
    StringRef Name = "__ImageBase";
532
1.31k
    if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
533
1.28k
      return GV;
534
535
34
    auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
536
34
                                        /*isConstant=*/true,
537
34
                                        llvm::GlobalValue::ExternalLinkage,
538
34
                                        /*Initializer=*/nullptr, Name);
539
34
    CGM.setDSOLocal(GV);
540
34
    return GV;
541
34
  }
542
543
2.56k
  llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
544
2.56k
    if (!isImageRelative())
545
1.24k
      return PtrVal;
546
547
1.32k
    if (PtrVal->isNullValue())
548
6
      return llvm::Constant::getNullValue(CGM.IntTy);
549
550
1.31k
    llvm::Constant *ImageBaseAsInt =
551
1.31k
        llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
552
1.31k
    llvm::Constant *PtrValAsInt =
553
1.31k
        llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
554
1.31k
    llvm::Constant *Diff =
555
1.31k
        llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
556
1.31k
                                   /*HasNUW=*/true, /*HasNSW=*/true);
557
1.31k
    return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
558
1.31k
  }
559
560
private:
561
5.24k
  MicrosoftMangleContext &getMangleContext() {
562
5.24k
    return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
563
5.24k
  }
564
565
570
  llvm::Constant *getZeroInt() {
566
570
    return llvm::ConstantInt::get(CGM.IntTy, 0);
567
570
  }
568
569
121
  llvm::Constant *getAllOnesInt() {
570
121
    return  llvm::Constant::getAllOnesValue(CGM.IntTy);
571
121
  }
572
573
  CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
574
575
  void
576
  GetNullMemberPointerFields(const MemberPointerType *MPT,
577
                             llvm::SmallVectorImpl<llvm::Constant *> &fields);
578
579
  /// Shared code for virtual base adjustment.  Returns the offset from
580
  /// the vbptr to the virtual base.  Optionally returns the address of the
581
  /// vbptr itself.
582
  llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
583
                                       Address Base,
584
                                       llvm::Value *VBPtrOffset,
585
                                       llvm::Value *VBTableOffset,
586
                                       llvm::Value **VBPtr = nullptr);
587
588
  llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
589
                                       Address Base,
590
                                       int32_t VBPtrOffset,
591
                                       int32_t VBTableOffset,
592
37
                                       llvm::Value **VBPtr = nullptr) {
593
37
    assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
594
37
    llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
595
37
                *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
596
37
    return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
597
37
  }
598
599
  std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
600
  performBaseAdjustment(CodeGenFunction &CGF, Address Value,
601
                        QualType SrcRecordTy);
602
603
  /// Performs a full virtual base adjustment.  Used to dereference
604
  /// pointers to members of virtual bases.
605
  llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
606
                                 const CXXRecordDecl *RD, Address Base,
607
                                 llvm::Value *VirtualBaseAdjustmentOffset,
608
                                 llvm::Value *VBPtrOffset /* optional */);
609
610
  /// Emits a full member pointer with the fields common to data and
611
  /// function member pointers.
612
  llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
613
                                        bool IsMemberFunction,
614
                                        const CXXRecordDecl *RD,
615
                                        CharUnits NonVirtualBaseAdjustment,
616
                                        unsigned VBTableIndex);
617
618
  bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
619
                                   llvm::Constant *MP);
620
621
  /// - Initialize all vbptrs of 'this' with RD as the complete type.
622
  void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
623
624
  /// Caching wrapper around VBTableBuilder::enumerateVBTables().
625
  const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
626
627
  /// Generate a thunk for calling a virtual member function MD.
628
  llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
629
                                         const MethodVFTableLocation &ML);
630
631
  llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
632
                                        CharUnits offset);
633
634
public:
635
  llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
636
637
  bool isZeroInitializable(const MemberPointerType *MPT) override;
638
639
421
  bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
640
421
    const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
641
421
    return RD->hasAttr<MSInheritanceAttr>();
642
421
  }
643
644
  llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
645
646
  llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
647
                                        CharUnits offset) override;
648
  llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
649
  llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
650
651
  llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
652
                                           llvm::Value *L,
653
                                           llvm::Value *R,
654
                                           const MemberPointerType *MPT,
655
                                           bool Inequality) override;
656
657
  llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
658
                                          llvm::Value *MemPtr,
659
                                          const MemberPointerType *MPT) override;
660
661
  llvm::Value *
662
  EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
663
                               Address Base, llvm::Value *MemPtr,
664
                               const MemberPointerType *MPT) override;
665
666
  llvm::Value *EmitNonNullMemberPointerConversion(
667
      const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
668
      CastKind CK, CastExpr::path_const_iterator PathBegin,
669
      CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
670
      CGBuilderTy &Builder);
671
672
  llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
673
                                           const CastExpr *E,
674
                                           llvm::Value *Src) override;
675
676
  llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
677
                                              llvm::Constant *Src) override;
678
679
  llvm::Constant *EmitMemberPointerConversion(
680
      const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
681
      CastKind CK, CastExpr::path_const_iterator PathBegin,
682
      CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
683
684
  CGCallee
685
  EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
686
                                  Address This, llvm::Value *&ThisPtrForCall,
687
                                  llvm::Value *MemPtr,
688
                                  const MemberPointerType *MPT) override;
689
690
  void emitCXXStructor(GlobalDecl GD) override;
691
692
120
  llvm::StructType *getCatchableTypeType() {
693
120
    if (CatchableTypeType)
694
104
      return CatchableTypeType;
695
16
    llvm::Type *FieldTypes[] = {
696
16
        CGM.IntTy,                           // Flags
697
16
        getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
698
16
        CGM.IntTy,                           // NonVirtualAdjustment
699
16
        CGM.IntTy,                           // OffsetToVBPtr
700
16
        CGM.IntTy,                           // VBTableIndex
701
16
        CGM.IntTy,                           // Size
702
16
        getImageRelativeType(CGM.Int8PtrTy)  // CopyCtor
703
16
    };
704
16
    CatchableTypeType = llvm::StructType::create(
705
16
        CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
706
16
    return CatchableTypeType;
707
16
  }
708
709
44
  llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
710
44
    llvm::StructType *&CatchableTypeArrayType =
711
44
        CatchableTypeArrayTypeMap[NumEntries];
712
44
    if (CatchableTypeArrayType)
713
24
      return CatchableTypeArrayType;
714
715
20
    llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
716
20
    CTATypeName += llvm::utostr(NumEntries);
717
20
    llvm::Type *CTType =
718
20
        getImageRelativeType(getCatchableTypeType()->getPointerTo());
719
20
    llvm::Type *FieldTypes[] = {
720
20
        CGM.IntTy,                               // NumEntries
721
20
        llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
722
20
    };
723
20
    CatchableTypeArrayType =
724
20
        llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
725
20
    return CatchableTypeArrayType;
726
20
  }
727
728
90
  llvm::StructType *getThrowInfoType() {
729
90
    if (ThrowInfoType)
730
73
      return ThrowInfoType;
731
17
    llvm::Type *FieldTypes[] = {
732
17
        CGM.IntTy,                           // Flags
733
17
        getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
734
17
        getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
735
17
        getImageRelativeType(CGM.Int8PtrTy)  // CatchableTypeArray
736
17
    };
737
17
    ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
738
17
                                             "eh.ThrowInfo");
739
17
    return ThrowInfoType;
740
17
  }
741
742
43
  llvm::FunctionCallee getThrowFn() {
743
    // _CxxThrowException is passed an exception object and a ThrowInfo object
744
    // which describes the exception.
745
43
    llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
746
43
    llvm::FunctionType *FTy =
747
43
        llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
748
43
    llvm::FunctionCallee Throw =
749
43
        CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
750
    // _CxxThrowException is stdcall on 32-bit x86 platforms.
751
43
    if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
752
41
      if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
753
41
        Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
754
41
    }
755
43
    return Throw;
756
43
  }
757
758
  llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
759
                                          CXXCtorType CT);
760
761
  llvm::Constant *getCatchableType(QualType T,
762
                                   uint32_t NVOffset = 0,
763
                                   int32_t VBPtrOffset = -1,
764
                                   uint32_t VBIndex = 0);
765
766
  llvm::GlobalVariable *getCatchableTypeArray(QualType T);
767
768
  llvm::GlobalVariable *getThrowInfo(QualType T) override;
769
770
  std::pair<llvm::Value *, const CXXRecordDecl *>
771
  LoadVTablePtr(CodeGenFunction &CGF, Address This,
772
                const CXXRecordDecl *RD) override;
773
774
private:
775
  typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
776
  typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
777
  typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
778
  /// All the vftables that have been referenced.
779
  VFTablesMapTy VFTablesMap;
780
  VTablesMapTy VTablesMap;
781
782
  /// This set holds the record decls we've deferred vtable emission for.
783
  llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
784
785
786
  /// All the vbtables which have been referenced.
787
  llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
788
789
  /// Info on the global variable used to guard initialization of static locals.
790
  /// The BitIndex field is only used for externally invisible declarations.
791
  struct GuardInfo {
792
24
    GuardInfo() : Guard(nullptr), BitIndex(0) {}
793
    llvm::GlobalVariable *Guard;
794
    unsigned BitIndex;
795
  };
796
797
  /// Map from DeclContext to the current guard variable.  We assume that the
798
  /// AST is visited in source code order.
799
  llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
800
  llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
801
  llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
802
803
  llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
804
  llvm::StructType *BaseClassDescriptorType;
805
  llvm::StructType *ClassHierarchyDescriptorType;
806
  llvm::StructType *CompleteObjectLocatorType;
807
808
  llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
809
810
  llvm::StructType *CatchableTypeType;
811
  llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
812
  llvm::StructType *ThrowInfoType;
813
};
814
815
}
816
817
CGCXXABI::RecordArgABI
818
898
MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
819
  // Use the default C calling convention rules for things that can be passed in
820
  // registers, i.e. non-trivially copyable records or records marked with
821
  // [[trivial_abi]].
822
898
  if (RD->canPassInRegisters())
823
557
    return RAA_Default;
824
825
341
  switch (CGM.getTarget().getTriple().getArch()) {
826
1
  default:
827
    // FIXME: Implement for other architectures.
828
1
    return RAA_Indirect;
829
830
21
  case llvm::Triple::thumb:
831
    // Pass things indirectly for now because it is simple.
832
    // FIXME: This is incompatible with MSVC for arguments with a dtor and no
833
    // copy ctor.
834
21
    return RAA_Indirect;
835
836
175
  case llvm::Triple::x86: {
837
    // If the argument has *required* alignment greater than four bytes, pass
838
    // it indirectly. Prior to MSVC version 19.14, passing overaligned
839
    // arguments was not supported and resulted in a compiler error. In 19.14
840
    // and later versions, such arguments are now passed indirectly.
841
175
    TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
842
175
    if (Info.AlignIsRequired && 
Info.Align > 45
)
843
5
      return RAA_Indirect;
844
845
    // If C++ prohibits us from making a copy, construct the arguments directly
846
    // into argument memory.
847
170
    return RAA_DirectInMemory;
848
170
  }
849
850
144
  case llvm::Triple::x86_64:
851
144
  case llvm::Triple::aarch64:
852
144
    return RAA_Indirect;
853
0
  }
854
855
0
  llvm_unreachable("invalid enum");
856
0
}
857
858
void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
859
                                              const CXXDeleteExpr *DE,
860
                                              Address Ptr,
861
                                              QualType ElementType,
862
45
                                              const CXXDestructorDecl *Dtor) {
863
  // FIXME: Provide a source location here even though there's no
864
  // CXXMemberCallExpr for dtor call.
865
45
  bool UseGlobalDelete = DE->isGlobalDelete();
866
43
  CXXDtorType DtorType = UseGlobalDelete ? 
Dtor_Complete2
: Dtor_Deleting;
867
45
  llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
868
45
  if (UseGlobalDelete)
869
2
    CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
870
45
}
871
872
3
void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
873
3
  llvm::Value *Args[] = {
874
3
      llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
875
3
      llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
876
3
  llvm::FunctionCallee Fn = getThrowFn();
877
3
  if (isNoReturn)
878
3
    CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
879
0
  else
880
0
    CGF.EmitRuntimeCallOrInvoke(Fn, Args);
881
3
}
882
883
void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
884
26
                                     const CXXCatchStmt *S) {
885
  // In the MS ABI, the runtime handles the copy, and the catch handler is
886
  // responsible for destruction.
887
26
  VarDecl *CatchParam = S->getExceptionDecl();
888
26
  llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
889
26
  llvm::CatchPadInst *CPI =
890
26
      cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
891
26
  CGF.CurrentFuncletPad = CPI;
892
893
  // If this is a catch-all or the catch parameter is unnamed, we don't need to
894
  // emit an alloca to the object.
895
26
  if (!CatchParam || 
!CatchParam->getDeclName()15
) {
896
21
    CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
897
21
    return;
898
21
  }
899
900
5
  CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
901
5
  CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
902
5
  CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
903
5
  CGF.EmitAutoVarCleanups(var);
904
5
}
905
906
/// We need to perform a generic polymorphic operation (like a typeid
907
/// or a cast), which requires an object with a vfptr.  Adjust the
908
/// address to point to an object with a vfptr.
909
std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
910
MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
911
21
                                       QualType SrcRecordTy) {
912
21
  Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
913
21
  const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
914
21
  const ASTContext &Context = getContext();
915
916
  // If the class itself has a vfptr, great.  This check implicitly
917
  // covers non-virtual base subobjects: a class with its own virtual
918
  // functions would be a candidate to be a primary base.
919
21
  if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
920
8
    return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
921
8
                           SrcDecl);
922
923
  // Okay, one of the vbases must have a vfptr, or else this isn't
924
  // actually a polymorphic class.
925
13
  const CXXRecordDecl *PolymorphicBase = nullptr;
926
13
  for (auto &Base : SrcDecl->vbases()) {
927
13
    const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
928
13
    if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
929
13
      PolymorphicBase = BaseDecl;
930
13
      break;
931
13
    }
932
13
  }
933
13
  assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
934
935
13
  llvm::Value *Offset =
936
13
    GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
937
13
  llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset);
938
13
  CharUnits VBaseAlign =
939
13
    CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
940
13
  return std::make_tuple(Address(Ptr, VBaseAlign), Offset, PolymorphicBase);
941
13
}
942
943
bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
944
3
                                                QualType SrcRecordTy) {
945
3
  const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
946
3
  return IsDeref &&
947
2
         !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
948
3
}
949
950
static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
951
4
                                        llvm::Value *Argument) {
952
4
  llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
953
4
  llvm::FunctionType *FTy =
954
4
      llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
955
4
  llvm::Value *Args[] = {Argument};
956
4
  llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
957
4
  return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
958
4
}
959
960
1
void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
961
1
  llvm::CallBase *Call =
962
1
      emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
963
1
  Call->setDoesNotReturn();
964
1
  CGF.Builder.CreateUnreachable();
965
1
}
966
967
llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
968
                                         QualType SrcRecordTy,
969
                                         Address ThisPtr,
970
3
                                         llvm::Type *StdTypeInfoPtrTy) {
971
3
  std::tie(ThisPtr, std::ignore, std::ignore) =
972
3
      performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
973
3
  llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
974
3
  return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
975
3
}
976
977
bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
978
16
                                                         QualType SrcRecordTy) {
979
16
  const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
980
16
  return SrcIsPtr &&
981
12
         !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
982
16
}
983
984
llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
985
    CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
986
13
    QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
987
13
  llvm::Type *DestLTy = CGF.ConvertType(DestTy);
988
989
13
  llvm::Value *SrcRTTI =
990
13
      CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
991
13
  llvm::Value *DestRTTI =
992
13
      CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
993
994
13
  llvm::Value *Offset;
995
13
  std::tie(This, Offset, std::ignore) =
996
13
      performBaseAdjustment(CGF, This, SrcRecordTy);
997
13
  llvm::Value *ThisPtr = This.getPointer();
998
13
  Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
999
1000
  // PVOID __RTDynamicCast(
1001
  //   PVOID inptr,
1002
  //   LONG VfDelta,
1003
  //   PVOID SrcType,
1004
  //   PVOID TargetType,
1005
  //   BOOL isReference)
1006
13
  llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1007
13
                            CGF.Int8PtrTy, CGF.Int32Ty};
1008
13
  llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1009
13
      llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1010
13
      "__RTDynamicCast");
1011
13
  llvm::Value *Args[] = {
1012
13
      ThisPtr, Offset, SrcRTTI, DestRTTI,
1013
13
      llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1014
13
  ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
1015
13
  return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1016
13
}
1017
1018
llvm::Value *
1019
MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1020
                                       QualType SrcRecordTy,
1021
3
                                       QualType DestTy) {
1022
3
  std::tie(Value, std::ignore, std::ignore) =
1023
3
      performBaseAdjustment(CGF, Value, SrcRecordTy);
1024
1025
  // PVOID __RTCastToVoid(
1026
  //   PVOID inptr)
1027
3
  llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1028
3
  llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1029
3
      llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1030
3
      "__RTCastToVoid");
1031
3
  llvm::Value *Args[] = {Value.getPointer()};
1032
3
  return CGF.EmitRuntimeCall(Function, Args);
1033
3
}
1034
1035
0
bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1036
0
  return false;
1037
0
}
1038
1039
llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1040
    CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1041
488
    const CXXRecordDecl *BaseClassDecl) {
1042
488
  const ASTContext &Context = getContext();
1043
488
  int64_t VBPtrChars =
1044
488
      Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1045
488
  llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1046
488
  CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1047
488
  CharUnits VBTableChars =
1048
488
      IntSize *
1049
488
      CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1050
488
  llvm::Value *VBTableOffset =
1051
488
      llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1052
1053
488
  llvm::Value *VBPtrToNewBase =
1054
488
      GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1055
488
  VBPtrToNewBase =
1056
488
      CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1057
488
  return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1058
488
}
1059
1060
34.1k
bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1061
34.1k
  return isa<CXXConstructorDecl>(GD.getDecl());
1062
34.1k
}
1063
1064
14.6k
static bool isDeletingDtor(GlobalDecl GD) {
1065
14.6k
  return isa<CXXDestructorDecl>(GD.getDecl()) &&
1066
7.45k
         GD.getDtorType() == Dtor_Deleting;
1067
14.6k
}
1068
1069
9.56k
bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1070
9.56k
  return isDeletingDtor(GD);
1071
9.56k
}
1072
1073
36
static bool isCXX14Aggregate(const CXXRecordDecl *RD) {
1074
  // For AArch64, we use the C++14 definition of an aggregate, so we also
1075
  // check for:
1076
  //   No private or protected non static data members.
1077
  //   No base classes
1078
  //   No virtual functions
1079
  // Additionally, we need to ensure that there is a trivial copy assignment
1080
  // operator, a trivial destructor and no user-provided constructors.
1081
36
  if (RD->hasProtectedFields() || RD->hasPrivateFields())
1082
1
    return false;
1083
35
  if (RD->getNumBases() > 0)
1084
3
    return false;
1085
32
  if (RD->isPolymorphic())
1086
0
    return false;
1087
32
  if (RD->hasNonTrivialCopyAssignment())
1088
2
    return false;
1089
30
  for (const CXXConstructorDecl *Ctor : RD->ctors())
1090
75
    if (Ctor->isUserProvided())
1091
6
      return false;
1092
24
  if (RD->hasNonTrivialDestructor())
1093
4
    return false;
1094
20
  return true;
1095
20
}
1096
1097
7.91k
bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1098
7.91k
  const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1099
7.91k
  if (!RD)
1100
7.73k
    return false;
1101
1102
  // Normally, the C++ concept of "is trivially copyable" is used to determine
1103
  // if a struct can be returned directly. However, as MSVC and the language
1104
  // have evolved, the definition of "trivially copyable" has changed, while the
1105
  // ABI must remain stable. AArch64 uses the C++14 concept of an "aggregate",
1106
  // while other ISAs use the older concept of "plain old data".
1107
184
  bool isTrivialForABI = RD->isPOD();
1108
184
  bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
1109
184
  if (isAArch64)
1110
40
    isTrivialForABI = RD->canPassInRegisters() && 
isCXX14Aggregate(RD)36
;
1111
1112
  // MSVC always returns structs indirectly from C++ instance methods.
1113
184
  bool isIndirectReturn = !isTrivialForABI || 
FI.isInstanceMethod()93
;
1114
1115
184
  if (isIndirectReturn) {
1116
121
    CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1117
121
    FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1118
1119
    // MSVC always passes `this` before the `sret` parameter.
1120
121
    FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1121
1122
    // On AArch64, use the `inreg` attribute if the object is considered to not
1123
    // be trivially copyable, or if this is an instance method struct return.
1124
121
    FI.getReturnInfo().setInReg(isAArch64);
1125
1126
121
    return true;
1127
121
  }
1128
1129
  // Otherwise, use the C ABI rules.
1130
63
  return false;
1131
63
}
1132
1133
llvm::BasicBlock *
1134
MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1135
381
                                               const CXXRecordDecl *RD) {
1136
381
  llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1137
381
  assert(IsMostDerivedClass &&
1138
381
         "ctor for a class with virtual bases must have an implicit parameter");
1139
381
  llvm::Value *IsCompleteObject =
1140
381
    CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1141
1142
381
  llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1143
381
  llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1144
381
  CGF.Builder.CreateCondBr(IsCompleteObject,
1145
381
                           CallVbaseCtorsBB, SkipVbaseCtorsBB);
1146
1147
381
  CGF.EmitBlock(CallVbaseCtorsBB);
1148
1149
  // Fill in the vbtable pointers here.
1150
381
  EmitVBPtrStores(CGF, RD);
1151
1152
  // CGF will put the base ctor calls in this basic block for us later.
1153
1154
381
  return SkipVbaseCtorsBB;
1155
381
}
1156
1157
llvm::BasicBlock *
1158
7
MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1159
7
  llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1160
7
  assert(IsMostDerivedClass &&
1161
7
         "ctor for a class with virtual bases must have an implicit parameter");
1162
7
  llvm::Value *IsCompleteObject =
1163
7
      CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1164
1165
7
  llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1166
7
  llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1167
7
  CGF.Builder.CreateCondBr(IsCompleteObject,
1168
7
                           CallVbaseDtorsBB, SkipVbaseDtorsBB);
1169
1170
7
  CGF.EmitBlock(CallVbaseDtorsBB);
1171
  // CGF will put the base dtor calls in this basic block for us later.
1172
1173
7
  return SkipVbaseDtorsBB;
1174
7
}
1175
1176
void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1177
401
    CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1178
  // In most cases, an override for a vbase virtual method can adjust
1179
  // the "this" parameter by applying a constant offset.
1180
  // However, this is not enough while a constructor or a destructor of some
1181
  // class X is being executed if all the following conditions are met:
1182
  //  - X has virtual bases, (1)
1183
  //  - X overrides a virtual method M of a vbase Y, (2)
1184
  //  - X itself is a vbase of the most derived class.
1185
  //
1186
  // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1187
  // which holds the extra amount of "this" adjustment we must do when we use
1188
  // the X vftables (i.e. during X ctor or dtor).
1189
  // Outside the ctors and dtors, the values of vtorDisps are zero.
1190
1191
401
  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1192
401
  typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1193
401
  const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1194
401
  CGBuilderTy &Builder = CGF.Builder;
1195
1196
401
  unsigned AS = getThisAddress(CGF).getAddressSpace();
1197
401
  llvm::Value *Int8This = nullptr;  // Initialize lazily.
1198
1199
573
  for (const CXXBaseSpecifier &S : RD->vbases()) {
1200
573
    const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1201
573
    auto I = VBaseMap.find(VBase);
1202
573
    assert(I != VBaseMap.end());
1203
573
    if (!I->second.hasVtorDisp())
1204
501
      continue;
1205
1206
72
    llvm::Value *VBaseOffset =
1207
72
        GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1208
72
    uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1209
1210
    // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1211
72
    llvm::Value *VtorDispValue = Builder.CreateSub(
1212
72
        VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1213
72
        "vtordisp.value");
1214
72
    VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1215
1216
72
    if (!Int8This)
1217
68
      Int8This = Builder.CreateBitCast(getThisValue(CGF),
1218
68
                                       CGF.Int8Ty->getPointerTo(AS));
1219
72
    llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1220
    // vtorDisp is always the 32-bits before the vbase in the class layout.
1221
72
    VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1222
72
    VtorDispPtr = Builder.CreateBitCast(
1223
72
        VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1224
1225
72
    Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1226
72
                               CharUnits::fromQuantity(4));
1227
72
  }
1228
401
}
1229
1230
static bool hasDefaultCXXMethodCC(ASTContext &Context,
1231
203
                                  const CXXMethodDecl *MD) {
1232
203
  CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1233
203
      /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1234
203
  CallingConv ActualCallingConv =
1235
203
      MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1236
203
  return ExpectedCallingConv == ActualCallingConv;
1237
203
}
1238
1239
749
void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1240
  // There's only one constructor type in this ABI.
1241
749
  CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1242
1243
  // Exported default constructors either have a simple call-site where they use
1244
  // the typical calling convention and have a single 'this' pointer for an
1245
  // argument -or- they get a wrapper function which appropriately thunks to the
1246
  // real default constructor.  This thunk is the default constructor closure.
1247
749
  if (D->hasAttr<DLLExportAttr>() && 
D->isDefaultConstructor()289
&&
1248
174
      D->isDefined()) {
1249
173
    if (!hasDefaultCXXMethodCC(getContext(), D) || 
D->getNumParams() != 0170
) {
1250
29
      llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1251
29
      Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1252
29
      CGM.setGVProperties(Fn, D);
1253
29
    }
1254
173
  }
1255
749
}
1256
1257
void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1258
381
                                      const CXXRecordDecl *RD) {
1259
381
  Address This = getThisAddress(CGF);
1260
381
  This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1261
381
  const ASTContext &Context = getContext();
1262
381
  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1263
1264
381
  const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1265
975
  for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; 
++I594
) {
1266
594
    const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1267
594
    llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1268
594
    const ASTRecordLayout &SubobjectLayout =
1269
594
        Context.getASTRecordLayout(VBT->IntroducingObject);
1270
594
    CharUnits Offs = VBT->NonVirtualOffset;
1271
594
    Offs += SubobjectLayout.getVBPtrOffset();
1272
594
    if (VBT->getVBaseWithVPtr())
1273
147
      Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1274
594
    Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1275
594
    llvm::Value *GVPtr =
1276
594
        CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1277
594
    VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1278
594
                                      "vbptr." + VBT->ObjectWithVPtr->getName());
1279
594
    CGF.Builder.CreateStore(GVPtr, VBPtr);
1280
594
  }
1281
381
}
1282
1283
CGCXXABI::AddedStructorArgCounts
1284
MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1285
10.3k
                                        SmallVectorImpl<CanQualType> &ArgTys) {
1286
10.3k
  AddedStructorArgCounts Added;
1287
  // TODO: 'for base' flag
1288
10.3k
  if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1289
4.74k
      GD.getDtorType() == Dtor_Deleting) {
1290
    // The scalar deleting destructor takes an implicit int parameter.
1291
1.42k
    ArgTys.push_back(getContext().IntTy);
1292
1.42k
    ++Added.Suffix;
1293
1.42k
  }
1294
10.3k
  auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1295
10.3k
  if (!CD)
1296
4.74k
    return Added;
1297
1298
  // All parameters are already in place except is_most_derived, which goes
1299
  // after 'this' if it's variadic and last if it's not.
1300
1301
5.61k
  const CXXRecordDecl *Class = CD->getParent();
1302
5.61k
  const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1303
5.61k
  if (Class->getNumVBases()) {
1304
1.54k
    if (FPT->isVariadic()) {
1305
6
      ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1306
6
      ++Added.Prefix;
1307
1.54k
    } else {
1308
1.54k
      ArgTys.push_back(getContext().IntTy);
1309
1.54k
      ++Added.Suffix;
1310
1.54k
    }
1311
1.54k
  }
1312
1313
5.61k
  return Added;
1314
5.61k
}
1315
1316
void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1317
                                                 const CXXDestructorDecl *Dtor,
1318
660
                                                 CXXDtorType DT) const {
1319
  // Deleting destructor variants are never imported or exported. Give them the
1320
  // default storage class.
1321
660
  if (DT == Dtor_Deleting) {
1322
308
    GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1323
352
  } else {
1324
352
    const NamedDecl *ND = Dtor;
1325
352
    CGM.setDLLImportDLLExport(GV, ND);
1326
352
  }
1327
660
}
1328
1329
llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1330
1.26k
    GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1331
  // Internal things are always internal, regardless of attributes. After this,
1332
  // we know the thunk is externally visible.
1333
1.26k
  if (Linkage == GVA_Internal)
1334
24
    return llvm::GlobalValue::InternalLinkage;
1335
1336
1.24k
  switch (DT) {
1337
538
  case Dtor_Base:
1338
    // The base destructor most closely tracks the user-declared constructor, so
1339
    // we delegate back to the normal declarator case.
1340
538
    return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1341
538
                                           /*IsConstantVariable=*/false);
1342
192
  case Dtor_Complete:
1343
    // The complete destructor is like an inline function, but it may be
1344
    // imported and therefore must be exported as well. This requires changing
1345
    // the linkage if a DLL attribute is present.
1346
192
    if (Dtor->hasAttr<DLLExportAttr>())
1347
2
      return llvm::GlobalValue::WeakODRLinkage;
1348
190
    if (Dtor->hasAttr<DLLImportAttr>())
1349
2
      return llvm::GlobalValue::AvailableExternallyLinkage;
1350
188
    return llvm::GlobalValue::LinkOnceODRLinkage;
1351
512
  case Dtor_Deleting:
1352
    // Deleting destructors are like inline functions. They have vague linkage
1353
    // and are emitted everywhere they are used. They are internal if the class
1354
    // is internal.
1355
512
    return llvm::GlobalValue::LinkOnceODRLinkage;
1356
0
  case Dtor_Comdat:
1357
0
    llvm_unreachable("MS C++ ABI does not support comdat dtors");
1358
0
  }
1359
0
  llvm_unreachable("invalid dtor type");
1360
0
}
1361
1362
194
void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1363
  // The TU defining a dtor is only guaranteed to emit a base destructor.  All
1364
  // other destructor variants are delegating thunks.
1365
194
  CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1366
1367
  // If the class is dllexported, emit the complete (vbase) destructor wherever
1368
  // the base dtor is emitted.
1369
  // FIXME: To match MSVC, this should only be done when the class is exported
1370
  // with -fdllexport-inlines enabled.
1371
194
  if (D->getParent()->getNumVBases() > 0 && 
D->hasAttr<DLLExportAttr>()23
)
1372
1
    CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1373
194
}
1374
1375
CharUnits
1376
1.25k
MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1377
1.25k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1378
1379
1.25k
  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1380
    // Complete destructors take a pointer to the complete object as a
1381
    // parameter, thus don't need this adjustment.
1382
967
    if (GD.getDtorType() == Dtor_Complete)
1383
157
      return CharUnits();
1384
1385
    // There's no Dtor_Base in vftable but it shares the this adjustment with
1386
    // the deleting one, so look it up instead.
1387
810
    GD = GlobalDecl(DD, Dtor_Deleting);
1388
810
  }
1389
1390
1.10k
  MethodVFTableLocation ML =
1391
1.10k
      CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1392
1.10k
  CharUnits Adjustment = ML.VFPtrOffset;
1393
1394
  // Normal virtual instance methods need to adjust from the vfptr that first
1395
  // defined the virtual method to the virtual base subobject, but destructors
1396
  // do not.  The vector deleting destructor thunk applies this adjustment for
1397
  // us if necessary.
1398
1.10k
  if (isa<CXXDestructorDecl>(MD))
1399
810
    Adjustment = CharUnits::Zero();
1400
1401
1.10k
  if (ML.VBase) {
1402
249
    const ASTRecordLayout &DerivedLayout =
1403
249
        getContext().getASTRecordLayout(MD->getParent());
1404
249
    Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1405
249
  }
1406
1407
1.10k
  return Adjustment;
1408
1.25k
}
1409
1410
Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1411
    CodeGenFunction &CGF, GlobalDecl GD, Address This,
1412
952
    bool VirtualCall) {
1413
952
  if (!VirtualCall) {
1414
    // If the call of a virtual function is not virtual, we just have to
1415
    // compensate for the adjustment the virtual function does in its prologue.
1416
576
    CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1417
576
    if (Adjustment.isZero())
1418
453
      return This;
1419
1420
123
    This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1421
123
    assert(Adjustment.isPositive());
1422
123
    return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1423
123
  }
1424
1425
376
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1426
1427
376
  GlobalDecl LookupGD = GD;
1428
376
  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1429
    // Complete dtors take a pointer to the complete object,
1430
    // thus don't need adjustment.
1431
98
    if (GD.getDtorType() == Dtor_Complete)
1432
0
      return This;
1433
1434
    // There's only Dtor_Deleting in vftable but it shares the this adjustment
1435
    // with the base one, so look up the deleting one instead.
1436
98
    LookupGD = GlobalDecl(DD, Dtor_Deleting);
1437
98
  }
1438
376
  MethodVFTableLocation ML =
1439
376
      CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1440
1441
376
  CharUnits StaticOffset = ML.VFPtrOffset;
1442
1443
  // Base destructors expect 'this' to point to the beginning of the base
1444
  // subobject, not the first vfptr that happens to contain the virtual dtor.
1445
  // However, we still need to apply the virtual base adjustment.
1446
376
  if (isa<CXXDestructorDecl>(MD) && 
GD.getDtorType() == Dtor_Base98
)
1447
0
    StaticOffset = CharUnits::Zero();
1448
1449
376
  Address Result = This;
1450
376
  if (ML.VBase) {
1451
92
    Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1452
1453
92
    const CXXRecordDecl *Derived = MD->getParent();
1454
92
    const CXXRecordDecl *VBase = ML.VBase;
1455
92
    llvm::Value *VBaseOffset =
1456
92
      GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1457
92
    llvm::Value *VBasePtr =
1458
92
      CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset);
1459
92
    CharUnits VBaseAlign =
1460
92
      CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1461
92
    Result = Address(VBasePtr, VBaseAlign);
1462
92
  }
1463
376
  if (!StaticOffset.isZero()) {
1464
66
    assert(StaticOffset.isPositive());
1465
66
    Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1466
66
    if (ML.VBase) {
1467
      // Non-virtual adjustment might result in a pointer outside the allocated
1468
      // object, e.g. if the final overrider class is laid out after the virtual
1469
      // base that declares a method in the most derived class.
1470
      // FIXME: Update the code that emits this adjustment in thunks prologues.
1471
12
      Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1472
54
    } else {
1473
54
      Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1474
54
    }
1475
66
  }
1476
376
  return Result;
1477
376
}
1478
1479
void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1480
                                                QualType &ResTy,
1481
1.92k
                                                FunctionArgList &Params) {
1482
1.92k
  ASTContext &Context = getContext();
1483
1.92k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1484
1.92k
  assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1485
1.92k
  if (isa<CXXConstructorDecl>(MD) && 
MD->getParent()->getNumVBases()1.26k
) {
1486
391
    auto *IsMostDerived = ImplicitParamDecl::Create(
1487
391
        Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1488
391
        &Context.Idents.get("is_most_derived"), Context.IntTy,
1489
391
        ImplicitParamDecl::Other);
1490
    // The 'most_derived' parameter goes second if the ctor is variadic and last
1491
    // if it's not.  Dtors can't be variadic.
1492
391
    const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1493
391
    if (FPT->isVariadic())
1494
8
      Params.insert(Params.begin() + 1, IsMostDerived);
1495
383
    else
1496
383
      Params.push_back(IsMostDerived);
1497
391
    getStructorImplicitParamDecl(CGF) = IsMostDerived;
1498
1.52k
  } else if (isDeletingDtor(CGF.CurGD)) {
1499
308
    auto *ShouldDelete = ImplicitParamDecl::Create(
1500
308
        Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1501
308
        &Context.Idents.get("should_call_delete"), Context.IntTy,
1502
308
        ImplicitParamDecl::Other);
1503
308
    Params.push_back(ShouldDelete);
1504
308
    getStructorImplicitParamDecl(CGF) = ShouldDelete;
1505
308
  }
1506
1.92k
}
1507
1508
3.55k
void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1509
  // Naked functions have no prolog.
1510
3.55k
  if (CGF.CurFuncDecl && 
CGF.CurFuncDecl->hasAttr<NakedAttr>()3.26k
)
1511
1
    return;
1512
1513
  // Overridden virtual methods of non-primary bases need to adjust the incoming
1514
  // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1515
  // sizeof(void*) to adjust from B* to C*:
1516
  //   struct A { virtual void a(); };
1517
  //   struct B { virtual void b(); };
1518
  //   struct C : A, B { virtual void b(); };
1519
  //
1520
  // Leave the value stored in the 'this' alloca unadjusted, so that the
1521
  // debugger sees the unadjusted value. Microsoft debuggers require this, and
1522
  // will apply the ThisAdjustment in the method type information.
1523
  // FIXME: Do something better for DWARF debuggers, which won't expect this,
1524
  // without making our codegen depend on debug info settings.
1525
3.55k
  llvm::Value *This = loadIncomingCXXThis(CGF);
1526
3.55k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1527
3.55k
  if (!CGF.CurFuncIsThunk && 
MD->isVirtual()3.28k
) {
1528
650
    CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1529
650
    if (!Adjustment.isZero()) {
1530
142
      unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1531
142
      llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1532
142
                 *thisTy = This->getType();
1533
142
      This = CGF.Builder.CreateBitCast(This, charPtrTy);
1534
142
      assert(Adjustment.isPositive());
1535
142
      This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1536
142
                                                    -Adjustment.getQuantity());
1537
142
      This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1538
142
    }
1539
650
  }
1540
3.55k
  setCXXABIThisValue(CGF, This);
1541
1542
  // If this is a function that the ABI specifies returns 'this', initialize
1543
  // the return slot to 'this' at the start of the function.
1544
  //
1545
  // Unlike the setting of return types, this is done within the ABI
1546
  // implementation instead of by clients of CGCXXABI because:
1547
  // 1) getThisValue is currently protected
1548
  // 2) in theory, an ABI could implement 'this' returns some other way;
1549
  //    HasThisReturn only specifies a contract, not the implementation
1550
3.55k
  if (HasThisReturn(CGF.CurGD))
1551
1.26k
    CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1552
2.28k
  else if (hasMostDerivedReturn(CGF.CurGD))
1553
308
    CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1554
308
                            CGF.ReturnValue);
1555
1556
3.55k
  if (isa<CXXConstructorDecl>(MD) && 
MD->getParent()->getNumVBases()1.26k
) {
1557
391
    assert(getStructorImplicitParamDecl(CGF) &&
1558
391
           "no implicit parameter for a constructor with virtual bases?");
1559
391
    getStructorImplicitParamValue(CGF)
1560
391
      = CGF.Builder.CreateLoad(
1561
391
          CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1562
391
          "is_most_derived");
1563
391
  }
1564
1565
3.55k
  if (isDeletingDtor(CGF.CurGD)) {
1566
308
    assert(getStructorImplicitParamDecl(CGF) &&
1567
308
           "no implicit parameter for a deleting destructor?");
1568
308
    getStructorImplicitParamValue(CGF)
1569
308
      = CGF.Builder.CreateLoad(
1570
308
          CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1571
308
          "should_call_delete");
1572
308
  }
1573
3.55k
}
1574
1575
CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1576
    CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1577
2.00k
    bool ForVirtualBase, bool Delegating) {
1578
2.00k
  assert(Type == Ctor_Complete || Type == Ctor_Base);
1579
1580
  // Check if we need a 'most_derived' parameter.
1581
2.00k
  if (!D->getParent()->getNumVBases())
1582
1.52k
    return AddedStructorArgs{};
1583
1584
  // Add the 'most_derived' argument second if we are variadic or last if not.
1585
480
  const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1586
480
  llvm::Value *MostDerivedArg;
1587
480
  if (Delegating) {
1588
2
    MostDerivedArg = getStructorImplicitParamValue(CGF);
1589
478
  } else {
1590
478
    MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1591
478
  }
1592
480
  if (FPT->isVariadic()) {
1593
8
    return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1594
8
  }
1595
472
  return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1596
472
}
1597
1598
llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1599
    CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1600
917
    bool ForVirtualBase, bool Delegating) {
1601
917
  return nullptr;
1602
917
}
1603
1604
void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1605
                                         const CXXDestructorDecl *DD,
1606
                                         CXXDtorType Type, bool ForVirtualBase,
1607
                                         bool Delegating, Address This,
1608
917
                                         QualType ThisTy) {
1609
  // Use the base destructor variant in place of the complete destructor variant
1610
  // if the class has no virtual bases. This effectively implements some of the
1611
  // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1612
917
  if (Type == Dtor_Complete && 
DD->getParent()->getNumVBases() == 0587
)
1613
502
    Type = Dtor_Base;
1614
1615
917
  GlobalDecl GD(DD, Type);
1616
917
  CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1617
1618
917
  if (DD->isVirtual()) {
1619
528
    assert(Type != CXXDtorType::Dtor_Deleting &&
1620
528
           "The deleting destructor should only be called via a virtual call");
1621
528
    This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1622
528
                                                    This, false);
1623
528
  }
1624
1625
917
  llvm::BasicBlock *BaseDtorEndBB = nullptr;
1626
917
  if (ForVirtualBase && 
isa<CXXConstructorDecl>(CGF.CurCodeDecl)110
) {
1627
7
    BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1628
7
  }
1629
1630
917
  llvm::Value *Implicit =
1631
917
      getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1632
917
                                    Delegating); // = nullptr
1633
917
  CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1634
917
                            /*ImplicitParam=*/Implicit,
1635
917
                            /*ImplicitParamTy=*/QualType(), nullptr);
1636
917
  if (BaseDtorEndBB) {
1637
    // Complete object handler should continue to be the remaining
1638
7
    CGF.Builder.CreateBr(BaseDtorEndBB);
1639
7
    CGF.EmitBlock(BaseDtorEndBB);
1640
7
  }
1641
917
}
1642
1643
void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1644
                                             const CXXRecordDecl *RD,
1645
808
                                             llvm::GlobalVariable *VTable) {
1646
808
  if (!CGM.getCodeGenOpts().LTOUnit)
1647
775
    return;
1648
1649
  // TODO: Should VirtualFunctionElimination also be supported here?
1650
  // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1651
33
  if (CGM.getCodeGenOpts().WholeProgramVTables) {
1652
21
    llvm::DenseSet<const CXXRecordDecl *> Visited;
1653
21
    llvm::GlobalObject::VCallVisibility TypeVis =
1654
21
        CGM.GetVCallVisibilityLevel(RD, Visited);
1655
21
    if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1656
20
      VTable->setVCallVisibilityMetadata(TypeVis);
1657
21
  }
1658
1659
  // The location of the first virtual function pointer in the virtual table,
1660
  // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1661
  // disabled, or sizeof(void*) if RTTI is enabled.
1662
33
  CharUnits AddressPoint =
1663
33
      getContext().getLangOpts().RTTIData
1664
32
          ? getContext().toCharUnitsFromBits(
1665
32
                getContext().getTargetInfo().getPointerWidth(0))
1666
1
          : CharUnits::Zero();
1667
1668
33
  if (Info.PathToIntroducingObject.empty()) {
1669
13
    CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1670
13
    return;
1671
13
  }
1672
1673
  // Add a bitset entry for the least derived base belonging to this vftable.
1674
20
  CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1675
20
                            Info.PathToIntroducingObject.back());
1676
1677
  // Add a bitset entry for each derived class that is laid out at the same
1678
  // offset as the least derived base.
1679
20
  for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; 
--I0
) {
1680
4
    const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1681
4
    const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1682
1683
4
    const ASTRecordLayout &Layout =
1684
4
        getContext().getASTRecordLayout(DerivedRD);
1685
4
    CharUnits Offset;
1686
4
    auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1687
4
    if (VBI == Layout.getVBaseOffsetsMap().end())
1688
0
      Offset = Layout.getBaseClassOffset(BaseRD);
1689
4
    else
1690
4
      Offset = VBI->second.VBaseOffset;
1691
4
    if (!Offset.isZero())
1692
4
      return;
1693
0
    CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1694
0
  }
1695
1696
  // Finally do the same for the most derived class.
1697
16
  if (Info.FullOffsetInMDC.isZero())
1698
9
    CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1699
16
}
1700
1701
void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1702
828
                                            const CXXRecordDecl *RD) {
1703
828
  MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1704
828
  const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1705
1706
838
  for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1707
838
    llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1708
838
    if (VTable->hasInitializer())
1709
30
      continue;
1710
1711
808
    const VTableLayout &VTLayout =
1712
808
      VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1713
1714
808
    llvm::Constant *RTTI = nullptr;
1715
808
    if (any_of(VTLayout.vtable_components(),
1716
1.14k
               [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1717
251
      RTTI = getMSCompleteObjectLocator(RD, *Info);
1718
1719
808
    ConstantInitBuilder builder(CGM);
1720
808
    auto components = builder.beginStruct();
1721
808
    CGVT.createVTableInitializer(components, VTLayout, RTTI,
1722
808
                                 VTable->hasLocalLinkage());
1723
808
    components.finishAndSetAsInitializer(VTable);
1724
1725
808
    emitVTableTypeMetadata(*Info, RD, VTable);
1726
808
  }
1727
828
}
1728
1729
bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1730
819
    CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1731
819
  return Vptr.NearestVBase != nullptr;
1732
819
}
1733
1734
llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1735
    CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1736
1.53k
    const CXXRecordDecl *NearestVBase) {
1737
1.53k
  llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1738
1.53k
  if (!VTableAddressPoint) {
1739
719
    assert(Base.getBase()->getNumVBases() &&
1740
719
           !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1741
719
  }
1742
1.53k
  return VTableAddressPoint;
1743
1.53k
}
1744
1745
static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1746
                              const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1747
1.62k
                              SmallString<256> &Name) {
1748
1.62k
  llvm::raw_svector_ostream Out(Name);
1749
1.62k
  MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1750
1.62k
}
1751
1752
llvm::Constant *
1753
MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1754
1.64k
                                       const CXXRecordDecl *VTableClass) {
1755
1.64k
  (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1756
1.64k
  VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1757
1.64k
  return VFTablesMap[ID];
1758
1.64k
}
1759
1760
llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1761
106
    BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1762
106
  llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1763
106
  assert(VFTable && "Couldn't find a vftable for the given base?");
1764
106
  return VFTable;
1765
106
}
1766
1767
llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1768
2.48k
                                                       CharUnits VPtrOffset) {
1769
  // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1770
  // shouldn't be used in the given record type. We want to cache this result in
1771
  // VFTablesMap, thus a simple zero check is not sufficient.
1772
1773
2.48k
  VFTableIdTy ID(RD, VPtrOffset);
1774
2.48k
  VTablesMapTy::iterator I;
1775
2.48k
  bool Inserted;
1776
2.48k
  std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1777
2.48k
  if (!Inserted)
1778
1.13k
    return I->second;
1779
1780
1.34k
  llvm::GlobalVariable *&VTable = I->second;
1781
1782
1.34k
  MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1783
1.34k
  const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1784
1785
1.34k
  if (DeferredVFTables.insert(RD).second) {
1786
    // We haven't processed this record type before.
1787
    // Queue up this vtable for possible deferred emission.
1788
802
    CGM.addDeferredVTable(RD);
1789
1790
802
#ifndef NDEBUG
1791
    // Create all the vftables at once in order to make sure each vftable has
1792
    // a unique mangled name.
1793
802
    llvm::StringSet<> ObservedMangledNames;
1794
1.61k
    for (size_t J = 0, F = VFPtrs.size(); J != F; 
++J810
) {
1795
810
      SmallString<256> Name;
1796
810
      mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1797
810
      if (!ObservedMangledNames.insert(Name.str()).second)
1798
0
        llvm_unreachable("Already saw this mangling before?");
1799
810
    }
1800
802
#endif
1801
802
  }
1802
1803
1.34k
  const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if(
1804
1.28k
      VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) {
1805
1.28k
        return VPI->FullOffsetInMDC == VPtrOffset;
1806
1.28k
      });
1807
1.34k
  if (VFPtrI == VFPtrs.end()) {
1808
533
    VFTablesMap[ID] = nullptr;
1809
533
    return nullptr;
1810
533
  }
1811
810
  const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1812
1813
810
  SmallString<256> VFTableName;
1814
810
  mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1815
1816
  // Classes marked __declspec(dllimport) need vftables generated on the
1817
  // import-side in order to support features like constexpr.  No other
1818
  // translation unit relies on the emission of the local vftable, translation
1819
  // units are expected to generate them as needed.
1820
  //
1821
  // Because of this unique behavior, we maintain this logic here instead of
1822
  // getVTableLinkage.
1823
810
  llvm::GlobalValue::LinkageTypes VFTableLinkage =
1824
23
      RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1825
787
                                   : CGM.getVTableLinkage(RD);
1826
810
  bool VFTableComesFromAnotherTU =
1827
810
      llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1828
810
      llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1829
810
  bool VTableAliasIsRequred =
1830
810
      !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1831
1832
810
  if (llvm::GlobalValue *VFTable =
1833
0
          CGM.getModule().getNamedGlobal(VFTableName)) {
1834
0
    VFTablesMap[ID] = VFTable;
1835
0
    VTable = VTableAliasIsRequred
1836
0
                 ? cast<llvm::GlobalVariable>(
1837
0
                       cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1838
0
                 : cast<llvm::GlobalVariable>(VFTable);
1839
0
    return VTable;
1840
0
  }
1841
1842
810
  const VTableLayout &VTLayout =
1843
810
      VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1844
810
  llvm::GlobalValue::LinkageTypes VTableLinkage =
1845
557
      VTableAliasIsRequred ? 
llvm::GlobalValue::PrivateLinkage253
: VFTableLinkage;
1846
1847
557
  StringRef VTableName = VTableAliasIsRequred ? 
StringRef()253
: VFTableName.str();
1848
1849
810
  llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1850
1851
  // Create a backing variable for the contents of VTable.  The VTable may
1852
  // or may not include space for a pointer to RTTI data.
1853
810
  llvm::GlobalValue *VFTable;
1854
810
  VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1855
810
                                    /*isConstant=*/true, VTableLinkage,
1856
810
                                    /*Initializer=*/nullptr, VTableName);
1857
810
  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1858
1859
810
  llvm::Comdat *C = nullptr;
1860
810
  if (!VFTableComesFromAnotherTU &&
1861
810
      (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1862
24
       (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1863
24
        VTableAliasIsRequred)))
1864
804
    C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1865
1866
  // Only insert a pointer into the VFTable for RTTI data if we are not
1867
  // importing it.  We never reference the RTTI data directly so there is no
1868
  // need to make room for it.
1869
810
  if (VTableAliasIsRequred) {
1870
253
    llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1871
253
                                 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1872
253
                                 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1873
    // Create a GEP which points just after the first entry in the VFTable,
1874
    // this should be the location of the first virtual method.
1875
253
    llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1876
253
        VTable->getValueType(), VTable, GEPIndices);
1877
253
    if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1878
235
      VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1879
235
      if (C)
1880
235
        C->setSelectionKind(llvm::Comdat::Largest);
1881
235
    }
1882
253
    VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1883
253
                                        /*AddressSpace=*/0, VFTableLinkage,
1884
253
                                        VFTableName.str(), VTableGEP,
1885
253
                                        &CGM.getModule());
1886
253
    VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1887
557
  } else {
1888
    // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1889
    // be referencing any RTTI data.
1890
    // The GlobalVariable will end up being an appropriate definition of the
1891
    // VFTable.
1892
557
    VFTable = VTable;
1893
557
  }
1894
810
  if (C)
1895
804
    VTable->setComdat(C);
1896
1897
810
  if (RD->hasAttr<DLLExportAttr>())
1898
58
    VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1899
1900
810
  VFTablesMap[ID] = VFTable;
1901
810
  return VTable;
1902
810
}
1903
1904
CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1905
                                                    GlobalDecl GD,
1906
                                                    Address This,
1907
                                                    llvm::Type *Ty,
1908
188
                                                    SourceLocation Loc) {
1909
188
  CGBuilderTy &Builder = CGF.Builder;
1910
1911
188
  Ty = Ty->getPointerTo()->getPointerTo();
1912
188
  Address VPtr =
1913
188
      adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1914
1915
188
  auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1916
188
  llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent());
1917
1918
188
  MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1919
188
  MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1920
1921
  // Compute the identity of the most derived class whose virtual table is
1922
  // located at the MethodVFTableLocation ML.
1923
46
  auto getObjectWithVPtr = [&] {
1924
46
    return llvm::find_if(VFTContext.getVFPtrOffsets(
1925
36
                             ML.VBase ? 
ML.VBase10
: MethodDecl->getParent()),
1926
50
                         [&](const std::unique_ptr<VPtrInfo> &Info) {
1927
50
                           return Info->FullOffsetInMDC == ML.VFPtrOffset;
1928
50
                         })
1929
46
        ->get()
1930
46
        ->ObjectWithVPtr;
1931
46
  };
1932
1933
188
  llvm::Value *VFunc;
1934
188
  if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1935
5
    VFunc = CGF.EmitVTableTypeCheckedLoad(
1936
5
        getObjectWithVPtr(), VTable,
1937
5
        ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1938
183
  } else {
1939
183
    if (CGM.getCodeGenOpts().PrepareForLTO)
1940
41
      CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1941
1942
183
    llvm::Value *VFuncPtr =
1943
183
        Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1944
183
    VFunc = Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1945
183
  }
1946
1947
188
  CGCallee Callee(GD, VFunc);
1948
188
  return Callee;
1949
188
}
1950
1951
llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1952
    CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1953
49
    Address This, DeleteOrMemberCallExpr E) {
1954
49
  auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1955
49
  auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1956
49
  assert((CE != nullptr) ^ (D != nullptr));
1957
49
  assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1958
49
  assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1959
1960
  // We have only one destructor in the vftable but can get both behaviors
1961
  // by passing an implicit int parameter.
1962
49
  GlobalDecl GD(Dtor, Dtor_Deleting);
1963
49
  const CGFunctionInfo *FInfo =
1964
49
      &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1965
49
  llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1966
49
  CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1967
1968
49
  ASTContext &Context = getContext();
1969
49
  llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1970
49
      llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1971
49
      DtorType == Dtor_Deleting);
1972
1973
49
  QualType ThisTy;
1974
49
  if (CE) {
1975
4
    ThisTy = CE->getObjectType();
1976
45
  } else {
1977
45
    ThisTy = D->getDestroyedType();
1978
45
  }
1979
1980
49
  This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1981
49
  RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1982
49
                                        ImplicitParam, Context.IntTy, CE);
1983
49
  return RV.getScalarVal();
1984
49
}
1985
1986
const VBTableGlobals &
1987
754
MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1988
  // At this layer, we can key the cache off of a single class, which is much
1989
  // easier than caching each vbtable individually.
1990
754
  llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1991
754
  bool Added;
1992
754
  std::tie(Entry, Added) =
1993
754
      VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1994
754
  VBTableGlobals &VBGlobals = Entry->second;
1995
754
  if (!Added)
1996
381
    return VBGlobals;
1997
1998
373
  MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1999
373
  VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2000
2001
  // Cache the globals for all vbtables so we don't have to recompute the
2002
  // mangled names.
2003
373
  llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2004
373
  for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2005
373
                                      E = VBGlobals.VBTables->end();
2006
959
       I != E; 
++I586
) {
2007
586
    VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2008
586
  }
2009
2010
373
  return VBGlobals;
2011
373
}
2012
2013
llvm::Function *
2014
MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2015
55
                                        const MethodVFTableLocation &ML) {
2016
55
  assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2017
55
         "can't form pointers to ctors or virtual dtors");
2018
2019
  // Calculate the mangled name.
2020
55
  SmallString<256> ThunkName;
2021
55
  llvm::raw_svector_ostream Out(ThunkName);
2022
55
  getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2023
2024
  // If the thunk has been generated previously, just return it.
2025
55
  if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2026
6
    return cast<llvm::Function>(GV);
2027
2028
  // Create the llvm::Function.
2029
49
  const CGFunctionInfo &FnInfo =
2030
49
      CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2031
49
  llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2032
49
  llvm::Function *ThunkFn =
2033
49
      llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2034
49
                             ThunkName.str(), &CGM.getModule());
2035
49
  assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2036
2037
49
  ThunkFn->setLinkage(MD->isExternallyVisible()
2038
47
                          ? llvm::GlobalValue::LinkOnceODRLinkage
2039
2
                          : llvm::GlobalValue::InternalLinkage);
2040
49
  if (MD->isExternallyVisible())
2041
47
    ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2042
2043
49
  CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
2044
49
  CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2045
2046
  // Add the "thunk" attribute so that LLVM knows that the return type is
2047
  // meaningless. These thunks can be used to call functions with differing
2048
  // return types, and the caller is required to cast the prototype
2049
  // appropriately to extract the correct value.
2050
49
  ThunkFn->addFnAttr("thunk");
2051
2052
  // These thunks can be compared, so they are not unnamed.
2053
49
  ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2054
2055
  // Start codegen.
2056
49
  CodeGenFunction CGF(CGM);
2057
49
  CGF.CurGD = GlobalDecl(MD);
2058
49
  CGF.CurFuncIsThunk = true;
2059
2060
  // Build FunctionArgs, but only include the implicit 'this' parameter
2061
  // declaration.
2062
49
  FunctionArgList FunctionArgs;
2063
49
  buildThisParam(CGF, FunctionArgs);
2064
2065
  // Start defining the function.
2066
49
  CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2067
49
                    FunctionArgs, MD->getLocation(), SourceLocation());
2068
49
  setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2069
2070
  // Load the vfptr and then callee from the vftable.  The callee should have
2071
  // adjusted 'this' so that the vfptr is at offset zero.
2072
49
  llvm::Value *VTable = CGF.GetVTablePtr(
2073
49
      getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
2074
2075
49
  llvm::Value *VFuncPtr =
2076
49
      CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
2077
49
  llvm::Value *Callee =
2078
49
    CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
2079
2080
49
  CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2081
2082
49
  return ThunkFn;
2083
49
}
2084
2085
369
void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2086
369
  const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2087
949
  for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; 
++I580
) {
2088
580
    const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2089
580
    llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2090
580
    if (GV->isDeclaration())
2091
0
      emitVBTableDefinition(*VBT, RD, GV);
2092
580
  }
2093
369
}
2094
2095
llvm::GlobalVariable *
2096
MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2097
586
                                  llvm::GlobalVariable::LinkageTypes Linkage) {
2098
586
  SmallString<256> OutName;
2099
586
  llvm::raw_svector_ostream Out(OutName);
2100
586
  getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2101
586
  StringRef Name = OutName.str();
2102
2103
586
  llvm::ArrayType *VBTableType =
2104
586
      llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2105
2106
586
  assert(!CGM.getModule().getNamedGlobal(Name) &&
2107
586
         "vbtable with this name already exists: mangling bug?");
2108
586
  CharUnits Alignment =
2109
586
      CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2110
586
  llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2111
586
      Name, VBTableType, Linkage, Alignment.getQuantity());
2112
586
  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2113
2114
586
  if (RD->hasAttr<DLLImportAttr>())
2115
5
    GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2116
581
  else if (RD->hasAttr<DLLExportAttr>())
2117
9
    GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2118
2119
586
  if (!GV->hasExternalLinkage())
2120
586
    emitVBTableDefinition(VBT, RD, GV);
2121
2122
586
  return GV;
2123
586
}
2124
2125
void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2126
                                            const CXXRecordDecl *RD,
2127
586
                                            llvm::GlobalVariable *GV) const {
2128
586
  const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2129
2130
586
  assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2131
586
         "should only emit vbtables for classes with vbtables");
2132
2133
586
  const ASTRecordLayout &BaseLayout =
2134
586
      getContext().getASTRecordLayout(VBT.IntroducingObject);
2135
586
  const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2136
2137
586
  SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2138
586
                                           nullptr);
2139
2140
  // The offset from ObjectWithVPtr's vbptr to itself always leads.
2141
586
  CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2142
586
  Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2143
2144
586
  MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2145
913
  for (const auto &I : ObjectWithVPtr->vbases()) {
2146
913
    const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2147
913
    CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2148
913
    assert(!Offset.isNegative());
2149
2150
    // Make it relative to the subobject vbptr.
2151
913
    CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2152
913
    if (VBT.getVBaseWithVPtr())
2153
289
      CompleteVBPtrOffset +=
2154
289
          DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2155
913
    Offset -= CompleteVBPtrOffset;
2156
2157
913
    unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2158
913
    assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2159
913
    Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2160
913
  }
2161
2162
586
  assert(Offsets.size() ==
2163
586
         cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2164
586
                               ->getElementType())->getNumElements());
2165
586
  llvm::ArrayType *VBTableType =
2166
586
    llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2167
586
  llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2168
586
  GV->setInitializer(Init);
2169
2170
586
  if (RD->hasAttr<DLLImportAttr>())
2171
5
    GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2172
586
}
2173
2174
llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2175
                                                    Address This,
2176
267
                                                    const ThisAdjustment &TA) {
2177
267
  if (TA.isEmpty())
2178
35
    return This.getPointer();
2179
2180
232
  This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2181
2182
232
  llvm::Value *V;
2183
232
  if (TA.Virtual.isEmpty()) {
2184
98
    V = This.getPointer();
2185
134
  } else {
2186
134
    assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2187
    // Adjust the this argument based on the vtordisp value.
2188
134
    Address VtorDispPtr =
2189
134
        CGF.Builder.CreateConstInBoundsByteGEP(This,
2190
134
                 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2191
134
    VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2192
134
    llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2193
134
    V = CGF.Builder.CreateGEP(This.getPointer(),
2194
134
                              CGF.Builder.CreateNeg(VtorDisp));
2195
2196
    // Unfortunately, having applied the vtordisp means that we no
2197
    // longer really have a known alignment for the vbptr step.
2198
    // We'll assume the vbptr is pointer-aligned.
2199
2200
134
    if (TA.Virtual.Microsoft.VBPtrOffset) {
2201
      // If the final overrider is defined in a virtual base other than the one
2202
      // that holds the vfptr, we have to use a vtordispex thunk which looks up
2203
      // the vbtable of the derived class.
2204
16
      assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2205
16
      assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2206
16
      llvm::Value *VBPtr;
2207
16
      llvm::Value *VBaseOffset =
2208
16
          GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2209
16
                                  -TA.Virtual.Microsoft.VBPtrOffset,
2210
16
                                  TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2211
16
      V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2212
16
    }
2213
134
  }
2214
2215
232
  if (TA.NonVirtual) {
2216
    // Non-virtual adjustment might result in a pointer outside the allocated
2217
    // object, e.g. if the final overrider class is laid out after the virtual
2218
    // base that declares a method in the most derived class.
2219
150
    V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2220
150
  }
2221
2222
  // Don't need to bitcast back, the call CodeGen will handle this.
2223
232
  return V;
2224
232
}
2225
2226
llvm::Value *
2227
MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2228
35
                                         const ReturnAdjustment &RA) {
2229
35
  if (RA.isEmpty())
2230
0
    return Ret.getPointer();
2231
2232
35
  auto OrigTy = Ret.getType();
2233
35
  Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2234
2235
35
  llvm::Value *V = Ret.getPointer();
2236
35
  if (RA.Virtual.Microsoft.VBIndex) {
2237
21
    assert(RA.Virtual.Microsoft.VBIndex > 0);
2238
21
    int32_t IntSize = CGF.getIntSize().getQuantity();
2239
21
    llvm::Value *VBPtr;
2240
21
    llvm::Value *VBaseOffset =
2241
21
        GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2242
21
                                IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2243
21
    V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2244
21
  }
2245
2246
35
  if (RA.NonVirtual)
2247
16
    V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2248
2249
  // Cast back to the original type.
2250
35
  return CGF.Builder.CreateBitCast(V, OrigTy);
2251
35
}
2252
2253
bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2254
14
                                   QualType elementType) {
2255
  // Microsoft seems to completely ignore the possibility of a
2256
  // two-argument usual deallocation function.
2257
14
  return elementType.isDestructedType();
2258
14
}
2259
2260
36
bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2261
  // Microsoft seems to completely ignore the possibility of a
2262
  // two-argument usual deallocation function.
2263
36
  return expr->getAllocatedType().isDestructedType();
2264
36
}
2265
2266
9
CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2267
  // The array cookie is always a size_t; we then pad that out to the
2268
  // alignment of the element type.
2269
9
  ASTContext &Ctx = getContext();
2270
9
  return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2271
9
                  Ctx.getTypeAlignInChars(type));
2272
9
}
2273
2274
llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2275
                                                  Address allocPtr,
2276
3
                                                  CharUnits cookieSize) {
2277
3
  Address numElementsPtr =
2278
3
    CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2279
3
  return CGF.Builder.CreateLoad(numElementsPtr);
2280
3
}
2281
2282
Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2283
                                               Address newPtr,
2284
                                               llvm::Value *numElements,
2285
                                               const CXXNewExpr *expr,
2286
2
                                               QualType elementType) {
2287
2
  assert(requiresArrayCookie(expr));
2288
2289
  // The size of the cookie.
2290
2
  CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2291
2292
  // Compute an offset to the cookie.
2293
2
  Address cookiePtr = newPtr;
2294
2295
  // Write the number of elements into the appropriate slot.
2296
2
  Address numElementsPtr
2297
2
    = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2298
2
  CGF.Builder.CreateStore(numElements, numElementsPtr);
2299
2300
  // Finally, compute a pointer to the actual data buffer by skipping
2301
  // over the cookie completely.
2302
2
  return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2303
2
}
2304
2305
static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2306
                                        llvm::FunctionCallee Dtor,
2307
10
                                        llvm::Constant *Addr) {
2308
  // Create a function which calls the destructor.
2309
10
  llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2310
2311
  // extern "C" int __tlregdtor(void (*f)(void));
2312
10
  llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2313
10
      CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2314
2315
10
  llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2316
10
      TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2317
10
  if (llvm::Function *TLRegDtorFn =
2318
10
          dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2319
10
    TLRegDtorFn->setDoesNotThrow();
2320
2321
10
  CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2322
10
}
2323
2324
void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2325
                                         llvm::FunctionCallee Dtor,
2326
170
                                         llvm::Constant *Addr) {
2327
170
  if (D.isNoDestroy(CGM.getContext()))
2328
0
    return;
2329
2330
170
  if (D.getTLSKind())
2331
10
    return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2332
2333
  // The default behavior is to use atexit.
2334
160
  CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2335
160
}
2336
2337
void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2338
    CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2339
    ArrayRef<llvm::Function *> CXXThreadLocalInits,
2340
712
    ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2341
712
  if (CXXThreadLocalInits.empty())
2342
708
    return;
2343
2344
4
  CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2345
4
                                  llvm::Triple::x86
2346
4
                              ? "/include:___dyn_tls_init@12"
2347
0
                              : "/include:__dyn_tls_init");
2348
2349
  // This will create a GV in the .CRT$XDU section.  It will point to our
2350
  // initialization function.  The CRT will call all of these function
2351
  // pointers at start-up time and, eventually, at thread-creation time.
2352
6
  auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2353
6
    llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2354
6
        CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2355
6
        llvm::GlobalVariable::InternalLinkage, InitFunc,
2356
6
        Twine(InitFunc->getName(), "$initializer$"));
2357
6
    InitFuncPtr->setSection(".CRT$XDU");
2358
    // This variable has discardable linkage, we have to add it to @llvm.used to
2359
    // ensure it won't get discarded.
2360
6
    CGM.addUsedGlobal(InitFuncPtr);
2361
6
    return InitFuncPtr;
2362
6
  };
2363
2364
4
  std::vector<llvm::Function *> NonComdatInits;
2365
14
  for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; 
++I10
) {
2366
10
    llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2367
10
        CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2368
10
    llvm::Function *F = CXXThreadLocalInits[I];
2369
2370
    // If the GV is already in a comdat group, then we have to join it.
2371
10
    if (llvm::Comdat *C = GV->getComdat())
2372
2
      AddToXDU(F)->setComdat(C);
2373
8
    else
2374
8
      NonComdatInits.push_back(F);
2375
10
  }
2376
2377
4
  if (!NonComdatInits.empty()) {
2378
4
    llvm::FunctionType *FTy =
2379
4
        llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2380
4
    llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2381
4
        FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2382
4
        SourceLocation(), /*TLS=*/true);
2383
4
    CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2384
2385
4
    AddToXDU(InitFunc);
2386
4
  }
2387
4
}
2388
2389
LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2390
                                                     const VarDecl *VD,
2391
0
                                                     QualType LValType) {
2392
0
  CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2393
0
  return LValue();
2394
0
}
2395
2396
37
static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2397
37
  StringRef VarName("_Init_thread_epoch");
2398
37
  CharUnits Align = CGM.getIntAlign();
2399
37
  if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2400
28
    return ConstantAddress(GV, Align);
2401
9
  auto *GV = new llvm::GlobalVariable(
2402
9
      CGM.getModule(), CGM.IntTy,
2403
9
      /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2404
9
      /*Initializer=*/nullptr, VarName,
2405
9
      /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2406
9
  GV->setAlignment(Align.getAsAlign());
2407
9
  return ConstantAddress(GV, Align);
2408
9
}
2409
2410
37
static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2411
37
  llvm::FunctionType *FTy =
2412
37
      llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2413
37
                              CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2414
37
  return CGM.CreateRuntimeFunction(
2415
37
      FTy, "_Init_thread_header",
2416
37
      llvm::AttributeList::get(CGM.getLLVMContext(),
2417
37
                               llvm::AttributeList::FunctionIndex,
2418
37
                               llvm::Attribute::NoUnwind),
2419
37
      /*Local=*/true);
2420
37
}
2421
2422
37
static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2423
37
  llvm::FunctionType *FTy =
2424
37
      llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2425
37
                              CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2426
37
  return CGM.CreateRuntimeFunction(
2427
37
      FTy, "_Init_thread_footer",
2428
37
      llvm::AttributeList::get(CGM.getLLVMContext(),
2429
37
                               llvm::AttributeList::FunctionIndex,
2430
37
                               llvm::Attribute::NoUnwind),
2431
37
      /*Local=*/true);
2432
37
}
2433
2434
5
static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2435
5
  llvm::FunctionType *FTy =
2436
5
      llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2437
5
                              CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2438
5
  return CGM.CreateRuntimeFunction(
2439
5
      FTy, "_Init_thread_abort",
2440
5
      llvm::AttributeList::get(CGM.getLLVMContext(),
2441
5
                               llvm::AttributeList::FunctionIndex,
2442
5
                               llvm::Attribute::NoUnwind),
2443
5
      /*Local=*/true);
2444
5
}
2445
2446
namespace {
2447
struct ResetGuardBit final : EHScopeStack::Cleanup {
2448
  Address Guard;
2449
  unsigned GuardNum;
2450
  ResetGuardBit(Address Guard, unsigned GuardNum)
2451
58
      : Guard(Guard), GuardNum(GuardNum) {}
2452
2453
2
  void Emit(CodeGenFunction &CGF, Flags flags) override {
2454
    // Reset the bit in the mask so that the static variable may be
2455
    // reinitialized.
2456
2
    CGBuilderTy &Builder = CGF.Builder;
2457
2
    llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2458
2
    llvm::ConstantInt *Mask =
2459
2
        llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2460
2
    Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2461
2
  }
2462
};
2463
2464
struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2465
  llvm::Value *Guard;
2466
37
  CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2467
2468
5
  void Emit(CodeGenFunction &CGF, Flags flags) override {
2469
    // Calling _Init_thread_abort will reset the guard's state.
2470
5
    CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2471
5
  }
2472
};
2473
}
2474
2475
void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2476
                                      llvm::GlobalVariable *GV,
2477
141
                                      bool PerformInit) {
2478
  // MSVC only uses guards for static locals.
2479
141
  if (!D.isStaticLocal()) {
2480
46
    assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2481
    // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2482
46
    llvm::Function *F = CGF.CurFn;
2483
46
    F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2484
46
    F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2485
46
    CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2486
46
    return;
2487
46
  }
2488
2489
95
  bool ThreadlocalStatic = D.getTLSKind();
2490
95
  bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2491
2492
  // Thread-safe static variables which aren't thread-specific have a
2493
  // per-variable guard.
2494
95
  bool HasPerVariableGuard = ThreadsafeStatic && 
!ThreadlocalStatic41
;
2495
2496
95
  CGBuilderTy &Builder = CGF.Builder;
2497
95
  llvm::IntegerType *GuardTy = CGF.Int32Ty;
2498
95
  llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2499
95
  CharUnits GuardAlign = CharUnits::fromQuantity(4);
2500
2501
  // Get the guard variable for this function if we have one already.
2502
95
  GuardInfo *GI = nullptr;
2503
95
  if (ThreadlocalStatic)
2504
4
    GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2505
91
  else if (!ThreadsafeStatic)
2506
54
    GI = &GuardVariableMap[D.getDeclContext()];
2507
2508
58
  llvm::GlobalVariable *GuardVar = GI ? GI->Guard : 
nullptr37
;
2509
95
  unsigned GuardNum;
2510
95
  if (D.isExternallyVisible()) {
2511
    // Externally visible variables have to be numbered in Sema to properly
2512
    // handle unreachable VarDecls.
2513
37
    GuardNum = getContext().getStaticLocalNumber(&D);
2514
37
    assert(GuardNum > 0);
2515
37
    GuardNum--;
2516
58
  } else if (HasPerVariableGuard) {
2517
11
    GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2518
47
  } else {
2519
    // Non-externally visible variables are numbered here in CodeGen.
2520
47
    GuardNum = GI->BitIndex++;
2521
47
  }
2522
2523
95
  if (!HasPerVariableGuard && 
GuardNum >= 3258
) {
2524
3
    if (D.isExternallyVisible())
2525
0
      ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2526
3
    GuardNum %= 32;
2527
3
    GuardVar = nullptr;
2528
3
  }
2529
2530
95
  if (!GuardVar) {
2531
    // Mangle the name for the guard.
2532
64
    SmallString<256> GuardName;
2533
64
    {
2534
64
      llvm::raw_svector_ostream Out(GuardName);
2535
64
      if (HasPerVariableGuard)
2536
37
        getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2537
37
                                                               Out);
2538
27
      else
2539
27
        getMangleContext().mangleStaticGuardVariable(&D, Out);
2540
64
    }
2541
2542
    // Create the guard variable with a zero-initializer. Just absorb linkage,
2543
    // visibility and dll storage class from the guarded variable.
2544
64
    GuardVar =
2545
64
        new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2546
64
                                 GV->getLinkage(), Zero, GuardName.str());
2547
64
    GuardVar->setVisibility(GV->getVisibility());
2548
64
    GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2549
64
    GuardVar->setAlignment(GuardAlign.getAsAlign());
2550
64
    if (GuardVar->isWeakForLinker())
2551
35
      GuardVar->setComdat(
2552
35
          CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2553
64
    if (D.getTLSKind())
2554
4
      CGM.setTLSMode(GuardVar, D);
2555
64
    if (GI && 
!HasPerVariableGuard27
)
2556
27
      GI->Guard = GuardVar;
2557
64
  }
2558
2559
95
  ConstantAddress GuardAddr(GuardVar, GuardAlign);
2560
2561
95
  assert(GuardVar->getLinkage() == GV->getLinkage() &&
2562
95
         "static local from the same function had different linkage");
2563
2564
95
  if (!HasPerVariableGuard) {
2565
    // Pseudo code for the test:
2566
    // if (!(GuardVar & MyGuardBit)) {
2567
    //   GuardVar |= MyGuardBit;
2568
    //   ... initialize the object ...;
2569
    // }
2570
2571
    // Test our bit from the guard variable.
2572
58
    llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2573
58
    llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2574
58
    llvm::Value *NeedsInit =
2575
58
        Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2576
58
    llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2577
58
    llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2578
58
    CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2579
58
                                 CodeGenFunction::GuardKind::VariableGuard, &D);
2580
2581
    // Set our bit in the guard variable and emit the initializer and add a global
2582
    // destructor if appropriate.
2583
58
    CGF.EmitBlock(InitBlock);
2584
58
    Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2585
58
    CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2586
58
    CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2587
58
    CGF.PopCleanupBlock();
2588
58
    Builder.CreateBr(EndBlock);
2589
2590
    // Continue.
2591
58
    CGF.EmitBlock(EndBlock);
2592
37
  } else {
2593
    // Pseudo code for the test:
2594
    // if (TSS > _Init_thread_epoch) {
2595
    //   _Init_thread_header(&TSS);
2596
    //   if (TSS == -1) {
2597
    //     ... initialize the object ...;
2598
    //     _Init_thread_footer(&TSS);
2599
    //   }
2600
    // }
2601
    //
2602
    // The algorithm is almost identical to what can be found in the appendix
2603
    // found in N2325.
2604
2605
    // This BasicBLock determines whether or not we have any work to do.
2606
37
    llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2607
37
    FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2608
37
    llvm::LoadInst *InitThreadEpoch =
2609
37
        Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2610
37
    llvm::Value *IsUninitialized =
2611
37
        Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2612
37
    llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2613
37
    llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2614
37
    CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2615
37
                                 CodeGenFunction::GuardKind::VariableGuard, &D);
2616
2617
    // This BasicBlock attempts to determine whether or not this thread is
2618
    // responsible for doing the initialization.
2619
37
    CGF.EmitBlock(AttemptInitBlock);
2620
37
    CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2621
37
                                GuardAddr.getPointer());
2622
37
    llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2623
37
    SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2624
37
    llvm::Value *ShouldDoInit =
2625
37
        Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2626
37
    llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2627
37
    Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2628
2629
    // Ok, we ended up getting selected as the initializing thread.
2630
37
    CGF.EmitBlock(InitBlock);
2631
37
    CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2632
37
    CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2633
37
    CGF.PopCleanupBlock();
2634
37
    CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2635
37
                                GuardAddr.getPointer());
2636
37
    Builder.CreateBr(EndBlock);
2637
2638
37
    CGF.EmitBlock(EndBlock);
2639
37
  }
2640
95
}
2641
2642
131
bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2643
  // Null-ness for function memptrs only depends on the first field, which is
2644
  // the function pointer.  The rest don't matter, so we can zero initialize.
2645
131
  if (MPT->isMemberFunctionPointer())
2646
60
    return true;
2647
2648
  // The virtual base adjustment field is always -1 for null, so if we have one
2649
  // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
2650
  // valid field offset.
2651
71
  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2652
71
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2653
71
  return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2654
33
          RD->nullFieldOffsetIsZero());
2655
71
}
2656
2657
llvm::Type *
2658
450
MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2659
450
  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2660
450
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2661
450
  llvm::SmallVector<llvm::Type *, 4> fields;
2662
450
  if (MPT->isMemberFunctionPointer())
2663
360
    fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
2664
90
  else
2665
90
    fields.push_back(CGM.IntTy);  // FieldOffset
2666
2667
450
  if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2668
450
                                       Inheritance))
2669
85
    fields.push_back(CGM.IntTy);
2670
450
  if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2671
111
    fields.push_back(CGM.IntTy);
2672
450
  if (inheritanceModelHasVBTableOffsetField(Inheritance))
2673
137
    fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
2674
2675
450
  if (fields.size() == 1)
2676
296
    return fields[0];
2677
154
  return llvm::StructType::get(CGM.getLLVMContext(), fields);
2678
154
}
2679
2680
void MicrosoftCXXABI::
2681
GetNullMemberPointerFields(const MemberPointerType *MPT,
2682
109
                           llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2683
109
  assert(fields.empty());
2684
109
  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2685
109
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2686
109
  if (MPT->isMemberFunctionPointer()) {
2687
    // FunctionPointerOrVirtualThunk
2688
17
    fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2689
92
  } else {
2690
92
    if (RD->nullFieldOffsetIsZero())
2691
50
      fields.push_back(getZeroInt());  // FieldOffset
2692
42
    else
2693
42
      fields.push_back(getAllOnesInt());  // FieldOffset
2694
92
  }
2695
2696
109
  if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2697
109
                                       Inheritance))
2698
9
    fields.push_back(getZeroInt());
2699
109
  if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2700
34
    fields.push_back(getZeroInt());
2701
109
  if (inheritanceModelHasVBTableOffsetField(Inheritance))
2702
42
    fields.push_back(getAllOnesInt());
2703
109
}
2704
2705
llvm::Constant *
2706
87
MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2707
87
  llvm::SmallVector<llvm::Constant *, 4> fields;
2708
87
  GetNullMemberPointerFields(MPT, fields);
2709
87
  if (fields.size() == 1)
2710
42
    return fields[0];
2711
45
  llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2712
45
  assert(Res->getType() == ConvertMemberPointerType(MPT));
2713
45
  return Res;
2714
45
}
2715
2716
llvm::Constant *
2717
MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2718
                                       bool IsMemberFunction,
2719
                                       const CXXRecordDecl *RD,
2720
                                       CharUnits NonVirtualBaseAdjustment,
2721
372
                                       unsigned VBTableIndex) {
2722
372
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2723
2724
  // Single inheritance class member pointer are represented as scalars instead
2725
  // of aggregates.
2726
372
  if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2727
315
    return FirstField;
2728
2729
57
  llvm::SmallVector<llvm::Constant *, 4> fields;
2730
57
  fields.push_back(FirstField);
2731
2732
57
  if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2733
53
    fields.push_back(llvm::ConstantInt::get(
2734
53
      CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2735
2736
57
  if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2737
26
    CharUnits Offs = CharUnits::Zero();
2738
26
    if (VBTableIndex)
2739
0
      Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2740
26
    fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2741
26
  }
2742
2743
  // The rest of the fields are adjusted by conversions to a more derived class.
2744
57
  if (inheritanceModelHasVBTableOffsetField(Inheritance))
2745
40
    fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2746
2747
57
  return llvm::ConstantStruct::getAnon(fields);
2748
57
}
2749
2750
llvm::Constant *
2751
MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2752
22
                                       CharUnits offset) {
2753
22
  return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2754
22
}
2755
2756
llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2757
35
                                                       CharUnits offset) {
2758
35
  if (RD->getMSInheritanceModel() ==
2759
35
      MSInheritanceModel::Virtual)
2760
2
    offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2761
35
  llvm::Constant *FirstField =
2762
35
    llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2763
35
  return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2764
35
                               CharUnits::Zero(), /*VBTableIndex=*/0);
2765
35
}
2766
2767
llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2768
43
                                                   QualType MPType) {
2769
43
  const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2770
43
  const ValueDecl *MPD = MP.getMemberPointerDecl();
2771
43
  if (!MPD)
2772
6
    return EmitNullMemberPointer(DstTy);
2773
2774
37
  ASTContext &Ctx = getContext();
2775
37
  ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2776
2777
37
  llvm::Constant *C;
2778
37
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2779
24
    C = EmitMemberFunctionPointer(MD);
2780
13
  } else {
2781
    // For a pointer to data member, start off with the offset of the field in
2782
    // the class in which it was declared, and convert from there if necessary.
2783
    // For indirect field decls, get the outermost anonymous field and use the
2784
    // parent class.
2785
13
    CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2786
13
    const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2787
13
    if (!FD)
2788
4
      FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2789
13
    const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2790
13
    RD = RD->getMostRecentNonInjectedDecl();
2791
13
    C = EmitMemberDataPointer(RD, FieldOffset);
2792
13
  }
2793
2794
37
  if (!MemberPointerPath.empty()) {
2795
14
    const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2796
14
    const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2797
14
    const MemberPointerType *SrcTy =
2798
14
        Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2799
14
            ->castAs<MemberPointerType>();
2800
2801
14
    bool DerivedMember = MP.isMemberPointerToDerivedMember();
2802
14
    SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2803
14
    const CXXRecordDecl *PrevRD = SrcRD;
2804
14
    for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2805
14
      const CXXRecordDecl *Base = nullptr;
2806
14
      const CXXRecordDecl *Derived = nullptr;
2807
14
      if (DerivedMember) {
2808
0
        Base = PathElem;
2809
0
        Derived = PrevRD;
2810
14
      } else {
2811
14
        Base = PrevRD;
2812
14
        Derived = PathElem;
2813
14
      }
2814
14
      for (const CXXBaseSpecifier &BS : Derived->bases())
2815
16
        if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2816
16
            Base->getCanonicalDecl())
2817
14
          DerivedToBasePath.push_back(&BS);
2818
14
      PrevRD = PathElem;
2819
14
    }
2820
14
    assert(DerivedToBasePath.size() == MemberPointerPath.size());
2821
2822
0
    CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2823
14
                                : CK_BaseToDerivedMemberPointer;
2824
14
    C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2825
14
                                    DerivedToBasePath.end(), C);
2826
14
  }
2827
37
  return C;
2828
37
}
2829
2830
llvm::Constant *
2831
337
MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2832
337
  assert(MD->isInstance() && "Member function must not be static!");
2833
2834
337
  CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2835
337
  const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2836
337
  CodeGenTypes &Types = CGM.getTypes();
2837
2838
337
  unsigned VBTableIndex = 0;
2839
337
  llvm::Constant *FirstField;
2840
337
  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2841
337
  if (!MD->isVirtual()) {
2842
282
    llvm::Type *Ty;
2843
    // Check whether the function has a computable LLVM signature.
2844
282
    if (Types.isFuncTypeConvertible(FPT)) {
2845
      // The function has a computable LLVM signature; use the correct type.
2846
278
      Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2847
4
    } else {
2848
      // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2849
      // function type is incomplete.
2850
4
      Ty = CGM.PtrDiffTy;
2851
4
    }
2852
282
    FirstField = CGM.GetAddrOfFunction(MD, Ty);
2853
55
  } else {
2854
55
    auto &VTableContext = CGM.getMicrosoftVTableContext();
2855
55
    MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2856
55
    FirstField = EmitVirtualMemPtrThunk(MD, ML);
2857
    // Include the vfptr adjustment if the method is in a non-primary vftable.
2858
55
    NonVirtualBaseAdjustment += ML.VFPtrOffset;
2859
55
    if (ML.VBase)
2860
3
      VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2861
55
  }
2862
2863
337
  if (VBTableIndex == 0 &&
2864
334
      RD->getMSInheritanceModel() ==
2865
334
          MSInheritanceModel::Virtual)
2866
9
    NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2867
2868
  // The rest of the fields are common with data member pointers.
2869
337
  FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2870
337
  return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2871
337
                               NonVirtualBaseAdjustment, VBTableIndex);
2872
337
}
2873
2874
/// Member pointers are the same if they're either bitwise identical *or* both
2875
/// null.  Null-ness for function members is determined by the first field,
2876
/// while for data member pointers we must compare all fields.
2877
llvm::Value *
2878
MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2879
                                             llvm::Value *L,
2880
                                             llvm::Value *R,
2881
                                             const MemberPointerType *MPT,
2882
12
                                             bool Inequality) {
2883
12
  CGBuilderTy &Builder = CGF.Builder;
2884
2885
  // Handle != comparisons by switching the sense of all boolean operations.
2886
12
  llvm::ICmpInst::Predicate Eq;
2887
12
  llvm::Instruction::BinaryOps And, Or;
2888
12
  if (Inequality) {
2889
4
    Eq = llvm::ICmpInst::ICMP_NE;
2890
4
    And = llvm::Instruction::Or;
2891
4
    Or = llvm::Instruction::And;
2892
8
  } else {
2893
8
    Eq = llvm::ICmpInst::ICMP_EQ;
2894
8
    And = llvm::Instruction::And;
2895
8
    Or = llvm::Instruction::Or;
2896
8
  }
2897
2898
  // If this is a single field member pointer (single inheritance), this is a
2899
  // single icmp.
2900
12
  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2901
12
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2902
12
  if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
2903
12
                                      Inheritance))
2904
4
    return Builder.CreateICmp(Eq, L, R);
2905
2906
  // Compare the first field.
2907
8
  llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2908
8
  llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2909
8
  llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2910
2911
  // Compare everything other than the first field.
2912
8
  llvm::Value *Res = nullptr;
2913
8
  llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2914
28
  for (unsigned I = 1, E = LType->getNumElements(); I != E; 
++I20
) {
2915
20
    llvm::Value *LF = Builder.CreateExtractValue(L, I);
2916
20
    llvm::Value *RF = Builder.CreateExtractValue(R, I);
2917
20
    llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2918
20
    if (Res)
2919
12
      Res = Builder.CreateBinOp(And, Res, Cmp);
2920
8
    else
2921
8
      Res = Cmp;
2922
20
  }
2923
2924
  // Check if the first field is 0 if this is a function pointer.
2925
8
  if (MPT->isMemberFunctionPointer()) {
2926
    // (l1 == r1 && ...) || l0 == 0
2927
4
    llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2928
4
    llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2929
4
    Res = Builder.CreateBinOp(Or, Res, IsZero);
2930
4
  }
2931
2932
  // Combine the comparison of the first field, which must always be true for
2933
  // this comparison to succeeed.
2934
8
  return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2935
8
}
2936
2937
llvm::Value *
2938
MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2939
                                            llvm::Value *MemPtr,
2940
19
                                            const MemberPointerType *MPT) {
2941
19
  CGBuilderTy &Builder = CGF.Builder;
2942
19
  llvm::SmallVector<llvm::Constant *, 4> fields;
2943
  // We only need one field for member functions.
2944
19
  if (MPT->isMemberFunctionPointer())
2945
9
    fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2946
10
  else
2947
10
    GetNullMemberPointerFields(MPT, fields);
2948
19
  assert(!fields.empty());
2949
19
  llvm::Value *FirstField = MemPtr;
2950
19
  if (MemPtr->getType()->isStructTy())
2951
8
    FirstField = Builder.CreateExtractValue(MemPtr, 0);
2952
19
  llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2953
2954
  // For function member pointers, we only need to test the function pointer
2955
  // field.  The other fields if any can be garbage.
2956
19
  if (MPT->isMemberFunctionPointer())
2957
9
    return Res;
2958
2959
  // Otherwise, emit a series of compares and combine the results.
2960
14
  
for (int I = 1, E = fields.size(); 10
I < E;
++I4
) {
2961
4
    llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2962
4
    llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2963
4
    Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2964
4
  }
2965
10
  return Res;
2966
10
}
2967
2968
bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2969
96
                                                  llvm::Constant *Val) {
2970
  // Function pointers are null if the pointer in the first field is null.
2971
96
  if (MPT->isMemberFunctionPointer()) {
2972
78
    llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2973
76
      
Val->getAggregateElement(0U)2
: Val;
2974
78
    return FirstField->isNullValue();
2975
78
  }
2976
2977
  // If it's not a function pointer and it's zero initializable, we can easily
2978
  // check zero.
2979
18
  if (isZeroInitializable(MPT) && 
Val->isNullValue()6
)
2980
6
    return true;
2981
2982
  // Otherwise, break down all the fields for comparison.  Hopefully these
2983
  // little Constants are reused, while a big null struct might not be.
2984
12
  llvm::SmallVector<llvm::Constant *, 4> Fields;
2985
12
  GetNullMemberPointerFields(MPT, Fields);
2986
12
  if (Fields.size() == 1) {
2987
12
    assert(Val->getType()->isIntegerTy());
2988
12
    return Val == Fields[0];
2989
12
  }
2990
2991
0
  unsigned I, E;
2992
0
  for (I = 0, E = Fields.size(); I != E; ++I) {
2993
0
    if (Val->getAggregateElement(I) != Fields[I])
2994
0
      break;
2995
0
  }
2996
0
  return I == E;
2997
0
}
2998
2999
llvm::Value *
3000
MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3001
                                         Address This,
3002
                                         llvm::Value *VBPtrOffset,
3003
                                         llvm::Value *VBTableOffset,
3004
558
                                         llvm::Value **VBPtrOut) {
3005
558
  CGBuilderTy &Builder = CGF.Builder;
3006
  // Load the vbtable pointer from the vbptr in the instance.
3007
558
  This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
3008
558
  llvm::Value *VBPtr =
3009
558
    Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
3010
558
  if (VBPtrOut) 
*VBPtrOut = VBPtr70
;
3011
558
  VBPtr = Builder.CreateBitCast(VBPtr,
3012
558
            CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
3013
3014
558
  CharUnits VBPtrAlign;
3015
558
  if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3016
542
    VBPtrAlign = This.getAlignment().alignmentAtOffset(
3017
542
                                   CharUnits::fromQuantity(CI->getSExtValue()));
3018
16
  } else {
3019
16
    VBPtrAlign = CGF.getPointerAlign();
3020
16
  }
3021
3022
558
  llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
3023
3024
  // Translate from byte offset to table index. It improves analyzability.
3025
558
  llvm::Value *VBTableIndex = Builder.CreateAShr(
3026
558
      VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3027
558
      "vbtindex", /*isExact=*/true);
3028
3029
  // Load an i32 offset from the vb-table.
3030
558
  llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
3031
558
  VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
3032
558
  return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
3033
558
                                   "vbase_offs");
3034
558
}
3035
3036
// Returns an adjusted base cast to i8*, since we do more address arithmetic on
3037
// it.
3038
llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3039
    CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3040
33
    Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3041
33
  CGBuilderTy &Builder = CGF.Builder;
3042
33
  Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
3043
33
  llvm::BasicBlock *OriginalBB = nullptr;
3044
33
  llvm::BasicBlock *SkipAdjustBB = nullptr;
3045
33
  llvm::BasicBlock *VBaseAdjustBB = nullptr;
3046
3047
  // In the unspecified inheritance model, there might not be a vbtable at all,
3048
  // in which case we need to skip the virtual base lookup.  If there is a
3049
  // vbtable, the first entry is a no-op entry that gives back the original
3050
  // base, so look for a virtual base adjustment offset of zero.
3051
33
  if (VBPtrOffset) {
3052
21
    OriginalBB = Builder.GetInsertBlock();
3053
21
    VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3054
21
    SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3055
21
    llvm::Value *IsVirtual =
3056
21
      Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3057
21
                           "memptr.is_vbase");
3058
21
    Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3059
21
    CGF.EmitBlock(VBaseAdjustBB);
3060
21
  }
3061
3062
  // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3063
  // know the vbptr offset.
3064
33
  if (!VBPtrOffset) {
3065
12
    CharUnits offs = CharUnits::Zero();
3066
12
    if (!RD->hasDefinition()) {
3067
2
      DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3068
2
      unsigned DiagID = Diags.getCustomDiagID(
3069
2
          DiagnosticsEngine::Error,
3070
2
          "member pointer representation requires a "
3071
2
          "complete class type for %0 to perform this expression");
3072
2
      Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3073
10
    } else if (RD->getNumVBases())
3074
10
      offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3075
12
    VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3076
12
  }
3077
33
  llvm::Value *VBPtr = nullptr;
3078
33
  llvm::Value *VBaseOffs =
3079
33
    GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3080
33
  llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
3081
3082
  // Merge control flow with the case where we didn't have to adjust.
3083
33
  if (VBaseAdjustBB) {
3084
21
    Builder.CreateBr(SkipAdjustBB);
3085
21
    CGF.EmitBlock(SkipAdjustBB);
3086
21
    llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3087
21
    Phi->addIncoming(Base.getPointer(), OriginalBB);
3088
21
    Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3089
21
    return Phi;
3090
21
  }
3091
12
  return AdjustedBase;
3092
12
}
3093
3094
llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3095
    CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3096
24
    const MemberPointerType *MPT) {
3097
24
  assert(MPT->isMemberDataPointer());
3098
24
  unsigned AS = Base.getAddressSpace();
3099
24
  llvm::Type *PType =
3100
24
      CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3101
24
  CGBuilderTy &Builder = CGF.Builder;
3102
24
  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3103
24
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3104
3105
  // Extract the fields we need, regardless of model.  We'll apply them if we
3106
  // have them.
3107
24
  llvm::Value *FieldOffset = MemPtr;
3108
24
  llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3109
24
  llvm::Value *VBPtrOffset = nullptr;
3110
24
  if (MemPtr->getType()->isStructTy()) {
3111
    // We need to extract values.
3112
11
    unsigned I = 0;
3113
11
    FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3114
11
    if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3115
6
      VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3116
11
    if (inheritanceModelHasVBTableOffsetField(Inheritance))
3117
11
      VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3118
11
  }
3119
3120
24
  llvm::Value *Addr;
3121
24
  if (VirtualBaseAdjustmentOffset) {
3122
11
    Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3123
11
                             VBPtrOffset);
3124
13
  } else {
3125
13
    Addr = Base.getPointer();
3126
13
  }
3127
3128
  // Cast to char*.
3129
24
  Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3130
3131
  // Apply the offset, which we assume is non-null.
3132
24
  Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
3133
3134
  // Cast the address to the appropriate pointer type, adopting the address
3135
  // space of the base pointer.
3136
24
  return Builder.CreateBitCast(Addr, PType);
3137
24
}
3138
3139
llvm::Value *
3140
MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3141
                                             const CastExpr *E,
3142
79
                                             llvm::Value *Src) {
3143
79
  assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3144
79
         E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3145
79
         E->getCastKind() == CK_ReinterpretMemberPointer);
3146
3147
  // Use constant emission if we can.
3148
79
  if (isa<llvm::Constant>(Src))
3149
66
    return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3150
3151
  // We may be adding or dropping fields from the member pointer, so we need
3152
  // both types and the inheritance models of both records.
3153
13
  const MemberPointerType *SrcTy =
3154
13
    E->getSubExpr()->getType()->castAs<MemberPointerType>();
3155
13
  const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3156
13
  bool IsFunc = SrcTy->isMemberFunctionPointer();
3157
3158
  // If the classes use the same null representation, reinterpret_cast is a nop.
3159
13
  bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3160
13
  if (IsReinterpret && 
IsFunc6
)
3161
2
    return Src;
3162
3163
11
  CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3164
11
  CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3165
11
  if (IsReinterpret &&
3166
4
      SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3167
2
    return Src;
3168
3169
9
  CGBuilderTy &Builder = CGF.Builder;
3170
3171
  // Branch past the conversion if Src is null.
3172
9
  llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3173
9
  llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3174
3175
  // C++ 5.2.10p9: The null member pointer value is converted to the null member
3176
  //   pointer value of the destination type.
3177
9
  if (IsReinterpret) {
3178
    // For reinterpret casts, sema ensures that src and dst are both functions
3179
    // or data and have the same size, which means the LLVM types should match.
3180
2
    assert(Src->getType() == DstNull->getType());
3181
2
    return Builder.CreateSelect(IsNotNull, Src, DstNull);
3182
2
  }
3183
3184
7
  llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3185
7
  llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3186
7
  llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3187
7
  Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3188
7
  CGF.EmitBlock(ConvertBB);
3189
3190
7
  llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3191
7
      SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3192
7
      Builder);
3193
3194
7
  Builder.CreateBr(ContinueBB);
3195
3196
  // In the continuation, choose between DstNull and Dst.
3197
7
  CGF.EmitBlock(ContinueBB);
3198
7
  llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3199
7
  Phi->addIncoming(DstNull, OriginalBB);
3200
7
  Phi->addIncoming(Dst, ConvertBB);
3201
7
  return Phi;
3202
7
}
3203
3204
llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3205
    const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3206
    CastExpr::path_const_iterator PathBegin,
3207
    CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3208
88
    CGBuilderTy &Builder) {
3209
88
  const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3210
88
  const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3211
88
  MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3212
88
  MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3213
88
  bool IsFunc = SrcTy->isMemberFunctionPointer();
3214
88
  bool IsConstant = isa<llvm::Constant>(Src);
3215
3216
  // Decompose src.
3217
88
  llvm::Value *FirstField = Src;
3218
88
  llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3219
88
  llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3220
88
  llvm::Value *VBPtrOffset = getZeroInt();
3221
88
  if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3222
    // We need to extract values.
3223
6
    unsigned I = 0;
3224
6
    FirstField = Builder.CreateExtractValue(Src, I++);
3225
6
    if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3226
6
      NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3227
6
    if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3228
0
      VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3229
6
    if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3230
4
      VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3231
6
  }
3232
3233
88
  bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3234
83
  const MemberPointerType *DerivedTy = IsDerivedToBase ? 
SrcTy5
: DstTy;
3235
88
  const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3236
3237
  // For data pointers, we adjust the field offset directly.  For functions, we
3238
  // have a separate field.
3239
75
  llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : 
FirstField13
;
3240
3241
  // The virtual inheritance model has a quirk: the virtual base table is always
3242
  // referenced when dereferencing a member pointer even if the member pointer
3243
  // is non-virtual.  This is accounted for by adjusting the non-virtual offset
3244
  // to point backwards to the top of the MDC from the first VBase.  Undo this
3245
  // adjustment to normalize the member pointer.
3246
88
  llvm::Value *SrcVBIndexEqZero =
3247
88
      Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3248
88
  if (SrcInheritance == MSInheritanceModel::Virtual) {
3249
4
    if (int64_t SrcOffsetToFirstVBase =
3250
0
            getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3251
0
      llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3252
0
          SrcVBIndexEqZero,
3253
0
          llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3254
0
          getZeroInt());
3255
0
      NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3256
0
    }
3257
4
  }
3258
3259
  // A non-zero vbindex implies that we are dealing with a source member in a
3260
  // floating virtual base in addition to some non-virtual offset.  If the
3261
  // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3262
  // fixed, base.  The difference between these two cases is that the vbindex +
3263
  // nvoffset *always* point to the member regardless of what context they are
3264
  // evaluated in so long as the vbindex is adjusted.  A member inside a fixed
3265
  // base requires explicit nv adjustment.
3266
88
  llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3267
88
      CGM.IntTy,
3268
88
      CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3269
88
          .getQuantity());
3270
3271
88
  llvm::Value *NVDisp;
3272
88
  if (IsDerivedToBase)
3273
5
    NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3274
83
  else
3275
83
    NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3276
3277
88
  NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3278
3279
  // Update the vbindex to an appropriate value in the destination because
3280
  // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3281
88
  llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3282
88
  if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3283
16
      inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3284
4
    if (llvm::GlobalVariable *VDispMap =
3285
0
            getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3286
0
      llvm::Value *VBIndex = Builder.CreateExactUDiv(
3287
0
          VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3288
0
      if (IsConstant) {
3289
0
        llvm::Constant *Mapping = VDispMap->getInitializer();
3290
0
        VirtualBaseAdjustmentOffset =
3291
0
            Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3292
0
      } else {
3293
0
        llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3294
0
        VirtualBaseAdjustmentOffset =
3295
0
            Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3296
0
                                      CharUnits::fromQuantity(4));
3297
0
      }
3298
3299
0
      DstVBIndexEqZero =
3300
0
          Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3301
0
    }
3302
4
  }
3303
3304
  // Set the VBPtrOffset to zero if the vbindex is zero.  Otherwise, initialize
3305
  // it to the offset of the vbptr.
3306
88
  if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3307
12
    llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3308
12
        CGM.IntTy,
3309
12
        getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3310
12
    VBPtrOffset =
3311
12
        Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3312
12
  }
3313
3314
  // Likewise, apply a similar adjustment so that dereferencing the member
3315
  // pointer correctly accounts for the distance between the start of the first
3316
  // virtual base and the top of the MDC.
3317
88
  if (DstInheritance == MSInheritanceModel::Virtual) {
3318
4
    if (int64_t DstOffsetToFirstVBase =
3319
4
            getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3320
4
      llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3321
4
          DstVBIndexEqZero,
3322
4
          llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3323
4
          getZeroInt());
3324
4
      NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3325
4
    }
3326
4
  }
3327
3328
  // Recompose dst from the null struct and the adjusted fields from src.
3329
88
  llvm::Value *Dst;
3330
88
  if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3331
66
    Dst = FirstField;
3332
22
  } else {
3333
22
    Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3334
22
    unsigned Idx = 0;
3335
22
    Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3336
22
    if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3337
10
      Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3338
22
    if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3339
12
      Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3340
22
    if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3341
16
      Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3342
22
  }
3343
88
  return Dst;
3344
88
}
3345
3346
llvm::Constant *
3347
MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3348
82
                                             llvm::Constant *Src) {
3349
82
  const MemberPointerType *SrcTy =
3350
82
      E->getSubExpr()->getType()->castAs<MemberPointerType>();
3351
82
  const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3352
3353
82
  CastKind CK = E->getCastKind();
3354
3355
82
  return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3356
82
                                     E->path_end(), Src);
3357
82
}
3358
3359
llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3360
    const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3361
    CastExpr::path_const_iterator PathBegin,
3362
96
    CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3363
96
  assert(CK == CK_DerivedToBaseMemberPointer ||
3364
96
         CK == CK_BaseToDerivedMemberPointer ||
3365
96
         CK == CK_ReinterpretMemberPointer);
3366
  // If src is null, emit a new null for dst.  We can't return src because dst
3367
  // might have a new representation.
3368
96
  if (MemberPointerConstantIsNull(SrcTy, Src))
3369
10
    return EmitNullMemberPointer(DstTy);
3370
3371
  // We don't need to do anything for reinterpret_casts of non-null member
3372
  // pointers.  We should only get here when the two type representations have
3373
  // the same size.
3374
86
  if (CK == CK_ReinterpretMemberPointer)
3375
5
    return Src;
3376
3377
81
  CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3378
81
  auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3379
81
      SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3380
3381
81
  return Dst;
3382
81
}
3383
3384
CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3385
    CodeGenFunction &CGF, const Expr *E, Address This,
3386
    llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3387
49
    const MemberPointerType *MPT) {
3388
49
  assert(MPT->isMemberFunctionPointer());
3389
49
  const FunctionProtoType *FPT =
3390
49
    MPT->getPointeeType()->castAs<FunctionProtoType>();
3391
49
  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3392
49
  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3393
49
      CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3394
49
  CGBuilderTy &Builder = CGF.Builder;
3395
3396
49
  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3397
3398
  // Extract the fields we need, regardless of model.  We'll apply them if we
3399
  // have them.
3400
49
  llvm::Value *FunctionPointer = MemPtr;
3401
49
  llvm::Value *NonVirtualBaseAdjustment = nullptr;
3402
49
  llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3403
49
  llvm::Value *VBPtrOffset = nullptr;
3404
49
  if (MemPtr->getType()->isStructTy()) {
3405
    // We need to extract values.
3406
36
    unsigned I = 0;
3407
36
    FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3408
36
    if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3409
36
      NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3410
36
    if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3411
15
      VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3412
36
    if (inheritanceModelHasVBTableOffsetField(Inheritance))
3413
22
      VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3414
36
  }
3415
3416
49
  if (VirtualBaseAdjustmentOffset) {
3417
22
    ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3418
22
                                   VirtualBaseAdjustmentOffset, VBPtrOffset);
3419
27
  } else {
3420
27
    ThisPtrForCall = This.getPointer();
3421
27
  }
3422
3423
49
  if (NonVirtualBaseAdjustment) {
3424
    // Apply the adjustment and cast back to the original struct type.
3425
36
    llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3426
36
    Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3427
36
    ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3428
36
                                           "this.adjusted");
3429
36
  }
3430
3431
49
  FunctionPointer =
3432
49
    Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3433
49
  CGCallee Callee(FPT, FunctionPointer);
3434
49
  return Callee;
3435
49
}
3436
3437
723
CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3438
723
  return new MicrosoftCXXABI(CGM);
3439
723
}
3440
3441
// MS RTTI Overview:
3442
// The run time type information emitted by cl.exe contains 5 distinct types of
3443
// structures.  Many of them reference each other.
3444
//
3445
// TypeInfo:  Static classes that are returned by typeid.
3446
//
3447
// CompleteObjectLocator:  Referenced by vftables.  They contain information
3448
//   required for dynamic casting, including OffsetFromTop.  They also contain
3449
//   a reference to the TypeInfo for the type and a reference to the
3450
//   CompleteHierarchyDescriptor for the type.
3451
//
3452
// ClassHierarchyDescriptor: Contains information about a class hierarchy.
3453
//   Used during dynamic_cast to walk a class hierarchy.  References a base
3454
//   class array and the size of said array.
3455
//
3456
// BaseClassArray: Contains a list of classes in a hierarchy.  BaseClassArray is
3457
//   somewhat of a misnomer because the most derived class is also in the list
3458
//   as well as multiple copies of virtual bases (if they occur multiple times
3459
//   in the hierarchy.)  The BaseClassArray contains one BaseClassDescriptor for
3460
//   every path in the hierarchy, in pre-order depth first order.  Note, we do
3461
//   not declare a specific llvm type for BaseClassArray, it's merely an array
3462
//   of BaseClassDescriptor pointers.
3463
//
3464
// BaseClassDescriptor: Contains information about a class in a class hierarchy.
3465
//   BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3466
//   BaseClassArray is.  It contains information about a class within a
3467
//   hierarchy such as: is this base is ambiguous and what is its offset in the
3468
//   vbtable.  The names of the BaseClassDescriptors have all of their fields
3469
//   mangled into them so they can be aggressively deduplicated by the linker.
3470
3471
352
static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3472
352
  StringRef MangledName("??_7type_info@@6B@");
3473
352
  if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3474
265
    return VTable;
3475
87
  return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3476
87
                                  /*isConstant=*/true,
3477
87
                                  llvm::GlobalVariable::ExternalLinkage,
3478
87
                                  /*Initializer=*/nullptr, MangledName);
3479
87
}
3480
3481
namespace {
3482
3483
/// A Helper struct that stores information about a class in a class
3484
/// hierarchy.  The information stored in these structs struct is used during
3485
/// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3486
// During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3487
// implicit depth first pre-order tree connectivity.  getFirstChild and
3488
// getNextSibling allow us to walk the tree efficiently.
3489
struct MSRTTIClass {
3490
  enum {
3491
    IsPrivateOnPath = 1 | 8,
3492
    IsAmbiguous = 2,
3493
    IsPrivate = 4,
3494
    IsVirtual = 16,
3495
    HasHierarchyDescriptor = 64
3496
  };
3497
515
  MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3498
  uint32_t initialize(const MSRTTIClass *Parent,
3499
                      const CXXBaseSpecifier *Specifier);
3500
3501
515
  MSRTTIClass *getFirstChild() { return this + 1; }
3502
239
  static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3503
239
    return Child + 1 + Child->NumBases;
3504
239
  }
3505
3506
  const CXXRecordDecl *RD, *VirtualRoot;
3507
  uint32_t Flags, NumBases, OffsetInVBase;
3508
};
3509
3510
/// Recursively initialize the base class array.
3511
uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3512
515
                                 const CXXBaseSpecifier *Specifier) {
3513
515
  Flags = HasHierarchyDescriptor;
3514
515
  if (!Parent) {
3515
285
    VirtualRoot = nullptr;
3516
285
    OffsetInVBase = 0;
3517
230
  } else {
3518
230
    if (Specifier->getAccessSpecifier() != AS_public)
3519
37
      Flags |= IsPrivate | IsPrivateOnPath;
3520
230
    if (Specifier->isVirtual()) {
3521
48
      Flags |= IsVirtual;
3522
48
      VirtualRoot = RD;
3523
48
      OffsetInVBase = 0;
3524
182
    } else {
3525
182
      if (Parent->Flags & IsPrivateOnPath)
3526
12
        Flags |= IsPrivateOnPath;
3527
182
      VirtualRoot = Parent->VirtualRoot;
3528
182
      OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3529
182
          .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3530
182
    }
3531
230
  }
3532
515
  NumBases = 0;
3533
515
  MSRTTIClass *Child = getFirstChild();
3534
230
  for (const CXXBaseSpecifier &Base : RD->bases()) {
3535
230
    NumBases += Child->initialize(this, &Base) + 1;
3536
230
    Child = getNextChild(Child);
3537
230
  }
3538
515
  return NumBases;
3539
515
}
3540
3541
1.15k
static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3542
1.15k
  switch (Ty->getLinkage()) {
3543
52
  case NoLinkage:
3544
52
  case InternalLinkage:
3545
52
  case UniqueExternalLinkage:
3546
52
    return llvm::GlobalValue::InternalLinkage;
3547
3548
1.09k
  case VisibleNoLinkage:
3549
1.09k
  case ModuleInternalLinkage:
3550
1.09k
  case ModuleLinkage:
3551
1.09k
  case ExternalLinkage:
3552
1.09k
    return llvm::GlobalValue::LinkOnceODRLinkage;
3553
0
  }
3554
0
  llvm_unreachable("Invalid linkage!");
3555
0
}
3556
3557
/// An ephemeral helper class for building MS RTTI types.  It caches some
3558
/// calls to the module and information about the most derived class in a
3559
/// hierarchy.
3560
struct MSRTTIBuilder {
3561
  enum {
3562
    HasBranchingHierarchy = 1,
3563
    HasVirtualBranchingHierarchy = 2,
3564
    HasAmbiguousBases = 4
3565
  };
3566
3567
  MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3568
      : CGM(ABI.CGM), Context(CGM.getContext()),
3569
        VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3570
        Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3571
620
        ABI(ABI) {}
3572
3573
  llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3574
  llvm::GlobalVariable *
3575
  getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3576
  llvm::GlobalVariable *getClassHierarchyDescriptor();
3577
  llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3578
3579
  CodeGenModule &CGM;
3580
  ASTContext &Context;
3581
  llvm::LLVMContext &VMContext;
3582
  llvm::Module &Module;
3583
  const CXXRecordDecl *RD;
3584
  llvm::GlobalVariable::LinkageTypes Linkage;
3585
  MicrosoftCXXABI &ABI;
3586
};
3587
3588
} // namespace
3589
3590
/// Recursively serializes a class hierarchy in pre-order depth first
3591
/// order.
3592
static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3593
515
                                    const CXXRecordDecl *RD) {
3594
515
  Classes.push_back(MSRTTIClass(RD));
3595
515
  for (const CXXBaseSpecifier &Base : RD->bases())
3596
230
    serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3597
515
}
3598
3599
/// Find ambiguity among base classes.
3600
static void
3601
285
detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3602
285
  llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3603
285
  llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3604
285
  llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3605
794
  for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3606
509
    if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3607
48
        !VirtualBases.insert(Class->RD).second) {
3608
9
      Class = MSRTTIClass::getNextChild(Class);
3609
9
      continue;
3610
9
    }
3611
500
    if (!UniqueBases.insert(Class->RD).second)
3612
2
      AmbiguousBases.insert(Class->RD);
3613
500
    Class++;
3614
500
  }
3615
285
  if (AmbiguousBases.empty())
3616
283
    return;
3617
2
  for (MSRTTIClass &Class : Classes)
3618
10
    if (AmbiguousBases.count(Class.RD))
3619
4
      Class.Flags |= MSRTTIClass::IsAmbiguous;
3620
2
}
3621
3622
620
llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3623
620
  SmallString<256> MangledName;
3624
620
  {
3625
620
    llvm::raw_svector_ostream Out(MangledName);
3626
620
    ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3627
620
  }
3628
3629
  // Check to see if we've already declared this ClassHierarchyDescriptor.
3630
620
  if (auto CHD = Module.getNamedGlobal(MangledName))
3631
355
    return CHD;
3632
3633
  // Serialize the class hierarchy and initialize the CHD Fields.
3634
265
  SmallVector<MSRTTIClass, 8> Classes;
3635
265
  serializeClassHierarchy(Classes, RD);
3636
265
  Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3637
265
  detectAmbiguousBases(Classes);
3638
265
  int Flags = 0;
3639
479
  for (auto Class : Classes) {
3640
479
    if (Class.RD->getNumBases() > 1)
3641
44
      Flags |= HasBranchingHierarchy;
3642
    // Note: cl.exe does not calculate "HasAmbiguousBases" correctly.  We
3643
    // believe the field isn't actually used.
3644
479
    if (Class.Flags & MSRTTIClass::IsAmbiguous)
3645
4
      Flags |= HasAmbiguousBases;
3646
479
  }
3647
265
  if ((Flags & HasBranchingHierarchy) && 
RD->getNumVBases() != 042
)
3648
13
    Flags |= HasVirtualBranchingHierarchy;
3649
  // These gep indices are used to get the address of the first element of the
3650
  // base class array.
3651
265
  llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3652
265
                               llvm::ConstantInt::get(CGM.IntTy, 0)};
3653
3654
  // Forward-declare the class hierarchy descriptor
3655
265
  auto Type = ABI.getClassHierarchyDescriptorType();
3656
265
  auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3657
265
                                      /*Initializer=*/nullptr,
3658
265
                                      MangledName);
3659
265
  if (CHD->isWeakForLinker())
3660
252
    CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3661
3662
265
  auto *Bases = getBaseClassArray(Classes);
3663
3664
  // Initialize the base class ClassHierarchyDescriptor.
3665
265
  llvm::Constant *Fields[] = {
3666
265
      llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3667
265
      llvm::ConstantInt::get(CGM.IntTy, Flags),
3668
265
      llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3669
265
      ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3670
265
          Bases->getValueType(), Bases,
3671
265
          llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3672
265
  };
3673
265
  CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3674
265
  return CHD;
3675
265
}
3676
3677
llvm::GlobalVariable *
3678
265
MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3679
265
  SmallString<256> MangledName;
3680
265
  {
3681
265
    llvm::raw_svector_ostream Out(MangledName);
3682
265
    ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3683
265
  }
3684
3685
  // Forward-declare the base class array.
3686
  // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3687
  // mode) bytes of padding.  We provide a pointer sized amount of padding by
3688
  // adding +1 to Classes.size().  The sections have pointer alignment and are
3689
  // marked pick-any so it shouldn't matter.
3690
265
  llvm::Type *PtrType = ABI.getImageRelativeType(
3691
265
      ABI.getBaseClassDescriptorType()->getPointerTo());
3692
265
  auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3693
265
  auto *BCA =
3694
265
      new llvm::GlobalVariable(Module, ArrType,
3695
265
                               /*isConstant=*/true, Linkage,
3696
265
                               /*Initializer=*/nullptr, MangledName);
3697
265
  if (BCA->isWeakForLinker())
3698
252
    BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3699
3700
  // Initialize the BaseClassArray.
3701
265
  SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3702
265
  for (MSRTTIClass &Class : Classes)
3703
479
    BaseClassArrayData.push_back(
3704
479
        ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3705
265
  BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3706
265
  BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3707
265
  return BCA;
3708
265
}
3709
3710
llvm::GlobalVariable *
3711
479
MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3712
  // Compute the fields for the BaseClassDescriptor.  They are computed up front
3713
  // because they are mangled into the name of the object.
3714
479
  uint32_t OffsetInVBTable = 0;
3715
479
  int32_t VBPtrOffset = -1;
3716
479
  if (Class.VirtualRoot) {
3717
62
    auto &VTableContext = CGM.getMicrosoftVTableContext();
3718
62
    OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3719
62
    VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3720
62
  }
3721
3722
479
  SmallString<256> MangledName;
3723
479
  {
3724
479
    llvm::raw_svector_ostream Out(MangledName);
3725
479
    ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3726
479
        Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3727
479
        Class.Flags, Out);
3728
479
  }
3729
3730
  // Check to see if we've already declared this object.
3731
479
  if (auto BCD = Module.getNamedGlobal(MangledName))
3732
110
    return BCD;
3733
3734
  // Forward-declare the base class descriptor.
3735
369
  auto Type = ABI.getBaseClassDescriptorType();
3736
369
  auto BCD =
3737
369
      new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3738
369
                               /*Initializer=*/nullptr, MangledName);
3739
369
  if (BCD->isWeakForLinker())
3740
349
    BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3741
3742
  // Initialize the BaseClassDescriptor.
3743
369
  llvm::Constant *Fields[] = {
3744
369
      ABI.getImageRelativeConstant(
3745
369
          ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3746
369
      llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3747
369
      llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3748
369
      llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3749
369
      llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3750
369
      llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3751
369
      ABI.getImageRelativeConstant(
3752
369
          MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3753
369
  };
3754
369
  BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3755
369
  return BCD;
3756
369
}
3757
3758
llvm::GlobalVariable *
3759
251
MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3760
251
  SmallString<256> MangledName;
3761
251
  {
3762
251
    llvm::raw_svector_ostream Out(MangledName);
3763
251
    ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3764
251
  }
3765
3766
  // Check to see if we've already computed this complete object locator.
3767
251
  if (auto COL = Module.getNamedGlobal(MangledName))
3768
0
    return COL;
3769
3770
  // Compute the fields of the complete object locator.
3771
251
  int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3772
251
  int VFPtrOffset = 0;
3773
  // The offset includes the vtordisp if one exists.
3774
251
  if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3775
38
    if (Context.getASTRecordLayout(RD)
3776
38
      .getVBaseOffsetsMap()
3777
38
      .find(VBase)
3778
38
      ->second.hasVtorDisp())
3779
10
      VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3780
3781
  // Forward-declare the complete object locator.
3782
251
  llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3783
251
  auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3784
251
    /*Initializer=*/nullptr, MangledName);
3785
3786
  // Initialize the CompleteObjectLocator.
3787
251
  llvm::Constant *Fields[] = {
3788
251
      llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3789
251
      llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3790
251
      llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3791
251
      ABI.getImageRelativeConstant(
3792
251
          CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3793
251
      ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3794
251
      ABI.getImageRelativeConstant(COL),
3795
251
  };
3796
251
  llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3797
251
  if (!ABI.isImageRelative())
3798
102
    FieldsRef = FieldsRef.drop_back();
3799
251
  COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3800
251
  if (COL->isWeakForLinker())
3801
233
    COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3802
251
  return COL;
3803
251
}
3804
3805
static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3806
                                   bool &IsConst, bool &IsVolatile,
3807
61
                                   bool &IsUnaligned) {
3808
61
  T = Context.getExceptionObjectType(T);
3809
3810
  // C++14 [except.handle]p3:
3811
  //   A handler is a match for an exception object of type E if [...]
3812
  //     - the handler is of type cv T or const T& where T is a pointer type and
3813
  //       E is a pointer type that can be converted to T by [...]
3814
  //         - a qualification conversion
3815
61
  IsConst = false;
3816
61
  IsVolatile = false;
3817
61
  IsUnaligned = false;
3818
61
  QualType PointeeType = T->getPointeeType();
3819
61
  if (!PointeeType.isNull()) {
3820
9
    IsConst = PointeeType.isConstQualified();
3821
9
    IsVolatile = PointeeType.isVolatileQualified();
3822
9
    IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3823
9
  }
3824
3825
  // Member pointer types like "const int A::*" are represented by having RTTI
3826
  // for "int A::*" and separately storing the const qualifier.
3827
61
  if (const auto *MPTy = T->getAs<MemberPointerType>())
3828
0
    T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3829
0
                                     MPTy->getClass());
3830
3831
  // Pointer types like "const int * const *" are represented by having RTTI
3832
  // for "const int **" and separately storing the const qualifier.
3833
61
  if (T->isPointerType())
3834
9
    T = Context.getPointerType(PointeeType.getUnqualifiedType());
3835
3836
61
  return T;
3837
61
}
3838
3839
CatchTypeInfo
3840
MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3841
15
                                              QualType CatchHandlerType) {
3842
  // TypeDescriptors for exceptions never have qualified pointer types,
3843
  // qualifiers are stored separately in order to support qualification
3844
  // conversions.
3845
15
  bool IsConst, IsVolatile, IsUnaligned;
3846
15
  Type =
3847
15
      decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3848
3849
15
  bool IsReference = CatchHandlerType->isReferenceType();
3850
3851
15
  uint32_t Flags = 0;
3852
15
  if (IsConst)
3853
1
    Flags |= 1;
3854
15
  if (IsVolatile)
3855
0
    Flags |= 2;
3856
15
  if (IsUnaligned)
3857
0
    Flags |= 4;
3858
15
  if (IsReference)
3859
3
    Flags |= 8;
3860
3861
15
  return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3862
15
                       Flags};
3863
15
}
3864
3865
/// Gets a TypeDescriptor.  Returns a llvm::Constant * rather than a
3866
/// llvm::GlobalVariable * because different type descriptors have different
3867
/// types, and need to be abstracted.  They are abstracting by casting the
3868
/// address to an Int8PtrTy.
3869
740
llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3870
740
  SmallString<256> MangledName;
3871
740
  {
3872
740
    llvm::raw_svector_ostream Out(MangledName);
3873
740
    getMangleContext().mangleCXXRTTI(Type, Out);
3874
740
  }
3875
3876
  // Check to see if we've already declared this TypeDescriptor.
3877
740
  if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3878
388
    return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3879
3880
  // Note for the future: If we would ever like to do deferred emission of
3881
  // RTTI, check if emitting vtables opportunistically need any adjustment.
3882
3883
  // Compute the fields for the TypeDescriptor.
3884
352
  SmallString<256> TypeInfoString;
3885
352
  {
3886
352
    llvm::raw_svector_ostream Out(TypeInfoString);
3887
352
    getMangleContext().mangleCXXRTTIName(Type, Out);
3888
352
  }
3889
3890
  // Declare and initialize the TypeDescriptor.
3891
352
  llvm::Constant *Fields[] = {
3892
352
    getTypeInfoVTable(CGM),                        // VFPtr
3893
352
    llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3894
352
    llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3895
352
  llvm::StructType *TypeDescriptorType =
3896
352
      getTypeDescriptorType(TypeInfoString);
3897
352
  auto *Var = new llvm::GlobalVariable(
3898
352
      CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
3899
352
      getLinkageForRTTI(Type),
3900
352
      llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3901
352
      MangledName);
3902
352
  if (Var->isWeakForLinker())
3903
337
    Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3904
352
  return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3905
352
}
3906
3907
/// Gets or a creates a Microsoft CompleteObjectLocator.
3908
llvm::GlobalVariable *
3909
MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3910
251
                                            const VPtrInfo &Info) {
3911
251
  return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3912
251
}
3913
3914
1.80k
void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
3915
1.80k
  if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
3916
    // There are no constructor variants, always emit the complete destructor.
3917
1.23k
    llvm::Function *Fn =
3918
1.23k
        CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
3919
1.23k
    CGM.maybeSetTrivialComdat(*ctor, *Fn);
3920
1.23k
    return;
3921
1.23k
  }
3922
3923
566
  auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
3924
3925
  // Emit the base destructor if the base and complete (vbase) destructors are
3926
  // equivalent. This effectively implements -mconstructor-aliases as part of
3927
  // the ABI.
3928
566
  if (GD.getDtorType() == Dtor_Complete &&
3929
95
      dtor->getParent()->getNumVBases() == 0)
3930
0
    GD = GD.getWithDtorType(Dtor_Base);
3931
3932
  // The base destructor is equivalent to the base destructor of its
3933
  // base class if there is exactly one non-virtual base class with a
3934
  // non-trivial destructor, there are no fields with a non-trivial
3935
  // destructor, and the body of the destructor is trivial.
3936
566
  if (GD.getDtorType() == Dtor_Base && 
!CGM.TryEmitBaseDestructorAsAlias(dtor)257
)
3937
4
    return;
3938
3939
562
  llvm::Function *Fn = CGM.codegenCXXStructor(GD);
3940
562
  if (Fn->isWeakForLinker())
3941
478
    Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3942
562
}
3943
3944
llvm::Function *
3945
MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3946
35
                                         CXXCtorType CT) {
3947
35
  assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3948
3949
  // Calculate the mangled name.
3950
35
  SmallString<256> ThunkName;
3951
35
  llvm::raw_svector_ostream Out(ThunkName);
3952
35
  getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
3953
3954
  // If the thunk has been generated previously, just return it.
3955
35
  if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3956
0
    return cast<llvm::Function>(GV);
3957
3958
  // Create the llvm::Function.
3959
35
  const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3960
35
  llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3961
35
  const CXXRecordDecl *RD = CD->getParent();
3962
35
  QualType RecordTy = getContext().getRecordType(RD);
3963
35
  llvm::Function *ThunkFn = llvm::Function::Create(
3964
35
      ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3965
35
  ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3966
35
      FnInfo.getEffectiveCallingConvention()));
3967
35
  if (ThunkFn->isWeakForLinker())
3968
35
    ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3969
35
  bool IsCopy = CT == Ctor_CopyingClosure;
3970
3971
  // Start codegen.
3972
35
  CodeGenFunction CGF(CGM);
3973
35
  CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3974
3975
  // Build FunctionArgs.
3976
35
  FunctionArgList FunctionArgs;
3977
3978
  // A constructor always starts with a 'this' pointer as its first argument.
3979
35
  buildThisParam(CGF, FunctionArgs);
3980
3981
  // Following the 'this' pointer is a reference to the source object that we
3982
  // are copying from.
3983
35
  ImplicitParamDecl SrcParam(
3984
35
      getContext(), /*DC=*/nullptr, SourceLocation(),
3985
35
      &getContext().Idents.get("src"),
3986
35
      getContext().getLValueReferenceType(RecordTy,
3987
35
                                          /*SpelledAsLValue=*/true),
3988
35
      ImplicitParamDecl::Other);
3989
35
  if (IsCopy)
3990
6
    FunctionArgs.push_back(&SrcParam);
3991
3992
  // Constructors for classes which utilize virtual bases have an additional
3993
  // parameter which indicates whether or not it is being delegated to by a more
3994
  // derived constructor.
3995
35
  ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
3996
35
                                  SourceLocation(),
3997
35
                                  &getContext().Idents.get("is_most_derived"),
3998
35
                                  getContext().IntTy, ImplicitParamDecl::Other);
3999
  // Only add the parameter to the list if the class has virtual bases.
4000
35
  if (RD->getNumVBases() > 0)
4001
0
    FunctionArgs.push_back(&IsMostDerived);
4002
4003
  // Start defining the function.
4004
35
  auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4005
35
  CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4006
35
                    FunctionArgs, CD->getLocation(), SourceLocation());
4007
  // Create a scope with an artificial location for the body of this function.
4008
35
  auto AL = ApplyDebugLocation::CreateArtificial(CGF);
4009
35
  setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4010
35
  llvm::Value *This = getThisValue(CGF);
4011
4012
35
  llvm::Value *SrcVal =
4013
6
      IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4014
29
             : nullptr;
4015
4016
35
  CallArgList Args;
4017
4018
  // Push the this ptr.
4019
35
  Args.add(RValue::get(This), CD->getThisType());
4020
4021
  // Push the src ptr.
4022
35
  if (SrcVal)
4023
6
    Args.add(RValue::get(SrcVal), SrcParam.getType());
4024
4025
  // Add the rest of the default arguments.
4026
35
  SmallVector<const Stmt *, 4> ArgVec;
4027
29
  ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 
16
: 0);
4028
30
  for (const ParmVarDecl *PD : params) {
4029
30
    assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4030
30
    ArgVec.push_back(PD->getDefaultArg());
4031
30
  }
4032
4033
35
  CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4034
4035
35
  const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4036
29
  CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 
16
: 0);
4037
4038
  // Insert any ABI-specific implicit constructor arguments.
4039
35
  AddedStructorArgCounts ExtraArgs =
4040
35
      addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4041
35
                                 /*ForVirtualBase=*/false,
4042
35
                                 /*Delegating=*/false, Args);
4043
  // Call the destructor with our arguments.
4044
35
  llvm::Constant *CalleePtr =
4045
35
      CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4046
35
  CGCallee Callee =
4047
35
      CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4048
35
  const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4049
35
      Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4050
35
  CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4051
4052
35
  Cleanups.ForceCleanup();
4053
4054
  // Emit the ret instruction, remove any temporary instructions created for the
4055
  // aid of CodeGen.
4056
35
  CGF.FinishFunction(SourceLocation());
4057
4058
35
  return ThunkFn;
4059
35
}
4060
4061
llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4062
                                                  uint32_t NVOffset,
4063
                                                  int32_t VBPtrOffset,
4064
82
                                                  uint32_t VBIndex) {
4065
82
  assert(!T->isReferenceType());
4066
4067
82
  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4068
82
  const CXXConstructorDecl *CD =
4069
50
      RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : 
nullptr32
;
4070
82
  CXXCtorType CT = Ctor_Complete;
4071
82
  if (CD)
4072
30
    if (!hasDefaultCXXMethodCC(getContext(), CD) || 
CD->getNumParams() != 126
)
4073
12
      CT = Ctor_CopyingClosure;
4074
4075
82
  uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4076
82
  SmallString<256> MangledName;
4077
82
  {
4078
82
    llvm::raw_svector_ostream Out(MangledName);
4079
82
    getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4080
82
                                              VBPtrOffset, VBIndex, Out);
4081
82
  }
4082
82
  if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4083
26
    return getImageRelativeConstant(GV);
4084
4085
  // The TypeDescriptor is used by the runtime to determine if a catch handler
4086
  // is appropriate for the exception object.
4087
56
  llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4088
4089
  // The runtime is responsible for calling the copy constructor if the
4090
  // exception is caught by value.
4091
56
  llvm::Constant *CopyCtor;
4092
56
  if (CD) {
4093
16
    if (CT == Ctor_CopyingClosure)
4094
6
      CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4095
10
    else
4096
10
      CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4097
4098
16
    CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4099
40
  } else {
4100
40
    CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4101
40
  }
4102
56
  CopyCtor = getImageRelativeConstant(CopyCtor);
4103
4104
56
  bool IsScalar = !RD;
4105
56
  bool HasVirtualBases = false;
4106
56
  bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4107
56
  QualType PointeeType = T;
4108
56
  if (T->isPointerType())
4109
12
    PointeeType = T->getPointeeType();
4110
56
  if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4111
28
    HasVirtualBases = RD->getNumVBases() > 0;
4112
28
    if (IdentifierInfo *II = RD->getIdentifier())
4113
28
      IsStdBadAlloc = II->isStr("bad_alloc") && 
RD->isInStdNamespace()0
;
4114
28
  }
4115
4116
  // Encode the relevant CatchableType properties into the Flags bitfield.
4117
  // FIXME: Figure out how bits 2 or 8 can get set.
4118
56
  uint32_t Flags = 0;
4119
56
  if (IsScalar)
4120
28
    Flags |= 1;
4121
56
  if (HasVirtualBases)
4122
4
    Flags |= 4;
4123
56
  if (IsStdBadAlloc)
4124
0
    Flags |= 16;
4125
4126
56
  llvm::Constant *Fields[] = {
4127
56
      llvm::ConstantInt::get(CGM.IntTy, Flags),       // Flags
4128
56
      TD,                                             // TypeDescriptor
4129
56
      llvm::ConstantInt::get(CGM.IntTy, NVOffset),    // NonVirtualAdjustment
4130
56
      llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4131
56
      llvm::ConstantInt::get(CGM.IntTy, VBIndex),     // VBTableIndex
4132
56
      llvm::ConstantInt::get(CGM.IntTy, Size),        // Size
4133
56
      CopyCtor                                        // CopyCtor
4134
56
  };
4135
56
  llvm::StructType *CTType = getCatchableTypeType();
4136
56
  auto *GV = new llvm::GlobalVariable(
4137
56
      CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4138
56
      llvm::ConstantStruct::get(CTType, Fields), MangledName);
4139
56
  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4140
56
  GV->setSection(".xdata");
4141
56
  if (GV->isWeakForLinker())
4142
54
    GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4143
56
  return getImageRelativeConstant(GV);
4144
56
}
4145
4146
46
llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4147
46
  assert(!T->isReferenceType());
4148
4149
  // See if we've already generated a CatchableTypeArray for this type before.
4150
46
  llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4151
46
  if (CTA)
4152
2
    return CTA;
4153
4154
  // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4155
  // using a SmallSetVector.  Duplicates may arise due to virtual bases
4156
  // occurring more than once in the hierarchy.
4157
44
  llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4158
4159
  // C++14 [except.handle]p3:
4160
  //   A handler is a match for an exception object of type E if [...]
4161
  //     - the handler is of type cv T or cv T& and T is an unambiguous public
4162
  //       base class of E, or
4163
  //     - the handler is of type cv T or const T& where T is a pointer type and
4164
  //       E is a pointer type that can be converted to T by [...]
4165
  //         - a standard pointer conversion (4.10) not involving conversions to
4166
  //           pointers to private or protected or ambiguous classes
4167
44
  const CXXRecordDecl *MostDerivedClass = nullptr;
4168
44
  bool IsPointer = T->isPointerType();
4169
44
  if (IsPointer)
4170
8
    MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4171
36
  else
4172
36
    MostDerivedClass = T->getAsCXXRecordDecl();
4173
4174
  // Collect all the unambiguous public bases of the MostDerivedClass.
4175
44
  if (MostDerivedClass) {
4176
20
    const ASTContext &Context = getContext();
4177
20
    const ASTRecordLayout &MostDerivedLayout =
4178
20
        Context.getASTRecordLayout(MostDerivedClass);
4179
20
    MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4180
20
    SmallVector<MSRTTIClass, 8> Classes;
4181
20
    serializeClassHierarchy(Classes, MostDerivedClass);
4182
20
    Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4183
20
    detectAmbiguousBases(Classes);
4184
36
    for (const MSRTTIClass &Class : Classes) {
4185
      // Skip any ambiguous or private bases.
4186
36
      if (Class.Flags &
4187
36
          (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4188
6
        continue;
4189
      // Write down how to convert from a derived pointer to a base pointer.
4190
30
      uint32_t OffsetInVBTable = 0;
4191
30
      int32_t VBPtrOffset = -1;
4192
30
      if (Class.VirtualRoot) {
4193
4
        OffsetInVBTable =
4194
4
          VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4195
4
        VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4196
4
      }
4197
4198
      // Turn our record back into a pointer if the exception object is a
4199
      // pointer.
4200
30
      QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4201
30
      if (IsPointer)
4202
0
        RTTITy = Context.getPointerType(RTTITy);
4203
30
      CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4204
30
                                             VBPtrOffset, OffsetInVBTable));
4205
30
    }
4206
20
  }
4207
4208
  // C++14 [except.handle]p3:
4209
  //   A handler is a match for an exception object of type E if
4210
  //     - The handler is of type cv T or cv T& and E and T are the same type
4211
  //       (ignoring the top-level cv-qualifiers)
4212
44
  CatchableTypes.insert(getCatchableType(T));
4213
4214
  // C++14 [except.handle]p3:
4215
  //   A handler is a match for an exception object of type E if
4216
  //     - the handler is of type cv T or const T& where T is a pointer type and
4217
  //       E is a pointer type that can be converted to T by [...]
4218
  //         - a standard pointer conversion (4.10) not involving conversions to
4219
  //           pointers to private or protected or ambiguous classes
4220
  //
4221
  // C++14 [conv.ptr]p2:
4222
  //   A prvalue of type "pointer to cv T," where T is an object type, can be
4223
  //   converted to a prvalue of type "pointer to cv void".
4224
44
  if (IsPointer && 
T->getPointeeType()->isObjectType()8
)
4225
6
    CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4226
4227
  // C++14 [except.handle]p3:
4228
  //   A handler is a match for an exception object of type E if [...]
4229
  //     - the handler is of type cv T or const T& where T is a pointer or
4230
  //       pointer to member type and E is std::nullptr_t.
4231
  //
4232
  // We cannot possibly list all possible pointer types here, making this
4233
  // implementation incompatible with the standard.  However, MSVC includes an
4234
  // entry for pointer-to-void in this case.  Let's do the same.
4235
44
  if (T->isNullPtrType())
4236
2
    CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4237
4238
44
  uint32_t NumEntries = CatchableTypes.size();
4239
44
  llvm::Type *CTType =
4240
44
      getImageRelativeType(getCatchableTypeType()->getPointerTo());
4241
44
  llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4242
44
  llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4243
44
  llvm::Constant *Fields[] = {
4244
44
      llvm::ConstantInt::get(CGM.IntTy, NumEntries),    // NumEntries
4245
44
      llvm::ConstantArray::get(
4246
44
          AT, llvm::makeArrayRef(CatchableTypes.begin(),
4247
44
                                 CatchableTypes.end())) // CatchableTypes
4248
44
  };
4249
44
  SmallString<256> MangledName;
4250
44
  {
4251
44
    llvm::raw_svector_ostream Out(MangledName);
4252
44
    getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4253
44
  }
4254
44
  CTA = new llvm::GlobalVariable(
4255
44
      CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4256
44
      llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4257
44
  CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4258
44
  CTA->setSection(".xdata");
4259
44
  if (CTA->isWeakForLinker())
4260
42
    CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4261
44
  return CTA;
4262
44
}
4263
4264
46
llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4265
46
  bool IsConst, IsVolatile, IsUnaligned;
4266
46
  T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4267
4268
  // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4269
  // the exception object may be caught as.
4270
46
  llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4271
  // The first field in a CatchableTypeArray is the number of CatchableTypes.
4272
  // This is used as a component of the mangled name which means that we need to
4273
  // know what it is in order to see if we have previously generated the
4274
  // ThrowInfo.
4275
46
  uint32_t NumEntries =
4276
46
      cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4277
46
          ->getLimitedValue();
4278
4279
46
  SmallString<256> MangledName;
4280
46
  {
4281
46
    llvm::raw_svector_ostream Out(MangledName);
4282
46
    getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4283
46
                                          NumEntries, Out);
4284
46
  }
4285
4286
  // Reuse a previously generated ThrowInfo if we have generated an appropriate
4287
  // one before.
4288
46
  if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4289
2
    return GV;
4290
4291
  // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4292
  // be at least as CV qualified.  Encode this requirement into the Flags
4293
  // bitfield.
4294
44
  uint32_t Flags = 0;
4295
44
  if (IsConst)
4296
4
    Flags |= 1;
4297
44
  if (IsVolatile)
4298
0
    Flags |= 2;
4299
44
  if (IsUnaligned)
4300
2
    Flags |= 4;
4301
4302
  // The cleanup-function (a destructor) must be called when the exception
4303
  // object's lifetime ends.
4304
44
  llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4305
44
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4306
20
    if (CXXDestructorDecl *DtorD = RD->getDestructor())
4307
12
      if (!DtorD->isTrivial())
4308
4
        CleanupFn = llvm::ConstantExpr::getBitCast(
4309
4
            CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4310
4
            CGM.Int8PtrTy);
4311
  // This is unused as far as we can tell, initialize it to null.
4312
44
  llvm::Constant *ForwardCompat =
4313
44
      getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4314
44
  llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4315
44
      llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4316
44
  llvm::StructType *TIType = getThrowInfoType();
4317
44
  llvm::Constant *Fields[] = {
4318
44
      llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4319
44
      getImageRelativeConstant(CleanupFn),      // CleanupFn
4320
44
      ForwardCompat,                            // ForwardCompat
4321
44
      PointerToCatchableTypes                   // CatchableTypeArray
4322
44
  };
4323
44
  auto *GV = new llvm::GlobalVariable(
4324
44
      CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4325
44
      llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4326
44
  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4327
44
  GV->setSection(".xdata");
4328
44
  if (GV->isWeakForLinker())
4329
42
    GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4330
44
  return GV;
4331
44
}
4332
4333
40
void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4334
40
  const Expr *SubExpr = E->getSubExpr();
4335
40
  QualType ThrowType = SubExpr->getType();
4336
  // The exception object lives on the stack and it's address is passed to the
4337
  // runtime function.
4338
40
  Address AI = CGF.CreateMemTemp(ThrowType);
4339
40
  CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4340
40
                       /*IsInit=*/true);
4341
4342
  // The so-called ThrowInfo is used to describe how the exception object may be
4343
  // caught.
4344
40
  llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4345
4346
  // Call into the runtime to throw the exception.
4347
40
  llvm::Value *Args[] = {
4348
40
    CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4349
40
    TI
4350
40
  };
4351
40
  CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4352
40
}
4353
4354
std::pair<llvm::Value *, const CXXRecordDecl *>
4355
MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4356
2
                               const CXXRecordDecl *RD) {
4357
2
  std::tie(This, std::ignore, RD) =
4358
2
      performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4359
2
  return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4360
2
}