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