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