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