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