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