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