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