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