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) override;
262 
263   void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
264                               llvm::GlobalVariable *VTable);
265 
266   void emitVTableDefinitions(CodeGenVTables &CGVT,
267                              const CXXRecordDecl *RD) override;
268 
269   bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
270                                            CodeGenFunction::VPtr Vptr) override;
271 
272   /// Don't initialize vptrs if dynamic class
273   /// is marked with with the 'novtable' attribute.
274   bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
275     return !VTableClass->hasAttr<MSNoVTableAttr>();
276   }
277 
278   llvm::Constant *
279   getVTableAddressPoint(BaseSubobject Base,
280                         const CXXRecordDecl *VTableClass) override;
281 
282   llvm::Value *getVTableAddressPointInStructor(
283       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
284       BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
285 
286   llvm::Constant *
287   getVTableAddressPointForConstExpr(BaseSubobject Base,
288                                     const CXXRecordDecl *VTableClass) override;
289 
290   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
291                                         CharUnits VPtrOffset) override;
292 
293   CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
294                                      Address This, llvm::Type *Ty,
295                                      SourceLocation Loc) override;
296 
297   llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
298                                          const CXXDestructorDecl *Dtor,
299                                          CXXDtorType DtorType,
300                                          Address This,
301                                          const CXXMemberCallExpr *CE) 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, /*Constant=*/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(/*AddressSpace=*/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, /*IsVarArgs=*/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 =
848       EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
849   if (UseGlobalDelete)
850     CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
851 }
852 
853 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
854   llvm::Value *Args[] = {
855       llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
856       llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
857   llvm::FunctionCallee Fn = getThrowFn();
858   if (isNoReturn)
859     CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
860   else
861     CGF.EmitRuntimeCallOrInvoke(Fn, Args);
862 }
863 
864 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
865                                      const CXXCatchStmt *S) {
866   // In the MS ABI, the runtime handles the copy, and the catch handler is
867   // responsible for destruction.
868   VarDecl *CatchParam = S->getExceptionDecl();
869   llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
870   llvm::CatchPadInst *CPI =
871       cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
872   CGF.CurrentFuncletPad = CPI;
873 
874   // If this is a catch-all or the catch parameter is unnamed, we don't need to
875   // emit an alloca to the object.
876   if (!CatchParam || !CatchParam->getDeclName()) {
877     CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
878     return;
879   }
880 
881   CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
882   CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
883   CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
884   CGF.EmitAutoVarCleanups(var);
885 }
886 
887 /// We need to perform a generic polymorphic operation (like a typeid
888 /// or a cast), which requires an object with a vfptr.  Adjust the
889 /// address to point to an object with a vfptr.
890 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
891 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
892                                        QualType SrcRecordTy) {
893   Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
894   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
895   const ASTContext &Context = getContext();
896 
897   // If the class itself has a vfptr, great.  This check implicitly
898   // covers non-virtual base subobjects: a class with its own virtual
899   // functions would be a candidate to be a primary base.
900   if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
901     return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
902                            SrcDecl);
903 
904   // Okay, one of the vbases must have a vfptr, or else this isn't
905   // actually a polymorphic class.
906   const CXXRecordDecl *PolymorphicBase = nullptr;
907   for (auto &Base : SrcDecl->vbases()) {
908     const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
909     if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
910       PolymorphicBase = BaseDecl;
911       break;
912     }
913   }
914   assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
915 
916   llvm::Value *Offset =
917     GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
918   llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset);
919   CharUnits VBaseAlign =
920     CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
921   return std::make_tuple(Address(Ptr, VBaseAlign), Offset, PolymorphicBase);
922 }
923 
924 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
925                                                 QualType SrcRecordTy) {
926   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
927   return IsDeref &&
928          !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
929 }
930 
931 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
932                                         llvm::Value *Argument) {
933   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
934   llvm::FunctionType *FTy =
935       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
936   llvm::Value *Args[] = {Argument};
937   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
938   return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
939 }
940 
941 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
942   llvm::CallBase *Call =
943       emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
944   Call->setDoesNotReturn();
945   CGF.Builder.CreateUnreachable();
946 }
947 
948 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
949                                          QualType SrcRecordTy,
950                                          Address ThisPtr,
951                                          llvm::Type *StdTypeInfoPtrTy) {
952   std::tie(ThisPtr, std::ignore, std::ignore) =
953       performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
954   llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
955   return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
956 }
957 
958 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
959                                                          QualType SrcRecordTy) {
960   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
961   return SrcIsPtr &&
962          !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
963 }
964 
965 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
966     CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
967     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
968   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
969 
970   llvm::Value *SrcRTTI =
971       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
972   llvm::Value *DestRTTI =
973       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
974 
975   llvm::Value *Offset;
976   std::tie(This, Offset, std::ignore) =
977       performBaseAdjustment(CGF, This, SrcRecordTy);
978   llvm::Value *ThisPtr = This.getPointer();
979   Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
980 
981   // PVOID __RTDynamicCast(
982   //   PVOID inptr,
983   //   LONG VfDelta,
984   //   PVOID SrcType,
985   //   PVOID TargetType,
986   //   BOOL isReference)
987   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
988                             CGF.Int8PtrTy, CGF.Int32Ty};
989   llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
990       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
991       "__RTDynamicCast");
992   llvm::Value *Args[] = {
993       ThisPtr, Offset, SrcRTTI, DestRTTI,
994       llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
995   ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
996   return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
997 }
998 
999 llvm::Value *
1000 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1001                                        QualType SrcRecordTy,
1002                                        QualType DestTy) {
1003   std::tie(Value, std::ignore, std::ignore) =
1004       performBaseAdjustment(CGF, Value, SrcRecordTy);
1005 
1006   // PVOID __RTCastToVoid(
1007   //   PVOID inptr)
1008   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1009   llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1010       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1011       "__RTCastToVoid");
1012   llvm::Value *Args[] = {Value.getPointer()};
1013   return CGF.EmitRuntimeCall(Function, Args);
1014 }
1015 
1016 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1017   return false;
1018 }
1019 
1020 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1021     CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1022     const CXXRecordDecl *BaseClassDecl) {
1023   const ASTContext &Context = getContext();
1024   int64_t VBPtrChars =
1025       Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1026   llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1027   CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1028   CharUnits VBTableChars =
1029       IntSize *
1030       CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1031   llvm::Value *VBTableOffset =
1032       llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1033 
1034   llvm::Value *VBPtrToNewBase =
1035       GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1036   VBPtrToNewBase =
1037       CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1038   return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1039 }
1040 
1041 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1042   return isa<CXXConstructorDecl>(GD.getDecl());
1043 }
1044 
1045 static bool isDeletingDtor(GlobalDecl GD) {
1046   return isa<CXXDestructorDecl>(GD.getDecl()) &&
1047          GD.getDtorType() == Dtor_Deleting;
1048 }
1049 
1050 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1051   return isDeletingDtor(GD);
1052 }
1053 
1054 static bool IsSizeGreaterThan128(const CXXRecordDecl *RD) {
1055   return RD->getASTContext().getTypeSize(RD->getTypeForDecl()) > 128;
1056 }
1057 
1058 static bool hasMicrosoftABIRestrictions(const CXXRecordDecl *RD) {
1059   // For AArch64, we use the C++14 definition of an aggregate, so we also
1060   // check for:
1061   //   No private or protected non static data members.
1062   //   No base classes
1063   //   No virtual functions
1064   // Additionally, we need to ensure that there is a trivial copy assignment
1065   // operator, a trivial destructor and no user-provided constructors.
1066   if (RD->hasProtectedFields() || RD->hasPrivateFields())
1067     return true;
1068   if (RD->getNumBases() > 0)
1069     return true;
1070   if (RD->isPolymorphic())
1071     return true;
1072   if (RD->hasNonTrivialCopyAssignment())
1073     return true;
1074   for (const CXXConstructorDecl *Ctor : RD->ctors())
1075     if (Ctor->isUserProvided())
1076       return true;
1077   if (RD->hasNonTrivialDestructor())
1078     return true;
1079   return false;
1080 }
1081 
1082 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1083   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1084   if (!RD)
1085     return false;
1086 
1087   bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
1088   bool isSimple = !isAArch64 || !hasMicrosoftABIRestrictions(RD);
1089   bool isIndirectReturn =
1090       isAArch64 ? (!RD->canPassInRegisters() ||
1091                    IsSizeGreaterThan128(RD))
1092                 : !RD->isPOD();
1093   bool isInstanceMethod = FI.isInstanceMethod();
1094 
1095   if (isIndirectReturn || !isSimple || isInstanceMethod) {
1096     CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1097     FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1098     FI.getReturnInfo().setSRetAfterThis(isInstanceMethod);
1099 
1100     FI.getReturnInfo().setInReg(isAArch64 &&
1101                                 !(isSimple && IsSizeGreaterThan128(RD)));
1102 
1103     return true;
1104   }
1105 
1106   // Otherwise, use the C ABI rules.
1107   return false;
1108 }
1109 
1110 llvm::BasicBlock *
1111 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1112                                                const CXXRecordDecl *RD) {
1113   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1114   assert(IsMostDerivedClass &&
1115          "ctor for a class with virtual bases must have an implicit parameter");
1116   llvm::Value *IsCompleteObject =
1117     CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1118 
1119   llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1120   llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1121   CGF.Builder.CreateCondBr(IsCompleteObject,
1122                            CallVbaseCtorsBB, SkipVbaseCtorsBB);
1123 
1124   CGF.EmitBlock(CallVbaseCtorsBB);
1125 
1126   // Fill in the vbtable pointers here.
1127   EmitVBPtrStores(CGF, RD);
1128 
1129   // CGF will put the base ctor calls in this basic block for us later.
1130 
1131   return SkipVbaseCtorsBB;
1132 }
1133 
1134 llvm::BasicBlock *
1135 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1136   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1137   assert(IsMostDerivedClass &&
1138          "ctor for a class with virtual bases must have an implicit parameter");
1139   llvm::Value *IsCompleteObject =
1140       CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1141 
1142   llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1143   llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1144   CGF.Builder.CreateCondBr(IsCompleteObject,
1145                            CallVbaseDtorsBB, SkipVbaseDtorsBB);
1146 
1147   CGF.EmitBlock(CallVbaseDtorsBB);
1148   // CGF will put the base dtor calls in this basic block for us later.
1149 
1150   return SkipVbaseDtorsBB;
1151 }
1152 
1153 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1154     CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1155   // In most cases, an override for a vbase virtual method can adjust
1156   // the "this" parameter by applying a constant offset.
1157   // However, this is not enough while a constructor or a destructor of some
1158   // class X is being executed if all the following conditions are met:
1159   //  - X has virtual bases, (1)
1160   //  - X overrides a virtual method M of a vbase Y, (2)
1161   //  - X itself is a vbase of the most derived class.
1162   //
1163   // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1164   // which holds the extra amount of "this" adjustment we must do when we use
1165   // the X vftables (i.e. during X ctor or dtor).
1166   // Outside the ctors and dtors, the values of vtorDisps are zero.
1167 
1168   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1169   typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1170   const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1171   CGBuilderTy &Builder = CGF.Builder;
1172 
1173   unsigned AS = getThisAddress(CGF).getAddressSpace();
1174   llvm::Value *Int8This = nullptr;  // Initialize lazily.
1175 
1176   for (const CXXBaseSpecifier &S : RD->vbases()) {
1177     const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1178     auto I = VBaseMap.find(VBase);
1179     assert(I != VBaseMap.end());
1180     if (!I->second.hasVtorDisp())
1181       continue;
1182 
1183     llvm::Value *VBaseOffset =
1184         GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1185     uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1186 
1187     // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1188     llvm::Value *VtorDispValue = Builder.CreateSub(
1189         VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1190         "vtordisp.value");
1191     VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1192 
1193     if (!Int8This)
1194       Int8This = Builder.CreateBitCast(getThisValue(CGF),
1195                                        CGF.Int8Ty->getPointerTo(AS));
1196     llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1197     // vtorDisp is always the 32-bits before the vbase in the class layout.
1198     VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1199     VtorDispPtr = Builder.CreateBitCast(
1200         VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1201 
1202     Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1203                                CharUnits::fromQuantity(4));
1204   }
1205 }
1206 
1207 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1208                                   const CXXMethodDecl *MD) {
1209   CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1210       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1211   CallingConv ActualCallingConv =
1212       MD->getType()->getAs<FunctionProtoType>()->getCallConv();
1213   return ExpectedCallingConv == ActualCallingConv;
1214 }
1215 
1216 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1217   // There's only one constructor type in this ABI.
1218   CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1219 
1220   // Exported default constructors either have a simple call-site where they use
1221   // the typical calling convention and have a single 'this' pointer for an
1222   // argument -or- they get a wrapper function which appropriately thunks to the
1223   // real default constructor.  This thunk is the default constructor closure.
1224   if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor())
1225     if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1226       llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1227       Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1228       CGM.setGVProperties(Fn, D);
1229     }
1230 }
1231 
1232 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1233                                       const CXXRecordDecl *RD) {
1234   Address This = getThisAddress(CGF);
1235   This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1236   const ASTContext &Context = getContext();
1237   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1238 
1239   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1240   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1241     const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1242     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1243     const ASTRecordLayout &SubobjectLayout =
1244         Context.getASTRecordLayout(VBT->IntroducingObject);
1245     CharUnits Offs = VBT->NonVirtualOffset;
1246     Offs += SubobjectLayout.getVBPtrOffset();
1247     if (VBT->getVBaseWithVPtr())
1248       Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1249     Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1250     llvm::Value *GVPtr =
1251         CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1252     VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1253                                       "vbptr." + VBT->ObjectWithVPtr->getName());
1254     CGF.Builder.CreateStore(GVPtr, VBPtr);
1255   }
1256 }
1257 
1258 CGCXXABI::AddedStructorArgs
1259 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1260                                         SmallVectorImpl<CanQualType> &ArgTys) {
1261   AddedStructorArgs Added;
1262   // TODO: 'for base' flag
1263   if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1264       GD.getDtorType() == Dtor_Deleting) {
1265     // The scalar deleting destructor takes an implicit int parameter.
1266     ArgTys.push_back(getContext().IntTy);
1267     ++Added.Suffix;
1268   }
1269   auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1270   if (!CD)
1271     return Added;
1272 
1273   // All parameters are already in place except is_most_derived, which goes
1274   // after 'this' if it's variadic and last if it's not.
1275 
1276   const CXXRecordDecl *Class = CD->getParent();
1277   const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1278   if (Class->getNumVBases()) {
1279     if (FPT->isVariadic()) {
1280       ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1281       ++Added.Prefix;
1282     } else {
1283       ArgTys.push_back(getContext().IntTy);
1284       ++Added.Suffix;
1285     }
1286   }
1287 
1288   return Added;
1289 }
1290 
1291 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1292                                                  const CXXDestructorDecl *Dtor,
1293                                                  CXXDtorType DT) const {
1294   // Deleting destructor variants are never imported or exported. Give them the
1295   // default storage class.
1296   if (DT == Dtor_Deleting) {
1297     GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1298   } else {
1299     const NamedDecl *ND = Dtor;
1300     CGM.setDLLImportDLLExport(GV, ND);
1301   }
1302 }
1303 
1304 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1305     GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1306   // Internal things are always internal, regardless of attributes. After this,
1307   // we know the thunk is externally visible.
1308   if (Linkage == GVA_Internal)
1309     return llvm::GlobalValue::InternalLinkage;
1310 
1311   switch (DT) {
1312   case Dtor_Base:
1313     // The base destructor most closely tracks the user-declared constructor, so
1314     // we delegate back to the normal declarator case.
1315     return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1316                                            /*isConstantVariable=*/false);
1317   case Dtor_Complete:
1318     // The complete destructor is like an inline function, but it may be
1319     // imported and therefore must be exported as well. This requires changing
1320     // the linkage if a DLL attribute is present.
1321     if (Dtor->hasAttr<DLLExportAttr>())
1322       return llvm::GlobalValue::WeakODRLinkage;
1323     if (Dtor->hasAttr<DLLImportAttr>())
1324       return llvm::GlobalValue::AvailableExternallyLinkage;
1325     return llvm::GlobalValue::LinkOnceODRLinkage;
1326   case Dtor_Deleting:
1327     // Deleting destructors are like inline functions. They have vague linkage
1328     // and are emitted everywhere they are used. They are internal if the class
1329     // is internal.
1330     return llvm::GlobalValue::LinkOnceODRLinkage;
1331   case Dtor_Comdat:
1332     llvm_unreachable("MS C++ ABI does not support comdat dtors");
1333   }
1334   llvm_unreachable("invalid dtor type");
1335 }
1336 
1337 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1338   // The TU defining a dtor is only guaranteed to emit a base destructor.  All
1339   // other destructor variants are delegating thunks.
1340   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1341 }
1342 
1343 CharUnits
1344 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1345   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1346 
1347   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1348     // Complete destructors take a pointer to the complete object as a
1349     // parameter, thus don't need this adjustment.
1350     if (GD.getDtorType() == Dtor_Complete)
1351       return CharUnits();
1352 
1353     // There's no Dtor_Base in vftable but it shares the this adjustment with
1354     // the deleting one, so look it up instead.
1355     GD = GlobalDecl(DD, Dtor_Deleting);
1356   }
1357 
1358   MethodVFTableLocation ML =
1359       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1360   CharUnits Adjustment = ML.VFPtrOffset;
1361 
1362   // Normal virtual instance methods need to adjust from the vfptr that first
1363   // defined the virtual method to the virtual base subobject, but destructors
1364   // do not.  The vector deleting destructor thunk applies this adjustment for
1365   // us if necessary.
1366   if (isa<CXXDestructorDecl>(MD))
1367     Adjustment = CharUnits::Zero();
1368 
1369   if (ML.VBase) {
1370     const ASTRecordLayout &DerivedLayout =
1371         getContext().getASTRecordLayout(MD->getParent());
1372     Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1373   }
1374 
1375   return Adjustment;
1376 }
1377 
1378 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1379     CodeGenFunction &CGF, GlobalDecl GD, Address This,
1380     bool VirtualCall) {
1381   if (!VirtualCall) {
1382     // If the call of a virtual function is not virtual, we just have to
1383     // compensate for the adjustment the virtual function does in its prologue.
1384     CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1385     if (Adjustment.isZero())
1386       return This;
1387 
1388     This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1389     assert(Adjustment.isPositive());
1390     return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1391   }
1392 
1393   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1394 
1395   GlobalDecl LookupGD = GD;
1396   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1397     // Complete dtors take a pointer to the complete object,
1398     // thus don't need adjustment.
1399     if (GD.getDtorType() == Dtor_Complete)
1400       return This;
1401 
1402     // There's only Dtor_Deleting in vftable but it shares the this adjustment
1403     // with the base one, so look up the deleting one instead.
1404     LookupGD = GlobalDecl(DD, Dtor_Deleting);
1405   }
1406   MethodVFTableLocation ML =
1407       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1408 
1409   CharUnits StaticOffset = ML.VFPtrOffset;
1410 
1411   // Base destructors expect 'this' to point to the beginning of the base
1412   // subobject, not the first vfptr that happens to contain the virtual dtor.
1413   // However, we still need to apply the virtual base adjustment.
1414   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1415     StaticOffset = CharUnits::Zero();
1416 
1417   Address Result = This;
1418   if (ML.VBase) {
1419     Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1420 
1421     const CXXRecordDecl *Derived = MD->getParent();
1422     const CXXRecordDecl *VBase = ML.VBase;
1423     llvm::Value *VBaseOffset =
1424       GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1425     llvm::Value *VBasePtr =
1426       CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset);
1427     CharUnits VBaseAlign =
1428       CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1429     Result = Address(VBasePtr, VBaseAlign);
1430   }
1431   if (!StaticOffset.isZero()) {
1432     assert(StaticOffset.isPositive());
1433     Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1434     if (ML.VBase) {
1435       // Non-virtual adjustment might result in a pointer outside the allocated
1436       // object, e.g. if the final overrider class is laid out after the virtual
1437       // base that declares a method in the most derived class.
1438       // FIXME: Update the code that emits this adjustment in thunks prologues.
1439       Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1440     } else {
1441       Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1442     }
1443   }
1444   return Result;
1445 }
1446 
1447 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1448                                                 QualType &ResTy,
1449                                                 FunctionArgList &Params) {
1450   ASTContext &Context = getContext();
1451   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1452   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1453   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1454     auto *IsMostDerived = ImplicitParamDecl::Create(
1455         Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1456         &Context.Idents.get("is_most_derived"), Context.IntTy,
1457         ImplicitParamDecl::Other);
1458     // The 'most_derived' parameter goes second if the ctor is variadic and last
1459     // if it's not.  Dtors can't be variadic.
1460     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1461     if (FPT->isVariadic())
1462       Params.insert(Params.begin() + 1, IsMostDerived);
1463     else
1464       Params.push_back(IsMostDerived);
1465     getStructorImplicitParamDecl(CGF) = IsMostDerived;
1466   } else if (isDeletingDtor(CGF.CurGD)) {
1467     auto *ShouldDelete = ImplicitParamDecl::Create(
1468         Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1469         &Context.Idents.get("should_call_delete"), Context.IntTy,
1470         ImplicitParamDecl::Other);
1471     Params.push_back(ShouldDelete);
1472     getStructorImplicitParamDecl(CGF) = ShouldDelete;
1473   }
1474 }
1475 
1476 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1477   // Naked functions have no prolog.
1478   if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1479     return;
1480 
1481   // Overridden virtual methods of non-primary bases need to adjust the incoming
1482   // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1483   // sizeof(void*) to adjust from B* to C*:
1484   //   struct A { virtual void a(); };
1485   //   struct B { virtual void b(); };
1486   //   struct C : A, B { virtual void b(); };
1487   //
1488   // Leave the value stored in the 'this' alloca unadjusted, so that the
1489   // debugger sees the unadjusted value. Microsoft debuggers require this, and
1490   // will apply the ThisAdjustment in the method type information.
1491   // FIXME: Do something better for DWARF debuggers, which won't expect this,
1492   // without making our codegen depend on debug info settings.
1493   llvm::Value *This = loadIncomingCXXThis(CGF);
1494   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1495   if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1496     CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1497     if (!Adjustment.isZero()) {
1498       unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1499       llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1500                  *thisTy = This->getType();
1501       This = CGF.Builder.CreateBitCast(This, charPtrTy);
1502       assert(Adjustment.isPositive());
1503       This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1504                                                     -Adjustment.getQuantity());
1505       This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1506     }
1507   }
1508   setCXXABIThisValue(CGF, This);
1509 
1510   // If this is a function that the ABI specifies returns 'this', initialize
1511   // the return slot to 'this' at the start of the function.
1512   //
1513   // Unlike the setting of return types, this is done within the ABI
1514   // implementation instead of by clients of CGCXXABI because:
1515   // 1) getThisValue is currently protected
1516   // 2) in theory, an ABI could implement 'this' returns some other way;
1517   //    HasThisReturn only specifies a contract, not the implementation
1518   if (HasThisReturn(CGF.CurGD))
1519     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1520   else if (hasMostDerivedReturn(CGF.CurGD))
1521     CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1522                             CGF.ReturnValue);
1523 
1524   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1525     assert(getStructorImplicitParamDecl(CGF) &&
1526            "no implicit parameter for a constructor with virtual bases?");
1527     getStructorImplicitParamValue(CGF)
1528       = CGF.Builder.CreateLoad(
1529           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1530           "is_most_derived");
1531   }
1532 
1533   if (isDeletingDtor(CGF.CurGD)) {
1534     assert(getStructorImplicitParamDecl(CGF) &&
1535            "no implicit parameter for a deleting destructor?");
1536     getStructorImplicitParamValue(CGF)
1537       = CGF.Builder.CreateLoad(
1538           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1539           "should_call_delete");
1540   }
1541 }
1542 
1543 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::addImplicitConstructorArgs(
1544     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1545     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1546   assert(Type == Ctor_Complete || Type == Ctor_Base);
1547 
1548   // Check if we need a 'most_derived' parameter.
1549   if (!D->getParent()->getNumVBases())
1550     return AddedStructorArgs{};
1551 
1552   // Add the 'most_derived' argument second if we are variadic or last if not.
1553   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1554   llvm::Value *MostDerivedArg;
1555   if (Delegating) {
1556     MostDerivedArg = getStructorImplicitParamValue(CGF);
1557   } else {
1558     MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1559   }
1560   RValue RV = RValue::get(MostDerivedArg);
1561   if (FPT->isVariadic()) {
1562     Args.insert(Args.begin() + 1, CallArg(RV, getContext().IntTy));
1563     return AddedStructorArgs::prefix(1);
1564   }
1565   Args.add(RV, getContext().IntTy);
1566   return AddedStructorArgs::suffix(1);
1567 }
1568 
1569 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1570                                          const CXXDestructorDecl *DD,
1571                                          CXXDtorType Type, bool ForVirtualBase,
1572                                          bool Delegating, Address This) {
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(),
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, const CXXMemberCallExpr *CE) {
1904   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1905   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1906 
1907   // We have only one destructor in the vftable but can get both behaviors
1908   // by passing an implicit int parameter.
1909   GlobalDecl GD(Dtor, Dtor_Deleting);
1910   const CGFunctionInfo *FInfo =
1911       &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1912   llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1913   CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1914 
1915   ASTContext &Context = getContext();
1916   llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1917       llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1918       DtorType == Dtor_Deleting);
1919 
1920   This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1921   RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(),
1922                                         ImplicitParam, Context.IntTy, CE);
1923   return RV.getScalarVal();
1924 }
1925 
1926 const VBTableGlobals &
1927 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1928   // At this layer, we can key the cache off of a single class, which is much
1929   // easier than caching each vbtable individually.
1930   llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1931   bool Added;
1932   std::tie(Entry, Added) =
1933       VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1934   VBTableGlobals &VBGlobals = Entry->second;
1935   if (!Added)
1936     return VBGlobals;
1937 
1938   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1939   VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1940 
1941   // Cache the globals for all vbtables so we don't have to recompute the
1942   // mangled names.
1943   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1944   for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1945                                       E = VBGlobals.VBTables->end();
1946        I != E; ++I) {
1947     VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1948   }
1949 
1950   return VBGlobals;
1951 }
1952 
1953 llvm::Function *
1954 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1955                                         const MethodVFTableLocation &ML) {
1956   assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1957          "can't form pointers to ctors or virtual dtors");
1958 
1959   // Calculate the mangled name.
1960   SmallString<256> ThunkName;
1961   llvm::raw_svector_ostream Out(ThunkName);
1962   getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
1963 
1964   // If the thunk has been generated previously, just return it.
1965   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1966     return cast<llvm::Function>(GV);
1967 
1968   // Create the llvm::Function.
1969   const CGFunctionInfo &FnInfo =
1970       CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
1971   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1972   llvm::Function *ThunkFn =
1973       llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1974                              ThunkName.str(), &CGM.getModule());
1975   assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1976 
1977   ThunkFn->setLinkage(MD->isExternallyVisible()
1978                           ? llvm::GlobalValue::LinkOnceODRLinkage
1979                           : llvm::GlobalValue::InternalLinkage);
1980   if (MD->isExternallyVisible())
1981     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1982 
1983   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1984   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1985 
1986   // Add the "thunk" attribute so that LLVM knows that the return type is
1987   // meaningless. These thunks can be used to call functions with differing
1988   // return types, and the caller is required to cast the prototype
1989   // appropriately to extract the correct value.
1990   ThunkFn->addFnAttr("thunk");
1991 
1992   // These thunks can be compared, so they are not unnamed.
1993   ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
1994 
1995   // Start codegen.
1996   CodeGenFunction CGF(CGM);
1997   CGF.CurGD = GlobalDecl(MD);
1998   CGF.CurFuncIsThunk = true;
1999 
2000   // Build FunctionArgs, but only include the implicit 'this' parameter
2001   // declaration.
2002   FunctionArgList FunctionArgs;
2003   buildThisParam(CGF, FunctionArgs);
2004 
2005   // Start defining the function.
2006   CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2007                     FunctionArgs, MD->getLocation(), SourceLocation());
2008   setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2009 
2010   // Load the vfptr and then callee from the vftable.  The callee should have
2011   // adjusted 'this' so that the vfptr is at offset zero.
2012   llvm::Value *VTable = CGF.GetVTablePtr(
2013       getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
2014 
2015   llvm::Value *VFuncPtr =
2016       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
2017   llvm::Value *Callee =
2018     CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
2019 
2020   CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2021 
2022   return ThunkFn;
2023 }
2024 
2025 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2026   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2027   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2028     const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2029     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2030     if (GV->isDeclaration())
2031       emitVBTableDefinition(*VBT, RD, GV);
2032   }
2033 }
2034 
2035 llvm::GlobalVariable *
2036 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2037                                   llvm::GlobalVariable::LinkageTypes Linkage) {
2038   SmallString<256> OutName;
2039   llvm::raw_svector_ostream Out(OutName);
2040   getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2041   StringRef Name = OutName.str();
2042 
2043   llvm::ArrayType *VBTableType =
2044       llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2045 
2046   assert(!CGM.getModule().getNamedGlobal(Name) &&
2047          "vbtable with this name already exists: mangling bug?");
2048   CharUnits Alignment =
2049       CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2050   llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2051       Name, VBTableType, Linkage, Alignment.getQuantity());
2052   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2053 
2054   if (RD->hasAttr<DLLImportAttr>())
2055     GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2056   else if (RD->hasAttr<DLLExportAttr>())
2057     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2058 
2059   if (!GV->hasExternalLinkage())
2060     emitVBTableDefinition(VBT, RD, GV);
2061 
2062   return GV;
2063 }
2064 
2065 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2066                                             const CXXRecordDecl *RD,
2067                                             llvm::GlobalVariable *GV) const {
2068   const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2069 
2070   assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2071          "should only emit vbtables for classes with vbtables");
2072 
2073   const ASTRecordLayout &BaseLayout =
2074       getContext().getASTRecordLayout(VBT.IntroducingObject);
2075   const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2076 
2077   SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2078                                            nullptr);
2079 
2080   // The offset from ObjectWithVPtr's vbptr to itself always leads.
2081   CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2082   Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2083 
2084   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2085   for (const auto &I : ObjectWithVPtr->vbases()) {
2086     const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2087     CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2088     assert(!Offset.isNegative());
2089 
2090     // Make it relative to the subobject vbptr.
2091     CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2092     if (VBT.getVBaseWithVPtr())
2093       CompleteVBPtrOffset +=
2094           DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2095     Offset -= CompleteVBPtrOffset;
2096 
2097     unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2098     assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2099     Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2100   }
2101 
2102   assert(Offsets.size() ==
2103          cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2104                                ->getElementType())->getNumElements());
2105   llvm::ArrayType *VBTableType =
2106     llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2107   llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2108   GV->setInitializer(Init);
2109 
2110   if (RD->hasAttr<DLLImportAttr>())
2111     GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2112 }
2113 
2114 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2115                                                     Address This,
2116                                                     const ThisAdjustment &TA) {
2117   if (TA.isEmpty())
2118     return This.getPointer();
2119 
2120   This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2121 
2122   llvm::Value *V;
2123   if (TA.Virtual.isEmpty()) {
2124     V = This.getPointer();
2125   } else {
2126     assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2127     // Adjust the this argument based on the vtordisp value.
2128     Address VtorDispPtr =
2129         CGF.Builder.CreateConstInBoundsByteGEP(This,
2130                  CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2131     VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2132     llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2133     V = CGF.Builder.CreateGEP(This.getPointer(),
2134                               CGF.Builder.CreateNeg(VtorDisp));
2135 
2136     // Unfortunately, having applied the vtordisp means that we no
2137     // longer really have a known alignment for the vbptr step.
2138     // We'll assume the vbptr is pointer-aligned.
2139 
2140     if (TA.Virtual.Microsoft.VBPtrOffset) {
2141       // If the final overrider is defined in a virtual base other than the one
2142       // that holds the vfptr, we have to use a vtordispex thunk which looks up
2143       // the vbtable of the derived class.
2144       assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2145       assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2146       llvm::Value *VBPtr;
2147       llvm::Value *VBaseOffset =
2148           GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2149                                   -TA.Virtual.Microsoft.VBPtrOffset,
2150                                   TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2151       V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2152     }
2153   }
2154 
2155   if (TA.NonVirtual) {
2156     // Non-virtual adjustment might result in a pointer outside the allocated
2157     // object, e.g. if the final overrider class is laid out after the virtual
2158     // base that declares a method in the most derived class.
2159     V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2160   }
2161 
2162   // Don't need to bitcast back, the call CodeGen will handle this.
2163   return V;
2164 }
2165 
2166 llvm::Value *
2167 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2168                                          const ReturnAdjustment &RA) {
2169   if (RA.isEmpty())
2170     return Ret.getPointer();
2171 
2172   auto OrigTy = Ret.getType();
2173   Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2174 
2175   llvm::Value *V = Ret.getPointer();
2176   if (RA.Virtual.Microsoft.VBIndex) {
2177     assert(RA.Virtual.Microsoft.VBIndex > 0);
2178     int32_t IntSize = CGF.getIntSize().getQuantity();
2179     llvm::Value *VBPtr;
2180     llvm::Value *VBaseOffset =
2181         GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2182                                 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2183     V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2184   }
2185 
2186   if (RA.NonVirtual)
2187     V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2188 
2189   // Cast back to the original type.
2190   return CGF.Builder.CreateBitCast(V, OrigTy);
2191 }
2192 
2193 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2194                                    QualType elementType) {
2195   // Microsoft seems to completely ignore the possibility of a
2196   // two-argument usual deallocation function.
2197   return elementType.isDestructedType();
2198 }
2199 
2200 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2201   // Microsoft seems to completely ignore the possibility of a
2202   // two-argument usual deallocation function.
2203   return expr->getAllocatedType().isDestructedType();
2204 }
2205 
2206 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2207   // The array cookie is always a size_t; we then pad that out to the
2208   // alignment of the element type.
2209   ASTContext &Ctx = getContext();
2210   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2211                   Ctx.getTypeAlignInChars(type));
2212 }
2213 
2214 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2215                                                   Address allocPtr,
2216                                                   CharUnits cookieSize) {
2217   Address numElementsPtr =
2218     CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2219   return CGF.Builder.CreateLoad(numElementsPtr);
2220 }
2221 
2222 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2223                                                Address newPtr,
2224                                                llvm::Value *numElements,
2225                                                const CXXNewExpr *expr,
2226                                                QualType elementType) {
2227   assert(requiresArrayCookie(expr));
2228 
2229   // The size of the cookie.
2230   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2231 
2232   // Compute an offset to the cookie.
2233   Address cookiePtr = newPtr;
2234 
2235   // Write the number of elements into the appropriate slot.
2236   Address numElementsPtr
2237     = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2238   CGF.Builder.CreateStore(numElements, numElementsPtr);
2239 
2240   // Finally, compute a pointer to the actual data buffer by skipping
2241   // over the cookie completely.
2242   return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2243 }
2244 
2245 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2246                                         llvm::FunctionCallee Dtor,
2247                                         llvm::Constant *Addr) {
2248   // Create a function which calls the destructor.
2249   llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2250 
2251   // extern "C" int __tlregdtor(void (*f)(void));
2252   llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2253       CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
2254 
2255   llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2256       TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2257   if (llvm::Function *TLRegDtorFn =
2258           dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2259     TLRegDtorFn->setDoesNotThrow();
2260 
2261   CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2262 }
2263 
2264 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2265                                          llvm::FunctionCallee Dtor,
2266                                          llvm::Constant *Addr) {
2267   if (D.isNoDestroy(CGM.getContext()))
2268     return;
2269 
2270   if (D.getTLSKind())
2271     return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2272 
2273   // The default behavior is to use atexit.
2274   CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2275 }
2276 
2277 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2278     CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2279     ArrayRef<llvm::Function *> CXXThreadLocalInits,
2280     ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2281   if (CXXThreadLocalInits.empty())
2282     return;
2283 
2284   CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2285                                   llvm::Triple::x86
2286                               ? "/include:___dyn_tls_init@12"
2287                               : "/include:__dyn_tls_init");
2288 
2289   // This will create a GV in the .CRT$XDU section.  It will point to our
2290   // initialization function.  The CRT will call all of these function
2291   // pointers at start-up time and, eventually, at thread-creation time.
2292   auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2293     llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2294         CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
2295         llvm::GlobalVariable::InternalLinkage, InitFunc,
2296         Twine(InitFunc->getName(), "$initializer$"));
2297     InitFuncPtr->setSection(".CRT$XDU");
2298     // This variable has discardable linkage, we have to add it to @llvm.used to
2299     // ensure it won't get discarded.
2300     CGM.addUsedGlobal(InitFuncPtr);
2301     return InitFuncPtr;
2302   };
2303 
2304   std::vector<llvm::Function *> NonComdatInits;
2305   for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2306     llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2307         CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2308     llvm::Function *F = CXXThreadLocalInits[I];
2309 
2310     // If the GV is already in a comdat group, then we have to join it.
2311     if (llvm::Comdat *C = GV->getComdat())
2312       AddToXDU(F)->setComdat(C);
2313     else
2314       NonComdatInits.push_back(F);
2315   }
2316 
2317   if (!NonComdatInits.empty()) {
2318     llvm::FunctionType *FTy =
2319         llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2320     llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2321         FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2322         SourceLocation(), /*TLS=*/true);
2323     CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2324 
2325     AddToXDU(InitFunc);
2326   }
2327 }
2328 
2329 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2330                                                      const VarDecl *VD,
2331                                                      QualType LValType) {
2332   CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2333   return LValue();
2334 }
2335 
2336 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2337   StringRef VarName("_Init_thread_epoch");
2338   CharUnits Align = CGM.getIntAlign();
2339   if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2340     return ConstantAddress(GV, Align);
2341   auto *GV = new llvm::GlobalVariable(
2342       CGM.getModule(), CGM.IntTy,
2343       /*Constant=*/false, llvm::GlobalVariable::ExternalLinkage,
2344       /*Initializer=*/nullptr, VarName,
2345       /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2346   GV->setAlignment(Align.getQuantity());
2347   return ConstantAddress(GV, Align);
2348 }
2349 
2350 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2351   llvm::FunctionType *FTy =
2352       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2353                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2354   return CGM.CreateRuntimeFunction(
2355       FTy, "_Init_thread_header",
2356       llvm::AttributeList::get(CGM.getLLVMContext(),
2357                                llvm::AttributeList::FunctionIndex,
2358                                llvm::Attribute::NoUnwind),
2359       /*Local=*/true);
2360 }
2361 
2362 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2363   llvm::FunctionType *FTy =
2364       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2365                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2366   return CGM.CreateRuntimeFunction(
2367       FTy, "_Init_thread_footer",
2368       llvm::AttributeList::get(CGM.getLLVMContext(),
2369                                llvm::AttributeList::FunctionIndex,
2370                                llvm::Attribute::NoUnwind),
2371       /*Local=*/true);
2372 }
2373 
2374 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2375   llvm::FunctionType *FTy =
2376       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2377                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2378   return CGM.CreateRuntimeFunction(
2379       FTy, "_Init_thread_abort",
2380       llvm::AttributeList::get(CGM.getLLVMContext(),
2381                                llvm::AttributeList::FunctionIndex,
2382                                llvm::Attribute::NoUnwind),
2383       /*Local=*/true);
2384 }
2385 
2386 namespace {
2387 struct ResetGuardBit final : EHScopeStack::Cleanup {
2388   Address Guard;
2389   unsigned GuardNum;
2390   ResetGuardBit(Address Guard, unsigned GuardNum)
2391       : Guard(Guard), GuardNum(GuardNum) {}
2392 
2393   void Emit(CodeGenFunction &CGF, Flags flags) override {
2394     // Reset the bit in the mask so that the static variable may be
2395     // reinitialized.
2396     CGBuilderTy &Builder = CGF.Builder;
2397     llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2398     llvm::ConstantInt *Mask =
2399         llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2400     Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2401   }
2402 };
2403 
2404 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2405   llvm::Value *Guard;
2406   CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2407 
2408   void Emit(CodeGenFunction &CGF, Flags flags) override {
2409     // Calling _Init_thread_abort will reset the guard's state.
2410     CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2411   }
2412 };
2413 }
2414 
2415 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2416                                       llvm::GlobalVariable *GV,
2417                                       bool PerformInit) {
2418   // MSVC only uses guards for static locals.
2419   if (!D.isStaticLocal()) {
2420     assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2421     // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2422     llvm::Function *F = CGF.CurFn;
2423     F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2424     F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2425     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2426     return;
2427   }
2428 
2429   bool ThreadlocalStatic = D.getTLSKind();
2430   bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2431 
2432   // Thread-safe static variables which aren't thread-specific have a
2433   // per-variable guard.
2434   bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2435 
2436   CGBuilderTy &Builder = CGF.Builder;
2437   llvm::IntegerType *GuardTy = CGF.Int32Ty;
2438   llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2439   CharUnits GuardAlign = CharUnits::fromQuantity(4);
2440 
2441   // Get the guard variable for this function if we have one already.
2442   GuardInfo *GI = nullptr;
2443   if (ThreadlocalStatic)
2444     GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2445   else if (!ThreadsafeStatic)
2446     GI = &GuardVariableMap[D.getDeclContext()];
2447 
2448   llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2449   unsigned GuardNum;
2450   if (D.isExternallyVisible()) {
2451     // Externally visible variables have to be numbered in Sema to properly
2452     // handle unreachable VarDecls.
2453     GuardNum = getContext().getStaticLocalNumber(&D);
2454     assert(GuardNum > 0);
2455     GuardNum--;
2456   } else if (HasPerVariableGuard) {
2457     GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2458   } else {
2459     // Non-externally visible variables are numbered here in CodeGen.
2460     GuardNum = GI->BitIndex++;
2461   }
2462 
2463   if (!HasPerVariableGuard && GuardNum >= 32) {
2464     if (D.isExternallyVisible())
2465       ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2466     GuardNum %= 32;
2467     GuardVar = nullptr;
2468   }
2469 
2470   if (!GuardVar) {
2471     // Mangle the name for the guard.
2472     SmallString<256> GuardName;
2473     {
2474       llvm::raw_svector_ostream Out(GuardName);
2475       if (HasPerVariableGuard)
2476         getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2477                                                                Out);
2478       else
2479         getMangleContext().mangleStaticGuardVariable(&D, Out);
2480     }
2481 
2482     // Create the guard variable with a zero-initializer. Just absorb linkage,
2483     // visibility and dll storage class from the guarded variable.
2484     GuardVar =
2485         new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2486                                  GV->getLinkage(), Zero, GuardName.str());
2487     GuardVar->setVisibility(GV->getVisibility());
2488     GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2489     GuardVar->setAlignment(GuardAlign.getQuantity());
2490     if (GuardVar->isWeakForLinker())
2491       GuardVar->setComdat(
2492           CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2493     if (D.getTLSKind())
2494       GuardVar->setThreadLocal(true);
2495     if (GI && !HasPerVariableGuard)
2496       GI->Guard = GuardVar;
2497   }
2498 
2499   ConstantAddress GuardAddr(GuardVar, GuardAlign);
2500 
2501   assert(GuardVar->getLinkage() == GV->getLinkage() &&
2502          "static local from the same function had different linkage");
2503 
2504   if (!HasPerVariableGuard) {
2505     // Pseudo code for the test:
2506     // if (!(GuardVar & MyGuardBit)) {
2507     //   GuardVar |= MyGuardBit;
2508     //   ... initialize the object ...;
2509     // }
2510 
2511     // Test our bit from the guard variable.
2512     llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2513     llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2514     llvm::Value *NeedsInit =
2515         Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2516     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2517     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2518     CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2519                                  CodeGenFunction::GuardKind::VariableGuard, &D);
2520 
2521     // Set our bit in the guard variable and emit the initializer and add a global
2522     // destructor if appropriate.
2523     CGF.EmitBlock(InitBlock);
2524     Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2525     CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2526     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2527     CGF.PopCleanupBlock();
2528     Builder.CreateBr(EndBlock);
2529 
2530     // Continue.
2531     CGF.EmitBlock(EndBlock);
2532   } else {
2533     // Pseudo code for the test:
2534     // if (TSS > _Init_thread_epoch) {
2535     //   _Init_thread_header(&TSS);
2536     //   if (TSS == -1) {
2537     //     ... initialize the object ...;
2538     //     _Init_thread_footer(&TSS);
2539     //   }
2540     // }
2541     //
2542     // The algorithm is almost identical to what can be found in the appendix
2543     // found in N2325.
2544 
2545     // This BasicBLock determines whether or not we have any work to do.
2546     llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2547     FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2548     llvm::LoadInst *InitThreadEpoch =
2549         Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2550     llvm::Value *IsUninitialized =
2551         Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2552     llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2553     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2554     CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2555                                  CodeGenFunction::GuardKind::VariableGuard, &D);
2556 
2557     // This BasicBlock attempts to determine whether or not this thread is
2558     // responsible for doing the initialization.
2559     CGF.EmitBlock(AttemptInitBlock);
2560     CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2561                                 GuardAddr.getPointer());
2562     llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2563     SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2564     llvm::Value *ShouldDoInit =
2565         Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2566     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2567     Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2568 
2569     // Ok, we ended up getting selected as the initializing thread.
2570     CGF.EmitBlock(InitBlock);
2571     CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2572     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2573     CGF.PopCleanupBlock();
2574     CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2575                                 GuardAddr.getPointer());
2576     Builder.CreateBr(EndBlock);
2577 
2578     CGF.EmitBlock(EndBlock);
2579   }
2580 }
2581 
2582 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2583   // Null-ness for function memptrs only depends on the first field, which is
2584   // the function pointer.  The rest don't matter, so we can zero initialize.
2585   if (MPT->isMemberFunctionPointer())
2586     return true;
2587 
2588   // The virtual base adjustment field is always -1 for null, so if we have one
2589   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
2590   // valid field offset.
2591   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2592   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2593   return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2594           RD->nullFieldOffsetIsZero());
2595 }
2596 
2597 llvm::Type *
2598 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2599   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2600   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2601   llvm::SmallVector<llvm::Type *, 4> fields;
2602   if (MPT->isMemberFunctionPointer())
2603     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
2604   else
2605     fields.push_back(CGM.IntTy);  // FieldOffset
2606 
2607   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2608                                           Inheritance))
2609     fields.push_back(CGM.IntTy);
2610   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2611     fields.push_back(CGM.IntTy);
2612   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2613     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
2614 
2615   if (fields.size() == 1)
2616     return fields[0];
2617   return llvm::StructType::get(CGM.getLLVMContext(), fields);
2618 }
2619 
2620 void MicrosoftCXXABI::
2621 GetNullMemberPointerFields(const MemberPointerType *MPT,
2622                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2623   assert(fields.empty());
2624   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2625   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2626   if (MPT->isMemberFunctionPointer()) {
2627     // FunctionPointerOrVirtualThunk
2628     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2629   } else {
2630     if (RD->nullFieldOffsetIsZero())
2631       fields.push_back(getZeroInt());  // FieldOffset
2632     else
2633       fields.push_back(getAllOnesInt());  // FieldOffset
2634   }
2635 
2636   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2637                                           Inheritance))
2638     fields.push_back(getZeroInt());
2639   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2640     fields.push_back(getZeroInt());
2641   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2642     fields.push_back(getAllOnesInt());
2643 }
2644 
2645 llvm::Constant *
2646 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2647   llvm::SmallVector<llvm::Constant *, 4> fields;
2648   GetNullMemberPointerFields(MPT, fields);
2649   if (fields.size() == 1)
2650     return fields[0];
2651   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2652   assert(Res->getType() == ConvertMemberPointerType(MPT));
2653   return Res;
2654 }
2655 
2656 llvm::Constant *
2657 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2658                                        bool IsMemberFunction,
2659                                        const CXXRecordDecl *RD,
2660                                        CharUnits NonVirtualBaseAdjustment,
2661                                        unsigned VBTableIndex) {
2662   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2663 
2664   // Single inheritance class member pointer are represented as scalars instead
2665   // of aggregates.
2666   if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2667     return FirstField;
2668 
2669   llvm::SmallVector<llvm::Constant *, 4> fields;
2670   fields.push_back(FirstField);
2671 
2672   if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2673     fields.push_back(llvm::ConstantInt::get(
2674       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2675 
2676   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2677     CharUnits Offs = CharUnits::Zero();
2678     if (VBTableIndex)
2679       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2680     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2681   }
2682 
2683   // The rest of the fields are adjusted by conversions to a more derived class.
2684   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2685     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2686 
2687   return llvm::ConstantStruct::getAnon(fields);
2688 }
2689 
2690 llvm::Constant *
2691 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2692                                        CharUnits offset) {
2693   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2694   if (RD->getMSInheritanceModel() ==
2695       MSInheritanceAttr::Keyword_virtual_inheritance)
2696     offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2697   llvm::Constant *FirstField =
2698     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2699   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2700                                CharUnits::Zero(), /*VBTableIndex=*/0);
2701 }
2702 
2703 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2704                                                    QualType MPType) {
2705   const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2706   const ValueDecl *MPD = MP.getMemberPointerDecl();
2707   if (!MPD)
2708     return EmitNullMemberPointer(DstTy);
2709 
2710   ASTContext &Ctx = getContext();
2711   ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2712 
2713   llvm::Constant *C;
2714   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2715     C = EmitMemberFunctionPointer(MD);
2716   } else {
2717     CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2718     C = EmitMemberDataPointer(DstTy, FieldOffset);
2719   }
2720 
2721   if (!MemberPointerPath.empty()) {
2722     const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2723     const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2724     const MemberPointerType *SrcTy =
2725         Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2726             ->castAs<MemberPointerType>();
2727 
2728     bool DerivedMember = MP.isMemberPointerToDerivedMember();
2729     SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2730     const CXXRecordDecl *PrevRD = SrcRD;
2731     for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2732       const CXXRecordDecl *Base = nullptr;
2733       const CXXRecordDecl *Derived = nullptr;
2734       if (DerivedMember) {
2735         Base = PathElem;
2736         Derived = PrevRD;
2737       } else {
2738         Base = PrevRD;
2739         Derived = PathElem;
2740       }
2741       for (const CXXBaseSpecifier &BS : Derived->bases())
2742         if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2743             Base->getCanonicalDecl())
2744           DerivedToBasePath.push_back(&BS);
2745       PrevRD = PathElem;
2746     }
2747     assert(DerivedToBasePath.size() == MemberPointerPath.size());
2748 
2749     CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2750                                 : CK_BaseToDerivedMemberPointer;
2751     C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2752                                     DerivedToBasePath.end(), C);
2753   }
2754   return C;
2755 }
2756 
2757 llvm::Constant *
2758 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2759   assert(MD->isInstance() && "Member function must not be static!");
2760 
2761   CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2762   const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2763   CodeGenTypes &Types = CGM.getTypes();
2764 
2765   unsigned VBTableIndex = 0;
2766   llvm::Constant *FirstField;
2767   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2768   if (!MD->isVirtual()) {
2769     llvm::Type *Ty;
2770     // Check whether the function has a computable LLVM signature.
2771     if (Types.isFuncTypeConvertible(FPT)) {
2772       // The function has a computable LLVM signature; use the correct type.
2773       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2774     } else {
2775       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2776       // function type is incomplete.
2777       Ty = CGM.PtrDiffTy;
2778     }
2779     FirstField = CGM.GetAddrOfFunction(MD, Ty);
2780   } else {
2781     auto &VTableContext = CGM.getMicrosoftVTableContext();
2782     MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2783     FirstField = EmitVirtualMemPtrThunk(MD, ML);
2784     // Include the vfptr adjustment if the method is in a non-primary vftable.
2785     NonVirtualBaseAdjustment += ML.VFPtrOffset;
2786     if (ML.VBase)
2787       VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2788   }
2789 
2790   if (VBTableIndex == 0 &&
2791       RD->getMSInheritanceModel() ==
2792           MSInheritanceAttr::Keyword_virtual_inheritance)
2793     NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2794 
2795   // The rest of the fields are common with data member pointers.
2796   FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2797   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2798                                NonVirtualBaseAdjustment, VBTableIndex);
2799 }
2800 
2801 /// Member pointers are the same if they're either bitwise identical *or* both
2802 /// null.  Null-ness for function members is determined by the first field,
2803 /// while for data member pointers we must compare all fields.
2804 llvm::Value *
2805 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2806                                              llvm::Value *L,
2807                                              llvm::Value *R,
2808                                              const MemberPointerType *MPT,
2809                                              bool Inequality) {
2810   CGBuilderTy &Builder = CGF.Builder;
2811 
2812   // Handle != comparisons by switching the sense of all boolean operations.
2813   llvm::ICmpInst::Predicate Eq;
2814   llvm::Instruction::BinaryOps And, Or;
2815   if (Inequality) {
2816     Eq = llvm::ICmpInst::ICMP_NE;
2817     And = llvm::Instruction::Or;
2818     Or = llvm::Instruction::And;
2819   } else {
2820     Eq = llvm::ICmpInst::ICMP_EQ;
2821     And = llvm::Instruction::And;
2822     Or = llvm::Instruction::Or;
2823   }
2824 
2825   // If this is a single field member pointer (single inheritance), this is a
2826   // single icmp.
2827   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2828   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2829   if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2830                                          Inheritance))
2831     return Builder.CreateICmp(Eq, L, R);
2832 
2833   // Compare the first field.
2834   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2835   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2836   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2837 
2838   // Compare everything other than the first field.
2839   llvm::Value *Res = nullptr;
2840   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2841   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2842     llvm::Value *LF = Builder.CreateExtractValue(L, I);
2843     llvm::Value *RF = Builder.CreateExtractValue(R, I);
2844     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2845     if (Res)
2846       Res = Builder.CreateBinOp(And, Res, Cmp);
2847     else
2848       Res = Cmp;
2849   }
2850 
2851   // Check if the first field is 0 if this is a function pointer.
2852   if (MPT->isMemberFunctionPointer()) {
2853     // (l1 == r1 && ...) || l0 == 0
2854     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2855     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2856     Res = Builder.CreateBinOp(Or, Res, IsZero);
2857   }
2858 
2859   // Combine the comparison of the first field, which must always be true for
2860   // this comparison to succeeed.
2861   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2862 }
2863 
2864 llvm::Value *
2865 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2866                                             llvm::Value *MemPtr,
2867                                             const MemberPointerType *MPT) {
2868   CGBuilderTy &Builder = CGF.Builder;
2869   llvm::SmallVector<llvm::Constant *, 4> fields;
2870   // We only need one field for member functions.
2871   if (MPT->isMemberFunctionPointer())
2872     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2873   else
2874     GetNullMemberPointerFields(MPT, fields);
2875   assert(!fields.empty());
2876   llvm::Value *FirstField = MemPtr;
2877   if (MemPtr->getType()->isStructTy())
2878     FirstField = Builder.CreateExtractValue(MemPtr, 0);
2879   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2880 
2881   // For function member pointers, we only need to test the function pointer
2882   // field.  The other fields if any can be garbage.
2883   if (MPT->isMemberFunctionPointer())
2884     return Res;
2885 
2886   // Otherwise, emit a series of compares and combine the results.
2887   for (int I = 1, E = fields.size(); I < E; ++I) {
2888     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2889     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2890     Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2891   }
2892   return Res;
2893 }
2894 
2895 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2896                                                   llvm::Constant *Val) {
2897   // Function pointers are null if the pointer in the first field is null.
2898   if (MPT->isMemberFunctionPointer()) {
2899     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2900       Val->getAggregateElement(0U) : Val;
2901     return FirstField->isNullValue();
2902   }
2903 
2904   // If it's not a function pointer and it's zero initializable, we can easily
2905   // check zero.
2906   if (isZeroInitializable(MPT) && Val->isNullValue())
2907     return true;
2908 
2909   // Otherwise, break down all the fields for comparison.  Hopefully these
2910   // little Constants are reused, while a big null struct might not be.
2911   llvm::SmallVector<llvm::Constant *, 4> Fields;
2912   GetNullMemberPointerFields(MPT, Fields);
2913   if (Fields.size() == 1) {
2914     assert(Val->getType()->isIntegerTy());
2915     return Val == Fields[0];
2916   }
2917 
2918   unsigned I, E;
2919   for (I = 0, E = Fields.size(); I != E; ++I) {
2920     if (Val->getAggregateElement(I) != Fields[I])
2921       break;
2922   }
2923   return I == E;
2924 }
2925 
2926 llvm::Value *
2927 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2928                                          Address This,
2929                                          llvm::Value *VBPtrOffset,
2930                                          llvm::Value *VBTableOffset,
2931                                          llvm::Value **VBPtrOut) {
2932   CGBuilderTy &Builder = CGF.Builder;
2933   // Load the vbtable pointer from the vbptr in the instance.
2934   This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
2935   llvm::Value *VBPtr =
2936     Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
2937   if (VBPtrOut) *VBPtrOut = VBPtr;
2938   VBPtr = Builder.CreateBitCast(VBPtr,
2939             CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
2940 
2941   CharUnits VBPtrAlign;
2942   if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
2943     VBPtrAlign = This.getAlignment().alignmentAtOffset(
2944                                    CharUnits::fromQuantity(CI->getSExtValue()));
2945   } else {
2946     VBPtrAlign = CGF.getPointerAlign();
2947   }
2948 
2949   llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
2950 
2951   // Translate from byte offset to table index. It improves analyzability.
2952   llvm::Value *VBTableIndex = Builder.CreateAShr(
2953       VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2954       "vbtindex", /*isExact=*/true);
2955 
2956   // Load an i32 offset from the vb-table.
2957   llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2958   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2959   return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
2960                                    "vbase_offs");
2961 }
2962 
2963 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2964 // it.
2965 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2966     CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2967     Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2968   CGBuilderTy &Builder = CGF.Builder;
2969   Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
2970   llvm::BasicBlock *OriginalBB = nullptr;
2971   llvm::BasicBlock *SkipAdjustBB = nullptr;
2972   llvm::BasicBlock *VBaseAdjustBB = nullptr;
2973 
2974   // In the unspecified inheritance model, there might not be a vbtable at all,
2975   // in which case we need to skip the virtual base lookup.  If there is a
2976   // vbtable, the first entry is a no-op entry that gives back the original
2977   // base, so look for a virtual base adjustment offset of zero.
2978   if (VBPtrOffset) {
2979     OriginalBB = Builder.GetInsertBlock();
2980     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2981     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2982     llvm::Value *IsVirtual =
2983       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2984                            "memptr.is_vbase");
2985     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2986     CGF.EmitBlock(VBaseAdjustBB);
2987   }
2988 
2989   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2990   // know the vbptr offset.
2991   if (!VBPtrOffset) {
2992     CharUnits offs = CharUnits::Zero();
2993     if (!RD->hasDefinition()) {
2994       DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2995       unsigned DiagID = Diags.getCustomDiagID(
2996           DiagnosticsEngine::Error,
2997           "member pointer representation requires a "
2998           "complete class type for %0 to perform this expression");
2999       Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3000     } else if (RD->getNumVBases())
3001       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3002     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3003   }
3004   llvm::Value *VBPtr = nullptr;
3005   llvm::Value *VBaseOffs =
3006     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3007   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
3008 
3009   // Merge control flow with the case where we didn't have to adjust.
3010   if (VBaseAdjustBB) {
3011     Builder.CreateBr(SkipAdjustBB);
3012     CGF.EmitBlock(SkipAdjustBB);
3013     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3014     Phi->addIncoming(Base.getPointer(), OriginalBB);
3015     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3016     return Phi;
3017   }
3018   return AdjustedBase;
3019 }
3020 
3021 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3022     CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3023     const MemberPointerType *MPT) {
3024   assert(MPT->isMemberDataPointer());
3025   unsigned AS = Base.getAddressSpace();
3026   llvm::Type *PType =
3027       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3028   CGBuilderTy &Builder = CGF.Builder;
3029   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3030   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
3031 
3032   // Extract the fields we need, regardless of model.  We'll apply them if we
3033   // have them.
3034   llvm::Value *FieldOffset = MemPtr;
3035   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3036   llvm::Value *VBPtrOffset = nullptr;
3037   if (MemPtr->getType()->isStructTy()) {
3038     // We need to extract values.
3039     unsigned I = 0;
3040     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3041     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
3042       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3043     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
3044       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3045   }
3046 
3047   llvm::Value *Addr;
3048   if (VirtualBaseAdjustmentOffset) {
3049     Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3050                              VBPtrOffset);
3051   } else {
3052     Addr = Base.getPointer();
3053   }
3054 
3055   // Cast to char*.
3056   Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3057 
3058   // Apply the offset, which we assume is non-null.
3059   Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
3060 
3061   // Cast the address to the appropriate pointer type, adopting the address
3062   // space of the base pointer.
3063   return Builder.CreateBitCast(Addr, PType);
3064 }
3065 
3066 llvm::Value *
3067 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3068                                              const CastExpr *E,
3069                                              llvm::Value *Src) {
3070   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3071          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3072          E->getCastKind() == CK_ReinterpretMemberPointer);
3073 
3074   // Use constant emission if we can.
3075   if (isa<llvm::Constant>(Src))
3076     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3077 
3078   // We may be adding or dropping fields from the member pointer, so we need
3079   // both types and the inheritance models of both records.
3080   const MemberPointerType *SrcTy =
3081     E->getSubExpr()->getType()->castAs<MemberPointerType>();
3082   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3083   bool IsFunc = SrcTy->isMemberFunctionPointer();
3084 
3085   // If the classes use the same null representation, reinterpret_cast is a nop.
3086   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3087   if (IsReinterpret && IsFunc)
3088     return Src;
3089 
3090   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3091   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3092   if (IsReinterpret &&
3093       SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3094     return Src;
3095 
3096   CGBuilderTy &Builder = CGF.Builder;
3097 
3098   // Branch past the conversion if Src is null.
3099   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3100   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3101 
3102   // C++ 5.2.10p9: The null member pointer value is converted to the null member
3103   //   pointer value of the destination type.
3104   if (IsReinterpret) {
3105     // For reinterpret casts, sema ensures that src and dst are both functions
3106     // or data and have the same size, which means the LLVM types should match.
3107     assert(Src->getType() == DstNull->getType());
3108     return Builder.CreateSelect(IsNotNull, Src, DstNull);
3109   }
3110 
3111   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3112   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3113   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3114   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3115   CGF.EmitBlock(ConvertBB);
3116 
3117   llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3118       SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3119       Builder);
3120 
3121   Builder.CreateBr(ContinueBB);
3122 
3123   // In the continuation, choose between DstNull and Dst.
3124   CGF.EmitBlock(ContinueBB);
3125   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3126   Phi->addIncoming(DstNull, OriginalBB);
3127   Phi->addIncoming(Dst, ConvertBB);
3128   return Phi;
3129 }
3130 
3131 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3132     const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3133     CastExpr::path_const_iterator PathBegin,
3134     CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3135     CGBuilderTy &Builder) {
3136   const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3137   const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3138   MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
3139   MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
3140   bool IsFunc = SrcTy->isMemberFunctionPointer();
3141   bool IsConstant = isa<llvm::Constant>(Src);
3142 
3143   // Decompose src.
3144   llvm::Value *FirstField = Src;
3145   llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3146   llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3147   llvm::Value *VBPtrOffset = getZeroInt();
3148   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
3149     // We need to extract values.
3150     unsigned I = 0;
3151     FirstField = Builder.CreateExtractValue(Src, I++);
3152     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
3153       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3154     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
3155       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3156     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
3157       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3158   }
3159 
3160   bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3161   const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3162   const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3163 
3164   // For data pointers, we adjust the field offset directly.  For functions, we
3165   // have a separate field.
3166   llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3167 
3168   // The virtual inheritance model has a quirk: the virtual base table is always
3169   // referenced when dereferencing a member pointer even if the member pointer
3170   // is non-virtual.  This is accounted for by adjusting the non-virtual offset
3171   // to point backwards to the top of the MDC from the first VBase.  Undo this
3172   // adjustment to normalize the member pointer.
3173   llvm::Value *SrcVBIndexEqZero =
3174       Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3175   if (SrcInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3176     if (int64_t SrcOffsetToFirstVBase =
3177             getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3178       llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3179           SrcVBIndexEqZero,
3180           llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3181           getZeroInt());
3182       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3183     }
3184   }
3185 
3186   // A non-zero vbindex implies that we are dealing with a source member in a
3187   // floating virtual base in addition to some non-virtual offset.  If the
3188   // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3189   // fixed, base.  The difference between these two cases is that the vbindex +
3190   // nvoffset *always* point to the member regardless of what context they are
3191   // evaluated in so long as the vbindex is adjusted.  A member inside a fixed
3192   // base requires explicit nv adjustment.
3193   llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3194       CGM.IntTy,
3195       CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3196           .getQuantity());
3197 
3198   llvm::Value *NVDisp;
3199   if (IsDerivedToBase)
3200     NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3201   else
3202     NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3203 
3204   NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3205 
3206   // Update the vbindex to an appropriate value in the destination because
3207   // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3208   llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3209   if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance) &&
3210       MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) {
3211     if (llvm::GlobalVariable *VDispMap =
3212             getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3213       llvm::Value *VBIndex = Builder.CreateExactUDiv(
3214           VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3215       if (IsConstant) {
3216         llvm::Constant *Mapping = VDispMap->getInitializer();
3217         VirtualBaseAdjustmentOffset =
3218             Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3219       } else {
3220         llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3221         VirtualBaseAdjustmentOffset =
3222             Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3223                                       CharUnits::fromQuantity(4));
3224       }
3225 
3226       DstVBIndexEqZero =
3227           Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3228     }
3229   }
3230 
3231   // Set the VBPtrOffset to zero if the vbindex is zero.  Otherwise, initialize
3232   // it to the offset of the vbptr.
3233   if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) {
3234     llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3235         CGM.IntTy,
3236         getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3237     VBPtrOffset =
3238         Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3239   }
3240 
3241   // Likewise, apply a similar adjustment so that dereferencing the member
3242   // pointer correctly accounts for the distance between the start of the first
3243   // virtual base and the top of the MDC.
3244   if (DstInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3245     if (int64_t DstOffsetToFirstVBase =
3246             getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3247       llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3248           DstVBIndexEqZero,
3249           llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3250           getZeroInt());
3251       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3252     }
3253   }
3254 
3255   // Recompose dst from the null struct and the adjusted fields from src.
3256   llvm::Value *Dst;
3257   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
3258     Dst = FirstField;
3259   } else {
3260     Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3261     unsigned Idx = 0;
3262     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3263     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
3264       Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3265     if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
3266       Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3267     if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
3268       Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3269   }
3270   return Dst;
3271 }
3272 
3273 llvm::Constant *
3274 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3275                                              llvm::Constant *Src) {
3276   const MemberPointerType *SrcTy =
3277       E->getSubExpr()->getType()->castAs<MemberPointerType>();
3278   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3279 
3280   CastKind CK = E->getCastKind();
3281 
3282   return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3283                                      E->path_end(), Src);
3284 }
3285 
3286 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3287     const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3288     CastExpr::path_const_iterator PathBegin,
3289     CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3290   assert(CK == CK_DerivedToBaseMemberPointer ||
3291          CK == CK_BaseToDerivedMemberPointer ||
3292          CK == CK_ReinterpretMemberPointer);
3293   // If src is null, emit a new null for dst.  We can't return src because dst
3294   // might have a new representation.
3295   if (MemberPointerConstantIsNull(SrcTy, Src))
3296     return EmitNullMemberPointer(DstTy);
3297 
3298   // We don't need to do anything for reinterpret_casts of non-null member
3299   // pointers.  We should only get here when the two type representations have
3300   // the same size.
3301   if (CK == CK_ReinterpretMemberPointer)
3302     return Src;
3303 
3304   CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3305   auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3306       SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3307 
3308   return Dst;
3309 }
3310 
3311 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3312     CodeGenFunction &CGF, const Expr *E, Address This,
3313     llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3314     const MemberPointerType *MPT) {
3315   assert(MPT->isMemberFunctionPointer());
3316   const FunctionProtoType *FPT =
3317     MPT->getPointeeType()->castAs<FunctionProtoType>();
3318   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3319   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3320       CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3321   CGBuilderTy &Builder = CGF.Builder;
3322 
3323   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
3324 
3325   // Extract the fields we need, regardless of model.  We'll apply them if we
3326   // have them.
3327   llvm::Value *FunctionPointer = MemPtr;
3328   llvm::Value *NonVirtualBaseAdjustment = nullptr;
3329   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3330   llvm::Value *VBPtrOffset = nullptr;
3331   if (MemPtr->getType()->isStructTy()) {
3332     // We need to extract values.
3333     unsigned I = 0;
3334     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3335     if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
3336       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3337     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
3338       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3339     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
3340       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3341   }
3342 
3343   if (VirtualBaseAdjustmentOffset) {
3344     ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3345                                    VirtualBaseAdjustmentOffset, VBPtrOffset);
3346   } else {
3347     ThisPtrForCall = This.getPointer();
3348   }
3349 
3350   if (NonVirtualBaseAdjustment) {
3351     // Apply the adjustment and cast back to the original struct type.
3352     llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3353     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3354     ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3355                                            "this.adjusted");
3356   }
3357 
3358   FunctionPointer =
3359     Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3360   CGCallee Callee(FPT, FunctionPointer);
3361   return Callee;
3362 }
3363 
3364 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3365   return new MicrosoftCXXABI(CGM);
3366 }
3367 
3368 // MS RTTI Overview:
3369 // The run time type information emitted by cl.exe contains 5 distinct types of
3370 // structures.  Many of them reference each other.
3371 //
3372 // TypeInfo:  Static classes that are returned by typeid.
3373 //
3374 // CompleteObjectLocator:  Referenced by vftables.  They contain information
3375 //   required for dynamic casting, including OffsetFromTop.  They also contain
3376 //   a reference to the TypeInfo for the type and a reference to the
3377 //   CompleteHierarchyDescriptor for the type.
3378 //
3379 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3380 //   Used during dynamic_cast to walk a class hierarchy.  References a base
3381 //   class array and the size of said array.
3382 //
3383 // BaseClassArray: Contains a list of classes in a hierarchy.  BaseClassArray is
3384 //   somewhat of a misnomer because the most derived class is also in the list
3385 //   as well as multiple copies of virtual bases (if they occur multiple times
3386 //   in the hierarchy.)  The BaseClassArray contains one BaseClassDescriptor for
3387 //   every path in the hierarchy, in pre-order depth first order.  Note, we do
3388 //   not declare a specific llvm type for BaseClassArray, it's merely an array
3389 //   of BaseClassDescriptor pointers.
3390 //
3391 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3392 //   BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3393 //   BaseClassArray is.  It contains information about a class within a
3394 //   hierarchy such as: is this base is ambiguous and what is its offset in the
3395 //   vbtable.  The names of the BaseClassDescriptors have all of their fields
3396 //   mangled into them so they can be aggressively deduplicated by the linker.
3397 
3398 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3399   StringRef MangledName("??_7type_info@@6B@");
3400   if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3401     return VTable;
3402   return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3403                                   /*Constant=*/true,
3404                                   llvm::GlobalVariable::ExternalLinkage,
3405                                   /*Initializer=*/nullptr, MangledName);
3406 }
3407 
3408 namespace {
3409 
3410 /// A Helper struct that stores information about a class in a class
3411 /// hierarchy.  The information stored in these structs struct is used during
3412 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3413 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3414 // implicit depth first pre-order tree connectivity.  getFirstChild and
3415 // getNextSibling allow us to walk the tree efficiently.
3416 struct MSRTTIClass {
3417   enum {
3418     IsPrivateOnPath = 1 | 8,
3419     IsAmbiguous = 2,
3420     IsPrivate = 4,
3421     IsVirtual = 16,
3422     HasHierarchyDescriptor = 64
3423   };
3424   MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3425   uint32_t initialize(const MSRTTIClass *Parent,
3426                       const CXXBaseSpecifier *Specifier);
3427 
3428   MSRTTIClass *getFirstChild() { return this + 1; }
3429   static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3430     return Child + 1 + Child->NumBases;
3431   }
3432 
3433   const CXXRecordDecl *RD, *VirtualRoot;
3434   uint32_t Flags, NumBases, OffsetInVBase;
3435 };
3436 
3437 /// Recursively initialize the base class array.
3438 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3439                                  const CXXBaseSpecifier *Specifier) {
3440   Flags = HasHierarchyDescriptor;
3441   if (!Parent) {
3442     VirtualRoot = nullptr;
3443     OffsetInVBase = 0;
3444   } else {
3445     if (Specifier->getAccessSpecifier() != AS_public)
3446       Flags |= IsPrivate | IsPrivateOnPath;
3447     if (Specifier->isVirtual()) {
3448       Flags |= IsVirtual;
3449       VirtualRoot = RD;
3450       OffsetInVBase = 0;
3451     } else {
3452       if (Parent->Flags & IsPrivateOnPath)
3453         Flags |= IsPrivateOnPath;
3454       VirtualRoot = Parent->VirtualRoot;
3455       OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3456           .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3457     }
3458   }
3459   NumBases = 0;
3460   MSRTTIClass *Child = getFirstChild();
3461   for (const CXXBaseSpecifier &Base : RD->bases()) {
3462     NumBases += Child->initialize(this, &Base) + 1;
3463     Child = getNextChild(Child);
3464   }
3465   return NumBases;
3466 }
3467 
3468 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3469   switch (Ty->getLinkage()) {
3470   case NoLinkage:
3471   case InternalLinkage:
3472   case UniqueExternalLinkage:
3473     return llvm::GlobalValue::InternalLinkage;
3474 
3475   case VisibleNoLinkage:
3476   case ModuleInternalLinkage:
3477   case ModuleLinkage:
3478   case ExternalLinkage:
3479     return llvm::GlobalValue::LinkOnceODRLinkage;
3480   }
3481   llvm_unreachable("Invalid linkage!");
3482 }
3483 
3484 /// An ephemeral helper class for building MS RTTI types.  It caches some
3485 /// calls to the module and information about the most derived class in a
3486 /// hierarchy.
3487 struct MSRTTIBuilder {
3488   enum {
3489     HasBranchingHierarchy = 1,
3490     HasVirtualBranchingHierarchy = 2,
3491     HasAmbiguousBases = 4
3492   };
3493 
3494   MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3495       : CGM(ABI.CGM), Context(CGM.getContext()),
3496         VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3497         Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3498         ABI(ABI) {}
3499 
3500   llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3501   llvm::GlobalVariable *
3502   getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3503   llvm::GlobalVariable *getClassHierarchyDescriptor();
3504   llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3505 
3506   CodeGenModule &CGM;
3507   ASTContext &Context;
3508   llvm::LLVMContext &VMContext;
3509   llvm::Module &Module;
3510   const CXXRecordDecl *RD;
3511   llvm::GlobalVariable::LinkageTypes Linkage;
3512   MicrosoftCXXABI &ABI;
3513 };
3514 
3515 } // namespace
3516 
3517 /// Recursively serializes a class hierarchy in pre-order depth first
3518 /// order.
3519 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3520                                     const CXXRecordDecl *RD) {
3521   Classes.push_back(MSRTTIClass(RD));
3522   for (const CXXBaseSpecifier &Base : RD->bases())
3523     serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3524 }
3525 
3526 /// Find ambiguity among base classes.
3527 static void
3528 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3529   llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3530   llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3531   llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3532   for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3533     if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3534         !VirtualBases.insert(Class->RD).second) {
3535       Class = MSRTTIClass::getNextChild(Class);
3536       continue;
3537     }
3538     if (!UniqueBases.insert(Class->RD).second)
3539       AmbiguousBases.insert(Class->RD);
3540     Class++;
3541   }
3542   if (AmbiguousBases.empty())
3543     return;
3544   for (MSRTTIClass &Class : Classes)
3545     if (AmbiguousBases.count(Class.RD))
3546       Class.Flags |= MSRTTIClass::IsAmbiguous;
3547 }
3548 
3549 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3550   SmallString<256> MangledName;
3551   {
3552     llvm::raw_svector_ostream Out(MangledName);
3553     ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3554   }
3555 
3556   // Check to see if we've already declared this ClassHierarchyDescriptor.
3557   if (auto CHD = Module.getNamedGlobal(MangledName))
3558     return CHD;
3559 
3560   // Serialize the class hierarchy and initialize the CHD Fields.
3561   SmallVector<MSRTTIClass, 8> Classes;
3562   serializeClassHierarchy(Classes, RD);
3563   Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3564   detectAmbiguousBases(Classes);
3565   int Flags = 0;
3566   for (auto Class : Classes) {
3567     if (Class.RD->getNumBases() > 1)
3568       Flags |= HasBranchingHierarchy;
3569     // Note: cl.exe does not calculate "HasAmbiguousBases" correctly.  We
3570     // believe the field isn't actually used.
3571     if (Class.Flags & MSRTTIClass::IsAmbiguous)
3572       Flags |= HasAmbiguousBases;
3573   }
3574   if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3575     Flags |= HasVirtualBranchingHierarchy;
3576   // These gep indices are used to get the address of the first element of the
3577   // base class array.
3578   llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3579                                llvm::ConstantInt::get(CGM.IntTy, 0)};
3580 
3581   // Forward-declare the class hierarchy descriptor
3582   auto Type = ABI.getClassHierarchyDescriptorType();
3583   auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3584                                       /*Initializer=*/nullptr,
3585                                       MangledName);
3586   if (CHD->isWeakForLinker())
3587     CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3588 
3589   auto *Bases = getBaseClassArray(Classes);
3590 
3591   // Initialize the base class ClassHierarchyDescriptor.
3592   llvm::Constant *Fields[] = {
3593       llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3594       llvm::ConstantInt::get(CGM.IntTy, Flags),
3595       llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3596       ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3597           Bases->getValueType(), Bases,
3598           llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3599   };
3600   CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3601   return CHD;
3602 }
3603 
3604 llvm::GlobalVariable *
3605 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3606   SmallString<256> MangledName;
3607   {
3608     llvm::raw_svector_ostream Out(MangledName);
3609     ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3610   }
3611 
3612   // Forward-declare the base class array.
3613   // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3614   // mode) bytes of padding.  We provide a pointer sized amount of padding by
3615   // adding +1 to Classes.size().  The sections have pointer alignment and are
3616   // marked pick-any so it shouldn't matter.
3617   llvm::Type *PtrType = ABI.getImageRelativeType(
3618       ABI.getBaseClassDescriptorType()->getPointerTo());
3619   auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3620   auto *BCA =
3621       new llvm::GlobalVariable(Module, ArrType,
3622                                /*Constant=*/true, Linkage,
3623                                /*Initializer=*/nullptr, MangledName);
3624   if (BCA->isWeakForLinker())
3625     BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3626 
3627   // Initialize the BaseClassArray.
3628   SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3629   for (MSRTTIClass &Class : Classes)
3630     BaseClassArrayData.push_back(
3631         ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3632   BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3633   BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3634   return BCA;
3635 }
3636 
3637 llvm::GlobalVariable *
3638 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3639   // Compute the fields for the BaseClassDescriptor.  They are computed up front
3640   // because they are mangled into the name of the object.
3641   uint32_t OffsetInVBTable = 0;
3642   int32_t VBPtrOffset = -1;
3643   if (Class.VirtualRoot) {
3644     auto &VTableContext = CGM.getMicrosoftVTableContext();
3645     OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3646     VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3647   }
3648 
3649   SmallString<256> MangledName;
3650   {
3651     llvm::raw_svector_ostream Out(MangledName);
3652     ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3653         Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3654         Class.Flags, Out);
3655   }
3656 
3657   // Check to see if we've already declared this object.
3658   if (auto BCD = Module.getNamedGlobal(MangledName))
3659     return BCD;
3660 
3661   // Forward-declare the base class descriptor.
3662   auto Type = ABI.getBaseClassDescriptorType();
3663   auto BCD =
3664       new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3665                                /*Initializer=*/nullptr, MangledName);
3666   if (BCD->isWeakForLinker())
3667     BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3668 
3669   // Initialize the BaseClassDescriptor.
3670   llvm::Constant *Fields[] = {
3671       ABI.getImageRelativeConstant(
3672           ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3673       llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3674       llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3675       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3676       llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3677       llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3678       ABI.getImageRelativeConstant(
3679           MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3680   };
3681   BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3682   return BCD;
3683 }
3684 
3685 llvm::GlobalVariable *
3686 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3687   SmallString<256> MangledName;
3688   {
3689     llvm::raw_svector_ostream Out(MangledName);
3690     ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3691   }
3692 
3693   // Check to see if we've already computed this complete object locator.
3694   if (auto COL = Module.getNamedGlobal(MangledName))
3695     return COL;
3696 
3697   // Compute the fields of the complete object locator.
3698   int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3699   int VFPtrOffset = 0;
3700   // The offset includes the vtordisp if one exists.
3701   if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3702     if (Context.getASTRecordLayout(RD)
3703       .getVBaseOffsetsMap()
3704       .find(VBase)
3705       ->second.hasVtorDisp())
3706       VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3707 
3708   // Forward-declare the complete object locator.
3709   llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3710   auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3711     /*Initializer=*/nullptr, MangledName);
3712 
3713   // Initialize the CompleteObjectLocator.
3714   llvm::Constant *Fields[] = {
3715       llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3716       llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3717       llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3718       ABI.getImageRelativeConstant(
3719           CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3720       ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3721       ABI.getImageRelativeConstant(COL),
3722   };
3723   llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3724   if (!ABI.isImageRelative())
3725     FieldsRef = FieldsRef.drop_back();
3726   COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3727   if (COL->isWeakForLinker())
3728     COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3729   return COL;
3730 }
3731 
3732 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3733                                    bool &IsConst, bool &IsVolatile,
3734                                    bool &IsUnaligned) {
3735   T = Context.getExceptionObjectType(T);
3736 
3737   // C++14 [except.handle]p3:
3738   //   A handler is a match for an exception object of type E if [...]
3739   //     - the handler is of type cv T or const T& where T is a pointer type and
3740   //       E is a pointer type that can be converted to T by [...]
3741   //         - a qualification conversion
3742   IsConst = false;
3743   IsVolatile = false;
3744   IsUnaligned = false;
3745   QualType PointeeType = T->getPointeeType();
3746   if (!PointeeType.isNull()) {
3747     IsConst = PointeeType.isConstQualified();
3748     IsVolatile = PointeeType.isVolatileQualified();
3749     IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3750   }
3751 
3752   // Member pointer types like "const int A::*" are represented by having RTTI
3753   // for "int A::*" and separately storing the const qualifier.
3754   if (const auto *MPTy = T->getAs<MemberPointerType>())
3755     T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3756                                      MPTy->getClass());
3757 
3758   // Pointer types like "const int * const *" are represented by having RTTI
3759   // for "const int **" and separately storing the const qualifier.
3760   if (T->isPointerType())
3761     T = Context.getPointerType(PointeeType.getUnqualifiedType());
3762 
3763   return T;
3764 }
3765 
3766 CatchTypeInfo
3767 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3768                                               QualType CatchHandlerType) {
3769   // TypeDescriptors for exceptions never have qualified pointer types,
3770   // qualifiers are stored separately in order to support qualification
3771   // conversions.
3772   bool IsConst, IsVolatile, IsUnaligned;
3773   Type =
3774       decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3775 
3776   bool IsReference = CatchHandlerType->isReferenceType();
3777 
3778   uint32_t Flags = 0;
3779   if (IsConst)
3780     Flags |= 1;
3781   if (IsVolatile)
3782     Flags |= 2;
3783   if (IsUnaligned)
3784     Flags |= 4;
3785   if (IsReference)
3786     Flags |= 8;
3787 
3788   return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3789                        Flags};
3790 }
3791 
3792 /// Gets a TypeDescriptor.  Returns a llvm::Constant * rather than a
3793 /// llvm::GlobalVariable * because different type descriptors have different
3794 /// types, and need to be abstracted.  They are abstracting by casting the
3795 /// address to an Int8PtrTy.
3796 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3797   SmallString<256> MangledName;
3798   {
3799     llvm::raw_svector_ostream Out(MangledName);
3800     getMangleContext().mangleCXXRTTI(Type, Out);
3801   }
3802 
3803   // Check to see if we've already declared this TypeDescriptor.
3804   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3805     return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3806 
3807   // Note for the future: If we would ever like to do deferred emission of
3808   // RTTI, check if emitting vtables opportunistically need any adjustment.
3809 
3810   // Compute the fields for the TypeDescriptor.
3811   SmallString<256> TypeInfoString;
3812   {
3813     llvm::raw_svector_ostream Out(TypeInfoString);
3814     getMangleContext().mangleCXXRTTIName(Type, Out);
3815   }
3816 
3817   // Declare and initialize the TypeDescriptor.
3818   llvm::Constant *Fields[] = {
3819     getTypeInfoVTable(CGM),                        // VFPtr
3820     llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3821     llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3822   llvm::StructType *TypeDescriptorType =
3823       getTypeDescriptorType(TypeInfoString);
3824   auto *Var = new llvm::GlobalVariable(
3825       CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3826       getLinkageForRTTI(Type),
3827       llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3828       MangledName);
3829   if (Var->isWeakForLinker())
3830     Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3831   return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3832 }
3833 
3834 /// Gets or a creates a Microsoft CompleteObjectLocator.
3835 llvm::GlobalVariable *
3836 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3837                                             const VPtrInfo &Info) {
3838   return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3839 }
3840 
3841 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
3842   if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
3843     // There are no constructor variants, always emit the complete destructor.
3844     llvm::Function *Fn =
3845         CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
3846     CGM.maybeSetTrivialComdat(*ctor, *Fn);
3847     return;
3848   }
3849 
3850   auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
3851 
3852   // Emit the base destructor if the base and complete (vbase) destructors are
3853   // equivalent. This effectively implements -mconstructor-aliases as part of
3854   // the ABI.
3855   if (GD.getDtorType() == Dtor_Complete &&
3856       dtor->getParent()->getNumVBases() == 0)
3857     GD = GD.getWithDtorType(Dtor_Base);
3858 
3859   // The base destructor is equivalent to the base destructor of its
3860   // base class if there is exactly one non-virtual base class with a
3861   // non-trivial destructor, there are no fields with a non-trivial
3862   // destructor, and the body of the destructor is trivial.
3863   if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3864     return;
3865 
3866   llvm::Function *Fn = CGM.codegenCXXStructor(GD);
3867   if (Fn->isWeakForLinker())
3868     Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3869 }
3870 
3871 llvm::Function *
3872 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3873                                          CXXCtorType CT) {
3874   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3875 
3876   // Calculate the mangled name.
3877   SmallString<256> ThunkName;
3878   llvm::raw_svector_ostream Out(ThunkName);
3879   getMangleContext().mangleCXXCtor(CD, CT, Out);
3880 
3881   // If the thunk has been generated previously, just return it.
3882   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3883     return cast<llvm::Function>(GV);
3884 
3885   // Create the llvm::Function.
3886   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3887   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3888   const CXXRecordDecl *RD = CD->getParent();
3889   QualType RecordTy = getContext().getRecordType(RD);
3890   llvm::Function *ThunkFn = llvm::Function::Create(
3891       ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3892   ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3893       FnInfo.getEffectiveCallingConvention()));
3894   if (ThunkFn->isWeakForLinker())
3895     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3896   bool IsCopy = CT == Ctor_CopyingClosure;
3897 
3898   // Start codegen.
3899   CodeGenFunction CGF(CGM);
3900   CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3901 
3902   // Build FunctionArgs.
3903   FunctionArgList FunctionArgs;
3904 
3905   // A constructor always starts with a 'this' pointer as its first argument.
3906   buildThisParam(CGF, FunctionArgs);
3907 
3908   // Following the 'this' pointer is a reference to the source object that we
3909   // are copying from.
3910   ImplicitParamDecl SrcParam(
3911       getContext(), /*DC=*/nullptr, SourceLocation(),
3912       &getContext().Idents.get("src"),
3913       getContext().getLValueReferenceType(RecordTy,
3914                                           /*SpelledAsLValue=*/true),
3915       ImplicitParamDecl::Other);
3916   if (IsCopy)
3917     FunctionArgs.push_back(&SrcParam);
3918 
3919   // Constructors for classes which utilize virtual bases have an additional
3920   // parameter which indicates whether or not it is being delegated to by a more
3921   // derived constructor.
3922   ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
3923                                   SourceLocation(),
3924                                   &getContext().Idents.get("is_most_derived"),
3925                                   getContext().IntTy, ImplicitParamDecl::Other);
3926   // Only add the parameter to the list if the class has virtual bases.
3927   if (RD->getNumVBases() > 0)
3928     FunctionArgs.push_back(&IsMostDerived);
3929 
3930   // Start defining the function.
3931   auto NL = ApplyDebugLocation::CreateEmpty(CGF);
3932   CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3933                     FunctionArgs, CD->getLocation(), SourceLocation());
3934   // Create a scope with an artificial location for the body of this function.
3935   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3936   setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
3937   llvm::Value *This = getThisValue(CGF);
3938 
3939   llvm::Value *SrcVal =
3940       IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3941              : nullptr;
3942 
3943   CallArgList Args;
3944 
3945   // Push the this ptr.
3946   Args.add(RValue::get(This), CD->getThisType());
3947 
3948   // Push the src ptr.
3949   if (SrcVal)
3950     Args.add(RValue::get(SrcVal), SrcParam.getType());
3951 
3952   // Add the rest of the default arguments.
3953   SmallVector<const Stmt *, 4> ArgVec;
3954   ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
3955   for (const ParmVarDecl *PD : params) {
3956     assert(PD->hasDefaultArg() && "ctor closure lacks default args");
3957     ArgVec.push_back(PD->getDefaultArg());
3958   }
3959 
3960   CodeGenFunction::RunCleanupsScope Cleanups(CGF);
3961 
3962   const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
3963   CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
3964 
3965   // Insert any ABI-specific implicit constructor arguments.
3966   AddedStructorArgs ExtraArgs =
3967       addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
3968                                  /*ForVirtualBase=*/false,
3969                                  /*Delegating=*/false, Args);
3970   // Call the destructor with our arguments.
3971   llvm::Constant *CalleePtr =
3972       CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
3973   CGCallee Callee =
3974       CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
3975   const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
3976       Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
3977   CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
3978 
3979   Cleanups.ForceCleanup();
3980 
3981   // Emit the ret instruction, remove any temporary instructions created for the
3982   // aid of CodeGen.
3983   CGF.FinishFunction(SourceLocation());
3984 
3985   return ThunkFn;
3986 }
3987 
3988 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3989                                                   uint32_t NVOffset,
3990                                                   int32_t VBPtrOffset,
3991                                                   uint32_t VBIndex) {
3992   assert(!T->isReferenceType());
3993 
3994   CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3995   const CXXConstructorDecl *CD =
3996       RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3997   CXXCtorType CT = Ctor_Complete;
3998   if (CD)
3999     if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4000       CT = Ctor_CopyingClosure;
4001 
4002   uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4003   SmallString<256> MangledName;
4004   {
4005     llvm::raw_svector_ostream Out(MangledName);
4006     getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4007                                               VBPtrOffset, VBIndex, Out);
4008   }
4009   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4010     return getImageRelativeConstant(GV);
4011 
4012   // The TypeDescriptor is used by the runtime to determine if a catch handler
4013   // is appropriate for the exception object.
4014   llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4015 
4016   // The runtime is responsible for calling the copy constructor if the
4017   // exception is caught by value.
4018   llvm::Constant *CopyCtor;
4019   if (CD) {
4020     if (CT == Ctor_CopyingClosure)
4021       CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4022     else
4023       CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4024 
4025     CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4026   } else {
4027     CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4028   }
4029   CopyCtor = getImageRelativeConstant(CopyCtor);
4030 
4031   bool IsScalar = !RD;
4032   bool HasVirtualBases = false;
4033   bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4034   QualType PointeeType = T;
4035   if (T->isPointerType())
4036     PointeeType = T->getPointeeType();
4037   if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4038     HasVirtualBases = RD->getNumVBases() > 0;
4039     if (IdentifierInfo *II = RD->getIdentifier())
4040       IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4041   }
4042 
4043   // Encode the relevant CatchableType properties into the Flags bitfield.
4044   // FIXME: Figure out how bits 2 or 8 can get set.
4045   uint32_t Flags = 0;
4046   if (IsScalar)
4047     Flags |= 1;
4048   if (HasVirtualBases)
4049     Flags |= 4;
4050   if (IsStdBadAlloc)
4051     Flags |= 16;
4052 
4053   llvm::Constant *Fields[] = {
4054       llvm::ConstantInt::get(CGM.IntTy, Flags),       // Flags
4055       TD,                                             // TypeDescriptor
4056       llvm::ConstantInt::get(CGM.IntTy, NVOffset),    // NonVirtualAdjustment
4057       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4058       llvm::ConstantInt::get(CGM.IntTy, VBIndex),     // VBTableIndex
4059       llvm::ConstantInt::get(CGM.IntTy, Size),        // Size
4060       CopyCtor                                        // CopyCtor
4061   };
4062   llvm::StructType *CTType = getCatchableTypeType();
4063   auto *GV = new llvm::GlobalVariable(
4064       CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
4065       llvm::ConstantStruct::get(CTType, Fields), MangledName);
4066   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4067   GV->setSection(".xdata");
4068   if (GV->isWeakForLinker())
4069     GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4070   return getImageRelativeConstant(GV);
4071 }
4072 
4073 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4074   assert(!T->isReferenceType());
4075 
4076   // See if we've already generated a CatchableTypeArray for this type before.
4077   llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4078   if (CTA)
4079     return CTA;
4080 
4081   // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4082   // using a SmallSetVector.  Duplicates may arise due to virtual bases
4083   // occurring more than once in the hierarchy.
4084   llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4085 
4086   // C++14 [except.handle]p3:
4087   //   A handler is a match for an exception object of type E if [...]
4088   //     - the handler is of type cv T or cv T& and T is an unambiguous public
4089   //       base class of E, or
4090   //     - the handler is of type cv T or const T& where T is a pointer type and
4091   //       E is a pointer type that can be converted to T by [...]
4092   //         - a standard pointer conversion (4.10) not involving conversions to
4093   //           pointers to private or protected or ambiguous classes
4094   const CXXRecordDecl *MostDerivedClass = nullptr;
4095   bool IsPointer = T->isPointerType();
4096   if (IsPointer)
4097     MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4098   else
4099     MostDerivedClass = T->getAsCXXRecordDecl();
4100 
4101   // Collect all the unambiguous public bases of the MostDerivedClass.
4102   if (MostDerivedClass) {
4103     const ASTContext &Context = getContext();
4104     const ASTRecordLayout &MostDerivedLayout =
4105         Context.getASTRecordLayout(MostDerivedClass);
4106     MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4107     SmallVector<MSRTTIClass, 8> Classes;
4108     serializeClassHierarchy(Classes, MostDerivedClass);
4109     Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4110     detectAmbiguousBases(Classes);
4111     for (const MSRTTIClass &Class : Classes) {
4112       // Skip any ambiguous or private bases.
4113       if (Class.Flags &
4114           (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4115         continue;
4116       // Write down how to convert from a derived pointer to a base pointer.
4117       uint32_t OffsetInVBTable = 0;
4118       int32_t VBPtrOffset = -1;
4119       if (Class.VirtualRoot) {
4120         OffsetInVBTable =
4121           VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4122         VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4123       }
4124 
4125       // Turn our record back into a pointer if the exception object is a
4126       // pointer.
4127       QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4128       if (IsPointer)
4129         RTTITy = Context.getPointerType(RTTITy);
4130       CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4131                                              VBPtrOffset, OffsetInVBTable));
4132     }
4133   }
4134 
4135   // C++14 [except.handle]p3:
4136   //   A handler is a match for an exception object of type E if
4137   //     - The handler is of type cv T or cv T& and E and T are the same type
4138   //       (ignoring the top-level cv-qualifiers)
4139   CatchableTypes.insert(getCatchableType(T));
4140 
4141   // C++14 [except.handle]p3:
4142   //   A handler is a match for an exception object of type E if
4143   //     - the handler is of type cv T or const T& where T is a pointer type and
4144   //       E is a pointer type that can be converted to T by [...]
4145   //         - a standard pointer conversion (4.10) not involving conversions to
4146   //           pointers to private or protected or ambiguous classes
4147   //
4148   // C++14 [conv.ptr]p2:
4149   //   A prvalue of type "pointer to cv T," where T is an object type, can be
4150   //   converted to a prvalue of type "pointer to cv void".
4151   if (IsPointer && T->getPointeeType()->isObjectType())
4152     CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4153 
4154   // C++14 [except.handle]p3:
4155   //   A handler is a match for an exception object of type E if [...]
4156   //     - the handler is of type cv T or const T& where T is a pointer or
4157   //       pointer to member type and E is std::nullptr_t.
4158   //
4159   // We cannot possibly list all possible pointer types here, making this
4160   // implementation incompatible with the standard.  However, MSVC includes an
4161   // entry for pointer-to-void in this case.  Let's do the same.
4162   if (T->isNullPtrType())
4163     CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4164 
4165   uint32_t NumEntries = CatchableTypes.size();
4166   llvm::Type *CTType =
4167       getImageRelativeType(getCatchableTypeType()->getPointerTo());
4168   llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4169   llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4170   llvm::Constant *Fields[] = {
4171       llvm::ConstantInt::get(CGM.IntTy, NumEntries),    // NumEntries
4172       llvm::ConstantArray::get(
4173           AT, llvm::makeArrayRef(CatchableTypes.begin(),
4174                                  CatchableTypes.end())) // CatchableTypes
4175   };
4176   SmallString<256> MangledName;
4177   {
4178     llvm::raw_svector_ostream Out(MangledName);
4179     getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4180   }
4181   CTA = new llvm::GlobalVariable(
4182       CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
4183       llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4184   CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4185   CTA->setSection(".xdata");
4186   if (CTA->isWeakForLinker())
4187     CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4188   return CTA;
4189 }
4190 
4191 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4192   bool IsConst, IsVolatile, IsUnaligned;
4193   T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4194 
4195   // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4196   // the exception object may be caught as.
4197   llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4198   // The first field in a CatchableTypeArray is the number of CatchableTypes.
4199   // This is used as a component of the mangled name which means that we need to
4200   // know what it is in order to see if we have previously generated the
4201   // ThrowInfo.
4202   uint32_t NumEntries =
4203       cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4204           ->getLimitedValue();
4205 
4206   SmallString<256> MangledName;
4207   {
4208     llvm::raw_svector_ostream Out(MangledName);
4209     getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4210                                           NumEntries, Out);
4211   }
4212 
4213   // Reuse a previously generated ThrowInfo if we have generated an appropriate
4214   // one before.
4215   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4216     return GV;
4217 
4218   // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4219   // be at least as CV qualified.  Encode this requirement into the Flags
4220   // bitfield.
4221   uint32_t Flags = 0;
4222   if (IsConst)
4223     Flags |= 1;
4224   if (IsVolatile)
4225     Flags |= 2;
4226   if (IsUnaligned)
4227     Flags |= 4;
4228 
4229   // The cleanup-function (a destructor) must be called when the exception
4230   // object's lifetime ends.
4231   llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4232   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4233     if (CXXDestructorDecl *DtorD = RD->getDestructor())
4234       if (!DtorD->isTrivial())
4235         CleanupFn = llvm::ConstantExpr::getBitCast(
4236             CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4237             CGM.Int8PtrTy);
4238   // This is unused as far as we can tell, initialize it to null.
4239   llvm::Constant *ForwardCompat =
4240       getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4241   llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4242       llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4243   llvm::StructType *TIType = getThrowInfoType();
4244   llvm::Constant *Fields[] = {
4245       llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4246       getImageRelativeConstant(CleanupFn),      // CleanupFn
4247       ForwardCompat,                            // ForwardCompat
4248       PointerToCatchableTypes                   // CatchableTypeArray
4249   };
4250   auto *GV = new llvm::GlobalVariable(
4251       CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
4252       llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4253   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4254   GV->setSection(".xdata");
4255   if (GV->isWeakForLinker())
4256     GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4257   return GV;
4258 }
4259 
4260 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4261   const Expr *SubExpr = E->getSubExpr();
4262   QualType ThrowType = SubExpr->getType();
4263   // The exception object lives on the stack and it's address is passed to the
4264   // runtime function.
4265   Address AI = CGF.CreateMemTemp(ThrowType);
4266   CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4267                        /*IsInit=*/true);
4268 
4269   // The so-called ThrowInfo is used to describe how the exception object may be
4270   // caught.
4271   llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4272 
4273   // Call into the runtime to throw the exception.
4274   llvm::Value *Args[] = {
4275     CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4276     TI
4277   };
4278   CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4279 }
4280 
4281 std::pair<llvm::Value *, const CXXRecordDecl *>
4282 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4283                                const CXXRecordDecl *RD) {
4284   std::tie(This, std::ignore, RD) =
4285       performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4286   return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4287 }
4288