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