Coverage Report

Created: 2022-05-17 06:19

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