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