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