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