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