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