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