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