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 "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/VTableBuilder.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/IR/CallSite.h"
26 
27 using namespace clang;
28 using namespace CodeGen;
29 
30 namespace {
31 
32 /// Holds all the vbtable globals for a given class.
33 struct VBTableGlobals {
34   const VPtrInfoVector *VBTables;
35   SmallVector<llvm::GlobalVariable *, 2> Globals;
36 };
37 
38 class MicrosoftCXXABI : public CGCXXABI {
39 public:
40   MicrosoftCXXABI(CodeGenModule &CGM)
41       : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
42         ClassHierarchyDescriptorType(nullptr),
43         CompleteObjectLocatorType(nullptr) {}
44 
45   bool HasThisReturn(GlobalDecl GD) const override;
46 
47   bool classifyReturnType(CGFunctionInfo &FI) const override;
48 
49   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
50 
51   bool isSRetParameterAfterThis() const override { return true; }
52 
53   StringRef GetPureVirtualCallName() override { return "_purecall"; }
54   // No known support for deleted functions in MSVC yet, so this choice is
55   // arbitrary.
56   StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
57 
58   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
59                                       llvm::Value *ptr,
60                                       QualType type) override;
61 
62   llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
63                                                    const VPtrInfo *Info);
64 
65   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
66 
67   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
68   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
69   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
70                           llvm::Value *ThisPtr,
71                           llvm::Type *StdTypeInfoPtrTy) override;
72 
73   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
74                                           QualType SrcRecordTy) override;
75 
76   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
77                                    QualType SrcRecordTy, QualType DestTy,
78                                    QualType DestRecordTy,
79                                    llvm::BasicBlock *CastEnd) override;
80 
81   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
82                                      QualType SrcRecordTy,
83                                      QualType DestTy) override;
84 
85   bool EmitBadCastCall(CodeGenFunction &CGF) override;
86 
87   llvm::Value *
88   GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
89                             const CXXRecordDecl *ClassDecl,
90                             const CXXRecordDecl *BaseClassDecl) override;
91 
92   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
93                                  CXXCtorType Type, CanQualType &ResTy,
94                                  SmallVectorImpl<CanQualType> &ArgTys) override;
95 
96   llvm::BasicBlock *
97   EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
98                                 const CXXRecordDecl *RD) override;
99 
100   void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
101                                               const CXXRecordDecl *RD) override;
102 
103   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
104 
105   // Background on MSVC destructors
106   // ==============================
107   //
108   // Both Itanium and MSVC ABIs have destructor variants.  The variant names
109   // roughly correspond in the following way:
110   //   Itanium       Microsoft
111   //   Base       -> no name, just ~Class
112   //   Complete   -> vbase destructor
113   //   Deleting   -> scalar deleting destructor
114   //                 vector deleting destructor
115   //
116   // The base and complete destructors are the same as in Itanium, although the
117   // complete destructor does not accept a VTT parameter when there are virtual
118   // bases.  A separate mechanism involving vtordisps is used to ensure that
119   // virtual methods of destroyed subobjects are not called.
120   //
121   // The deleting destructors accept an i32 bitfield as a second parameter.  Bit
122   // 1 indicates if the memory should be deleted.  Bit 2 indicates if the this
123   // pointer points to an array.  The scalar deleting destructor assumes that
124   // bit 2 is zero, and therefore does not contain a loop.
125   //
126   // For virtual destructors, only one entry is reserved in the vftable, and it
127   // always points to the vector deleting destructor.  The vector deleting
128   // destructor is the most general, so it can be used to destroy objects in
129   // place, delete single heap objects, or delete arrays.
130   //
131   // A TU defining a non-inline destructor is only guaranteed to emit a base
132   // destructor, and all of the other variants are emitted on an as-needed basis
133   // in COMDATs.  Because a non-base destructor can be emitted in a TU that
134   // lacks a definition for the destructor, non-base destructors must always
135   // delegate to or alias the base destructor.
136 
137   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
138                                 CXXDtorType Type,
139                                 CanQualType &ResTy,
140                                 SmallVectorImpl<CanQualType> &ArgTys) override;
141 
142   /// Non-base dtors should be emitted as delegating thunks in this ABI.
143   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
144                               CXXDtorType DT) const override {
145     return DT != Dtor_Base;
146   }
147 
148   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
149 
150   const CXXRecordDecl *
151   getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
152     MD = MD->getCanonicalDecl();
153     if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
154       MicrosoftVTableContext::MethodVFTableLocation ML =
155           CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
156       // The vbases might be ordered differently in the final overrider object
157       // and the complete object, so the "this" argument may sometimes point to
158       // memory that has no particular type (e.g. past the complete object).
159       // In this case, we just use a generic pointer type.
160       // FIXME: might want to have a more precise type in the non-virtual
161       // multiple inheritance case.
162       if (ML.VBase || !ML.VFPtrOffset.isZero())
163         return nullptr;
164     }
165     return MD->getParent();
166   }
167 
168   llvm::Value *
169   adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
170                                            llvm::Value *This,
171                                            bool VirtualCall) override;
172 
173   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
174                                  FunctionArgList &Params) override;
175 
176   llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
177       CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
178 
179   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
180 
181   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
182                                       const CXXConstructorDecl *D,
183                                       CXXCtorType Type, bool ForVirtualBase,
184                                       bool Delegating,
185                                       CallArgList &Args) override;
186 
187   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
188                           CXXDtorType Type, bool ForVirtualBase,
189                           bool Delegating, llvm::Value *This) override;
190 
191   void emitVTableDefinitions(CodeGenVTables &CGVT,
192                              const CXXRecordDecl *RD) override;
193 
194   llvm::Value *getVTableAddressPointInStructor(
195       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
196       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
197       bool &NeedsVirtualOffset) override;
198 
199   llvm::Constant *
200   getVTableAddressPointForConstExpr(BaseSubobject Base,
201                                     const CXXRecordDecl *VTableClass) override;
202 
203   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
204                                         CharUnits VPtrOffset) override;
205 
206   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
207                                          llvm::Value *This,
208                                          llvm::Type *Ty) override;
209 
210   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
211                                  const CXXDestructorDecl *Dtor,
212                                  CXXDtorType DtorType, SourceLocation CallLoc,
213                                  llvm::Value *This) override;
214 
215   void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
216                                         CallArgList &CallArgs) override {
217     assert(GD.getDtorType() == Dtor_Deleting &&
218            "Only deleting destructor thunks are available in this ABI");
219     CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
220                              CGM.getContext().IntTy);
221   }
222 
223   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
224 
225   llvm::GlobalVariable *
226   getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
227                    llvm::GlobalVariable::LinkageTypes Linkage);
228 
229   void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
230                              llvm::GlobalVariable *GV) const;
231 
232   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
233                        GlobalDecl GD, bool ReturnAdjustment) override {
234     // Never dllimport/dllexport thunks.
235     Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
236 
237     GVALinkage Linkage =
238         getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
239 
240     if (Linkage == GVA_Internal)
241       Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
242     else if (ReturnAdjustment)
243       Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
244     else
245       Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
246   }
247 
248   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
249                                      const ThisAdjustment &TA) override;
250 
251   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
252                                        const ReturnAdjustment &RA) override;
253 
254   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
255                        llvm::GlobalVariable *DeclPtr,
256                        bool PerformInit) override;
257 
258   // ==== Notes on array cookies =========
259   //
260   // MSVC seems to only use cookies when the class has a destructor; a
261   // two-argument usual array deallocation function isn't sufficient.
262   //
263   // For example, this code prints "100" and "1":
264   //   struct A {
265   //     char x;
266   //     void *operator new[](size_t sz) {
267   //       printf("%u\n", sz);
268   //       return malloc(sz);
269   //     }
270   //     void operator delete[](void *p, size_t sz) {
271   //       printf("%u\n", sz);
272   //       free(p);
273   //     }
274   //   };
275   //   int main() {
276   //     A *p = new A[100];
277   //     delete[] p;
278   //   }
279   // Whereas it prints "104" and "104" if you give A a destructor.
280 
281   bool requiresArrayCookie(const CXXDeleteExpr *expr,
282                            QualType elementType) override;
283   bool requiresArrayCookie(const CXXNewExpr *expr) override;
284   CharUnits getArrayCookieSizeImpl(QualType type) override;
285   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
286                                      llvm::Value *NewPtr,
287                                      llvm::Value *NumElements,
288                                      const CXXNewExpr *expr,
289                                      QualType ElementType) override;
290   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
291                                    llvm::Value *allocPtr,
292                                    CharUnits cookieSize) override;
293 
294   friend struct MSRTTIBuilder;
295 
296   bool isImageRelative() const {
297     return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
298   }
299 
300   // 5 routines for constructing the llvm types for MS RTTI structs.
301   llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
302     llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
303     TDTypeName += llvm::utostr(TypeInfoString.size());
304     llvm::StructType *&TypeDescriptorType =
305         TypeDescriptorTypeMap[TypeInfoString.size()];
306     if (TypeDescriptorType)
307       return TypeDescriptorType;
308     llvm::Type *FieldTypes[] = {
309         CGM.Int8PtrPtrTy,
310         CGM.Int8PtrTy,
311         llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
312     TypeDescriptorType =
313         llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
314     return TypeDescriptorType;
315   }
316 
317   llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
318     if (!isImageRelative())
319       return PtrType;
320     return CGM.IntTy;
321   }
322 
323   llvm::StructType *getBaseClassDescriptorType() {
324     if (BaseClassDescriptorType)
325       return BaseClassDescriptorType;
326     llvm::Type *FieldTypes[] = {
327         getImageRelativeType(CGM.Int8PtrTy),
328         CGM.IntTy,
329         CGM.IntTy,
330         CGM.IntTy,
331         CGM.IntTy,
332         CGM.IntTy,
333         getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
334     };
335     BaseClassDescriptorType = llvm::StructType::create(
336         CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
337     return BaseClassDescriptorType;
338   }
339 
340   llvm::StructType *getClassHierarchyDescriptorType() {
341     if (ClassHierarchyDescriptorType)
342       return ClassHierarchyDescriptorType;
343     // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
344     ClassHierarchyDescriptorType = llvm::StructType::create(
345         CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
346     llvm::Type *FieldTypes[] = {
347         CGM.IntTy,
348         CGM.IntTy,
349         CGM.IntTy,
350         getImageRelativeType(
351             getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
352     };
353     ClassHierarchyDescriptorType->setBody(FieldTypes);
354     return ClassHierarchyDescriptorType;
355   }
356 
357   llvm::StructType *getCompleteObjectLocatorType() {
358     if (CompleteObjectLocatorType)
359       return CompleteObjectLocatorType;
360     CompleteObjectLocatorType = llvm::StructType::create(
361         CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
362     llvm::Type *FieldTypes[] = {
363         CGM.IntTy,
364         CGM.IntTy,
365         CGM.IntTy,
366         getImageRelativeType(CGM.Int8PtrTy),
367         getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
368         getImageRelativeType(CompleteObjectLocatorType),
369     };
370     llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
371     if (!isImageRelative())
372       FieldTypesRef = FieldTypesRef.drop_back();
373     CompleteObjectLocatorType->setBody(FieldTypesRef);
374     return CompleteObjectLocatorType;
375   }
376 
377   llvm::GlobalVariable *getImageBase() {
378     StringRef Name = "__ImageBase";
379     if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
380       return GV;
381 
382     return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
383                                     /*isConstant=*/true,
384                                     llvm::GlobalValue::ExternalLinkage,
385                                     /*Initializer=*/nullptr, Name);
386   }
387 
388   llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
389     if (!isImageRelative())
390       return PtrVal;
391 
392     llvm::Constant *ImageBaseAsInt =
393         llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
394     llvm::Constant *PtrValAsInt =
395         llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
396     llvm::Constant *Diff =
397         llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
398                                    /*HasNUW=*/true, /*HasNSW=*/true);
399     return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
400   }
401 
402 private:
403   MicrosoftMangleContext &getMangleContext() {
404     return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
405   }
406 
407   llvm::Constant *getZeroInt() {
408     return llvm::ConstantInt::get(CGM.IntTy, 0);
409   }
410 
411   llvm::Constant *getAllOnesInt() {
412     return  llvm::Constant::getAllOnesValue(CGM.IntTy);
413   }
414 
415   llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
416     return C ? C : getZeroInt();
417   }
418 
419   llvm::Value *getValueOrZeroInt(llvm::Value *C) {
420     return C ? C : getZeroInt();
421   }
422 
423   CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
424 
425   void
426   GetNullMemberPointerFields(const MemberPointerType *MPT,
427                              llvm::SmallVectorImpl<llvm::Constant *> &fields);
428 
429   /// \brief Shared code for virtual base adjustment.  Returns the offset from
430   /// the vbptr to the virtual base.  Optionally returns the address of the
431   /// vbptr itself.
432   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
433                                        llvm::Value *Base,
434                                        llvm::Value *VBPtrOffset,
435                                        llvm::Value *VBTableOffset,
436                                        llvm::Value **VBPtr = nullptr);
437 
438   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
439                                        llvm::Value *Base,
440                                        int32_t VBPtrOffset,
441                                        int32_t VBTableOffset,
442                                        llvm::Value **VBPtr = nullptr) {
443     llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
444                 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
445     return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
446   }
447 
448   /// \brief Performs a full virtual base adjustment.  Used to dereference
449   /// pointers to members of virtual bases.
450   llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
451                                  const CXXRecordDecl *RD, llvm::Value *Base,
452                                  llvm::Value *VirtualBaseAdjustmentOffset,
453                                  llvm::Value *VBPtrOffset /* optional */);
454 
455   /// \brief Emits a full member pointer with the fields common to data and
456   /// function member pointers.
457   llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
458                                         bool IsMemberFunction,
459                                         const CXXRecordDecl *RD,
460                                         CharUnits NonVirtualBaseAdjustment);
461 
462   llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
463                                      const CXXMethodDecl *MD,
464                                      CharUnits NonVirtualBaseAdjustment);
465 
466   bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
467                                    llvm::Constant *MP);
468 
469   /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
470   void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
471 
472   /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
473   const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
474 
475   /// \brief Generate a thunk for calling a virtual member function MD.
476   llvm::Function *EmitVirtualMemPtrThunk(
477       const CXXMethodDecl *MD,
478       const MicrosoftVTableContext::MethodVFTableLocation &ML);
479 
480 public:
481   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
482 
483   bool isZeroInitializable(const MemberPointerType *MPT) override;
484 
485   bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
486     const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
487     return RD->getAttr<MSInheritanceAttr>() != nullptr;
488   }
489 
490   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
491 
492   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
493                                         CharUnits offset) override;
494   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
495   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
496 
497   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
498                                            llvm::Value *L,
499                                            llvm::Value *R,
500                                            const MemberPointerType *MPT,
501                                            bool Inequality) override;
502 
503   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
504                                           llvm::Value *MemPtr,
505                                           const MemberPointerType *MPT) override;
506 
507   llvm::Value *
508   EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
509                                llvm::Value *Base, llvm::Value *MemPtr,
510                                const MemberPointerType *MPT) override;
511 
512   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
513                                            const CastExpr *E,
514                                            llvm::Value *Src) override;
515 
516   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
517                                               llvm::Constant *Src) override;
518 
519   llvm::Value *
520   EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
521                                   llvm::Value *&This, llvm::Value *MemPtr,
522                                   const MemberPointerType *MPT) override;
523 
524 private:
525   typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
526   typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
527   typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
528   /// \brief All the vftables that have been referenced.
529   VFTablesMapTy VFTablesMap;
530   VTablesMapTy VTablesMap;
531 
532   /// \brief This set holds the record decls we've deferred vtable emission for.
533   llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
534 
535 
536   /// \brief All the vbtables which have been referenced.
537   llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
538 
539   /// Info on the global variable used to guard initialization of static locals.
540   /// The BitIndex field is only used for externally invisible declarations.
541   struct GuardInfo {
542     GuardInfo() : Guard(nullptr), BitIndex(0) {}
543     llvm::GlobalVariable *Guard;
544     unsigned BitIndex;
545   };
546 
547   /// Map from DeclContext to the current guard variable.  We assume that the
548   /// AST is visited in source code order.
549   llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
550 
551   llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
552   llvm::StructType *BaseClassDescriptorType;
553   llvm::StructType *ClassHierarchyDescriptorType;
554   llvm::StructType *CompleteObjectLocatorType;
555 };
556 
557 }
558 
559 CGCXXABI::RecordArgABI
560 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
561   switch (CGM.getTarget().getTriple().getArch()) {
562   default:
563     // FIXME: Implement for other architectures.
564     return RAA_Default;
565 
566   case llvm::Triple::x86:
567     // All record arguments are passed in memory on x86.  Decide whether to
568     // construct the object directly in argument memory, or to construct the
569     // argument elsewhere and copy the bytes during the call.
570 
571     // If C++ prohibits us from making a copy, construct the arguments directly
572     // into argument memory.
573     if (!canCopyArgument(RD))
574       return RAA_DirectInMemory;
575 
576     // Otherwise, construct the argument into a temporary and copy the bytes
577     // into the outgoing argument memory.
578     return RAA_Default;
579 
580   case llvm::Triple::x86_64:
581     // Win64 passes objects with non-trivial copy ctors indirectly.
582     if (RD->hasNonTrivialCopyConstructor())
583       return RAA_Indirect;
584 
585     // Win64 passes objects larger than 8 bytes indirectly.
586     if (getContext().getTypeSize(RD->getTypeForDecl()) > 64)
587       return RAA_Indirect;
588 
589     // We have a trivial copy constructor or no copy constructors, but we have
590     // to make sure it isn't deleted.
591     bool CopyDeleted = false;
592     for (const CXXConstructorDecl *CD : RD->ctors()) {
593       if (CD->isCopyConstructor()) {
594         assert(CD->isTrivial());
595         // We had at least one undeleted trivial copy ctor.  Return directly.
596         if (!CD->isDeleted())
597           return RAA_Default;
598         CopyDeleted = true;
599       }
600     }
601 
602     // The trivial copy constructor was deleted.  Return indirectly.
603     if (CopyDeleted)
604       return RAA_Indirect;
605 
606     // There were no copy ctors.  Return in RAX.
607     return RAA_Default;
608   }
609 
610   llvm_unreachable("invalid enum");
611 }
612 
613 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
614                                                      llvm::Value *ptr,
615                                                      QualType type) {
616   // FIXME: implement
617   return ptr;
618 }
619 
620 /// \brief Gets the offset to the virtual base that contains the vfptr for
621 /// MS-ABI polymorphic types.
622 static llvm::Value *getPolymorphicOffset(CodeGenFunction &CGF,
623                                          const CXXRecordDecl *RD,
624                                          llvm::Value *Value) {
625   const ASTContext &Context = RD->getASTContext();
626   for (const CXXBaseSpecifier &Base : RD->vbases())
627     if (Context.getASTRecordLayout(Base.getType()->getAsCXXRecordDecl())
628             .hasExtendableVFPtr())
629       return CGF.CGM.getCXXABI().GetVirtualBaseClassOffset(
630           CGF, Value, RD, Base.getType()->getAsCXXRecordDecl());
631   llvm_unreachable("One of our vbases should be polymorphic.");
632 }
633 
634 static std::pair<llvm::Value *, llvm::Value *>
635 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
636                       QualType SrcRecordTy) {
637   Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
638   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
639 
640   if (CGF.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
641     return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
642 
643   // Perform a base adjustment.
644   llvm::Value *Offset = getPolymorphicOffset(CGF, SrcDecl, Value);
645   Value = CGF.Builder.CreateInBoundsGEP(Value, Offset);
646   Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
647   return std::make_pair(Value, Offset);
648 }
649 
650 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
651                                                 QualType SrcRecordTy) {
652   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
653   return IsDeref &&
654          !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
655 }
656 
657 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
658                                        llvm::Value *Argument) {
659   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
660   llvm::FunctionType *FTy =
661       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
662   llvm::Value *Args[] = {Argument};
663   llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
664   return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
665 }
666 
667 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
668   llvm::CallSite Call =
669       emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
670   Call.setDoesNotReturn();
671   CGF.Builder.CreateUnreachable();
672 }
673 
674 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
675                                          QualType SrcRecordTy,
676                                          llvm::Value *ThisPtr,
677                                          llvm::Type *StdTypeInfoPtrTy) {
678   llvm::Value *Offset;
679   std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
680   return CGF.Builder.CreateBitCast(
681       emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy);
682 }
683 
684 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
685                                                          QualType SrcRecordTy) {
686   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
687   return SrcIsPtr &&
688          !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
689 }
690 
691 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
692     CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
693     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
694   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
695 
696   llvm::Value *SrcRTTI =
697       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
698   llvm::Value *DestRTTI =
699       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
700 
701   llvm::Value *Offset;
702   std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
703 
704   // PVOID __RTDynamicCast(
705   //   PVOID inptr,
706   //   LONG VfDelta,
707   //   PVOID SrcType,
708   //   PVOID TargetType,
709   //   BOOL isReference)
710   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
711                             CGF.Int8PtrTy, CGF.Int32Ty};
712   llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
713       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
714       "__RTDynamicCast");
715   llvm::Value *Args[] = {
716       Value, Offset, SrcRTTI, DestRTTI,
717       llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
718   Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
719   return CGF.Builder.CreateBitCast(Value, DestLTy);
720 }
721 
722 llvm::Value *
723 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
724                                        QualType SrcRecordTy,
725                                        QualType DestTy) {
726   llvm::Value *Offset;
727   std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
728 
729   // PVOID __RTCastToVoid(
730   //   PVOID inptr)
731   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
732   llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
733       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
734       "__RTCastToVoid");
735   llvm::Value *Args[] = {Value};
736   return CGF.EmitRuntimeCall(Function, Args);
737 }
738 
739 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
740   return false;
741 }
742 
743 llvm::Value *
744 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
745                                            llvm::Value *This,
746                                            const CXXRecordDecl *ClassDecl,
747                                            const CXXRecordDecl *BaseClassDecl) {
748   int64_t VBPtrChars =
749       getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
750   llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
751   CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
752   CharUnits VBTableChars =
753       IntSize *
754       CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
755   llvm::Value *VBTableOffset =
756     llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
757 
758   llvm::Value *VBPtrToNewBase =
759     GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
760   VBPtrToNewBase =
761     CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
762   return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
763 }
764 
765 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
766   return isa<CXXConstructorDecl>(GD.getDecl());
767 }
768 
769 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
770   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
771   if (!RD)
772     return false;
773 
774   if (FI.isInstanceMethod()) {
775     // If it's an instance method, aggregates are always returned indirectly via
776     // the second parameter.
777     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
778     FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
779     return true;
780   } else if (!RD->isPOD()) {
781     // If it's a free function, non-POD types are returned indirectly.
782     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
783     return true;
784   }
785 
786   // Otherwise, use the C ABI rules.
787   return false;
788 }
789 
790 void MicrosoftCXXABI::BuildConstructorSignature(
791     const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
792     SmallVectorImpl<CanQualType> &ArgTys) {
793 
794   // All parameters are already in place except is_most_derived, which goes
795   // after 'this' if it's variadic and last if it's not.
796 
797   const CXXRecordDecl *Class = Ctor->getParent();
798   const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
799   if (Class->getNumVBases()) {
800     if (FPT->isVariadic())
801       ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
802     else
803       ArgTys.push_back(CGM.getContext().IntTy);
804   }
805 }
806 
807 llvm::BasicBlock *
808 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
809                                                const CXXRecordDecl *RD) {
810   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
811   assert(IsMostDerivedClass &&
812          "ctor for a class with virtual bases must have an implicit parameter");
813   llvm::Value *IsCompleteObject =
814     CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
815 
816   llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
817   llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
818   CGF.Builder.CreateCondBr(IsCompleteObject,
819                            CallVbaseCtorsBB, SkipVbaseCtorsBB);
820 
821   CGF.EmitBlock(CallVbaseCtorsBB);
822 
823   // Fill in the vbtable pointers here.
824   EmitVBPtrStores(CGF, RD);
825 
826   // CGF will put the base ctor calls in this basic block for us later.
827 
828   return SkipVbaseCtorsBB;
829 }
830 
831 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
832     CodeGenFunction &CGF, const CXXRecordDecl *RD) {
833   // In most cases, an override for a vbase virtual method can adjust
834   // the "this" parameter by applying a constant offset.
835   // However, this is not enough while a constructor or a destructor of some
836   // class X is being executed if all the following conditions are met:
837   //  - X has virtual bases, (1)
838   //  - X overrides a virtual method M of a vbase Y, (2)
839   //  - X itself is a vbase of the most derived class.
840   //
841   // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
842   // which holds the extra amount of "this" adjustment we must do when we use
843   // the X vftables (i.e. during X ctor or dtor).
844   // Outside the ctors and dtors, the values of vtorDisps are zero.
845 
846   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
847   typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
848   const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
849   CGBuilderTy &Builder = CGF.Builder;
850 
851   unsigned AS =
852       cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
853   llvm::Value *Int8This = nullptr;  // Initialize lazily.
854 
855   for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
856         I != E; ++I) {
857     if (!I->second.hasVtorDisp())
858       continue;
859 
860     llvm::Value *VBaseOffset =
861         GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
862     // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
863     // just to Trunc back immediately.
864     VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
865     uint64_t ConstantVBaseOffset =
866         Layout.getVBaseClassOffset(I->first).getQuantity();
867 
868     // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
869     llvm::Value *VtorDispValue = Builder.CreateSub(
870         VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
871         "vtordisp.value");
872 
873     if (!Int8This)
874       Int8This = Builder.CreateBitCast(getThisValue(CGF),
875                                        CGF.Int8Ty->getPointerTo(AS));
876     llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
877     // vtorDisp is always the 32-bits before the vbase in the class layout.
878     VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
879     VtorDispPtr = Builder.CreateBitCast(
880         VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
881 
882     Builder.CreateStore(VtorDispValue, VtorDispPtr);
883   }
884 }
885 
886 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
887   // There's only one constructor type in this ABI.
888   CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
889 }
890 
891 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
892                                       const CXXRecordDecl *RD) {
893   llvm::Value *ThisInt8Ptr =
894     CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
895   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
896 
897   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
898   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
899     const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
900     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
901     const ASTRecordLayout &SubobjectLayout =
902         CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr);
903     CharUnits Offs = VBT->NonVirtualOffset;
904     Offs += SubobjectLayout.getVBPtrOffset();
905     if (VBT->getVBaseWithVPtr())
906       Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
907     llvm::Value *VBPtr =
908         CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
909     VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
910                                       "vbptr." + VBT->ReusingBase->getName());
911     CGF.Builder.CreateStore(GV, VBPtr);
912   }
913 }
914 
915 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
916                                                CXXDtorType Type,
917                                                CanQualType &ResTy,
918                                         SmallVectorImpl<CanQualType> &ArgTys) {
919   // 'this' is already in place
920 
921   // TODO: 'for base' flag
922 
923   if (Type == Dtor_Deleting) {
924     // The scalar deleting destructor takes an implicit int parameter.
925     ArgTys.push_back(CGM.getContext().IntTy);
926   }
927 }
928 
929 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
930   // The TU defining a dtor is only guaranteed to emit a base destructor.  All
931   // other destructor variants are delegating thunks.
932   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
933 }
934 
935 CharUnits
936 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
937   GD = GD.getCanonicalDecl();
938   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
939 
940   GlobalDecl LookupGD = GD;
941   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
942     // Complete destructors take a pointer to the complete object as a
943     // parameter, thus don't need this adjustment.
944     if (GD.getDtorType() == Dtor_Complete)
945       return CharUnits();
946 
947     // There's no Dtor_Base in vftable but it shares the this adjustment with
948     // the deleting one, so look it up instead.
949     LookupGD = GlobalDecl(DD, Dtor_Deleting);
950   }
951 
952   MicrosoftVTableContext::MethodVFTableLocation ML =
953       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
954   CharUnits Adjustment = ML.VFPtrOffset;
955 
956   // Normal virtual instance methods need to adjust from the vfptr that first
957   // defined the virtual method to the virtual base subobject, but destructors
958   // do not.  The vector deleting destructor thunk applies this adjustment for
959   // us if necessary.
960   if (isa<CXXDestructorDecl>(MD))
961     Adjustment = CharUnits::Zero();
962 
963   if (ML.VBase) {
964     const ASTRecordLayout &DerivedLayout =
965         CGM.getContext().getASTRecordLayout(MD->getParent());
966     Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
967   }
968 
969   return Adjustment;
970 }
971 
972 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
973     CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) {
974   if (!VirtualCall) {
975     // If the call of a virtual function is not virtual, we just have to
976     // compensate for the adjustment the virtual function does in its prologue.
977     CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
978     if (Adjustment.isZero())
979       return This;
980 
981     unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
982     llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
983     This = CGF.Builder.CreateBitCast(This, charPtrTy);
984     assert(Adjustment.isPositive());
985     return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity());
986   }
987 
988   GD = GD.getCanonicalDecl();
989   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
990 
991   GlobalDecl LookupGD = GD;
992   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
993     // Complete dtors take a pointer to the complete object,
994     // thus don't need adjustment.
995     if (GD.getDtorType() == Dtor_Complete)
996       return This;
997 
998     // There's only Dtor_Deleting in vftable but it shares the this adjustment
999     // with the base one, so look up the deleting one instead.
1000     LookupGD = GlobalDecl(DD, Dtor_Deleting);
1001   }
1002   MicrosoftVTableContext::MethodVFTableLocation ML =
1003       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1004 
1005   unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1006   llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1007   CharUnits StaticOffset = ML.VFPtrOffset;
1008 
1009   // Base destructors expect 'this' to point to the beginning of the base
1010   // subobject, not the first vfptr that happens to contain the virtual dtor.
1011   // However, we still need to apply the virtual base adjustment.
1012   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1013     StaticOffset = CharUnits::Zero();
1014 
1015   if (ML.VBase) {
1016     This = CGF.Builder.CreateBitCast(This, charPtrTy);
1017     llvm::Value *VBaseOffset =
1018         GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
1019     This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
1020   }
1021   if (!StaticOffset.isZero()) {
1022     assert(StaticOffset.isPositive());
1023     This = CGF.Builder.CreateBitCast(This, charPtrTy);
1024     if (ML.VBase) {
1025       // Non-virtual adjustment might result in a pointer outside the allocated
1026       // object, e.g. if the final overrider class is laid out after the virtual
1027       // base that declares a method in the most derived class.
1028       // FIXME: Update the code that emits this adjustment in thunks prologues.
1029       This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
1030     } else {
1031       This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
1032                                                     StaticOffset.getQuantity());
1033     }
1034   }
1035   return This;
1036 }
1037 
1038 static bool IsDeletingDtor(GlobalDecl GD) {
1039   const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
1040   if (isa<CXXDestructorDecl>(MD)) {
1041     return GD.getDtorType() == Dtor_Deleting;
1042   }
1043   return false;
1044 }
1045 
1046 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1047                                                 QualType &ResTy,
1048                                                 FunctionArgList &Params) {
1049   ASTContext &Context = getContext();
1050   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1051   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1052   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1053     ImplicitParamDecl *IsMostDerived
1054       = ImplicitParamDecl::Create(Context, nullptr,
1055                                   CGF.CurGD.getDecl()->getLocation(),
1056                                   &Context.Idents.get("is_most_derived"),
1057                                   Context.IntTy);
1058     // The 'most_derived' parameter goes second if the ctor is variadic and last
1059     // if it's not.  Dtors can't be variadic.
1060     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1061     if (FPT->isVariadic())
1062       Params.insert(Params.begin() + 1, IsMostDerived);
1063     else
1064       Params.push_back(IsMostDerived);
1065     getStructorImplicitParamDecl(CGF) = IsMostDerived;
1066   } else if (IsDeletingDtor(CGF.CurGD)) {
1067     ImplicitParamDecl *ShouldDelete
1068       = ImplicitParamDecl::Create(Context, nullptr,
1069                                   CGF.CurGD.getDecl()->getLocation(),
1070                                   &Context.Idents.get("should_call_delete"),
1071                                   Context.IntTy);
1072     Params.push_back(ShouldDelete);
1073     getStructorImplicitParamDecl(CGF) = ShouldDelete;
1074   }
1075 }
1076 
1077 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1078     CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1079   // In this ABI, every virtual function takes a pointer to one of the
1080   // subobjects that first defines it as the 'this' parameter, rather than a
1081   // pointer to the final overrider subobject. Thus, we need to adjust it back
1082   // to the final overrider subobject before use.
1083   // See comments in the MicrosoftVFTableContext implementation for the details.
1084   CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1085   if (Adjustment.isZero())
1086     return This;
1087 
1088   unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1089   llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1090              *thisTy = This->getType();
1091 
1092   This = CGF.Builder.CreateBitCast(This, charPtrTy);
1093   assert(Adjustment.isPositive());
1094   This =
1095       CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
1096   return CGF.Builder.CreateBitCast(This, thisTy);
1097 }
1098 
1099 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1100   EmitThisParam(CGF);
1101 
1102   /// If this is a function that the ABI specifies returns 'this', initialize
1103   /// the return slot to 'this' at the start of the function.
1104   ///
1105   /// Unlike the setting of return types, this is done within the ABI
1106   /// implementation instead of by clients of CGCXXABI because:
1107   /// 1) getThisValue is currently protected
1108   /// 2) in theory, an ABI could implement 'this' returns some other way;
1109   ///    HasThisReturn only specifies a contract, not the implementation
1110   if (HasThisReturn(CGF.CurGD))
1111     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1112 
1113   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1114   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1115     assert(getStructorImplicitParamDecl(CGF) &&
1116            "no implicit parameter for a constructor with virtual bases?");
1117     getStructorImplicitParamValue(CGF)
1118       = CGF.Builder.CreateLoad(
1119           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1120           "is_most_derived");
1121   }
1122 
1123   if (IsDeletingDtor(CGF.CurGD)) {
1124     assert(getStructorImplicitParamDecl(CGF) &&
1125            "no implicit parameter for a deleting destructor?");
1126     getStructorImplicitParamValue(CGF)
1127       = CGF.Builder.CreateLoad(
1128           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1129           "should_call_delete");
1130   }
1131 }
1132 
1133 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1134     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1135     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1136   assert(Type == Ctor_Complete || Type == Ctor_Base);
1137 
1138   // Check if we need a 'most_derived' parameter.
1139   if (!D->getParent()->getNumVBases())
1140     return 0;
1141 
1142   // Add the 'most_derived' argument second if we are variadic or last if not.
1143   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1144   llvm::Value *MostDerivedArg =
1145       llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1146   RValue RV = RValue::get(MostDerivedArg);
1147   if (MostDerivedArg) {
1148     if (FPT->isVariadic())
1149       Args.insert(Args.begin() + 1,
1150                   CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1151     else
1152       Args.add(RV, getContext().IntTy);
1153   }
1154 
1155   return 1;  // Added one arg.
1156 }
1157 
1158 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1159                                          const CXXDestructorDecl *DD,
1160                                          CXXDtorType Type, bool ForVirtualBase,
1161                                          bool Delegating, llvm::Value *This) {
1162   llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1163 
1164   if (DD->isVirtual()) {
1165     assert(Type != CXXDtorType::Dtor_Deleting &&
1166            "The deleting destructor should only be called via a virtual call");
1167     This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1168                                                     This, false);
1169   }
1170 
1171   // FIXME: Provide a source location here.
1172   CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
1173                         /*ImplicitParam=*/nullptr,
1174                         /*ImplicitParamTy=*/QualType(), nullptr, nullptr);
1175 }
1176 
1177 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1178                                             const CXXRecordDecl *RD) {
1179   MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1180   VPtrInfoVector VFPtrs = VFTContext.getVFPtrOffsets(RD);
1181 
1182   for (VPtrInfo *Info : VFPtrs) {
1183     llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1184     if (VTable->hasInitializer())
1185       continue;
1186 
1187     llvm::Constant *RTTI = getContext().getLangOpts().RTTIData
1188                                ? getMSCompleteObjectLocator(RD, Info)
1189                                : nullptr;
1190 
1191     const VTableLayout &VTLayout =
1192       VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1193     llvm::Constant *Init = CGVT.CreateVTableInitializer(
1194         RD, VTLayout.vtable_component_begin(),
1195         VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1196         VTLayout.getNumVTableThunks(), RTTI);
1197 
1198     VTable->setInitializer(Init);
1199   }
1200 }
1201 
1202 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1203     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1204     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1205   NeedsVirtualOffset = (NearestVBase != nullptr);
1206 
1207   (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1208   VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1209   llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID];
1210   if (!VTableAddressPoint) {
1211     assert(Base.getBase()->getNumVBases() &&
1212            !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1213   }
1214   return VTableAddressPoint;
1215 }
1216 
1217 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1218                               const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1219                               SmallString<256> &Name) {
1220   llvm::raw_svector_ostream Out(Name);
1221   MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1222 }
1223 
1224 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1225     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1226   (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1227   VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1228   llvm::GlobalValue *VFTable = VFTablesMap[ID];
1229   assert(VFTable && "Couldn't find a vftable for the given base?");
1230   return VFTable;
1231 }
1232 
1233 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1234                                                        CharUnits VPtrOffset) {
1235   // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1236   // shouldn't be used in the given record type. We want to cache this result in
1237   // VFTablesMap, thus a simple zero check is not sufficient.
1238   VFTableIdTy ID(RD, VPtrOffset);
1239   VTablesMapTy::iterator I;
1240   bool Inserted;
1241   std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1242   if (!Inserted)
1243     return I->second;
1244 
1245   llvm::GlobalVariable *&VTable = I->second;
1246 
1247   MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1248   const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1249 
1250   if (DeferredVFTables.insert(RD)) {
1251     // We haven't processed this record type before.
1252     // Queue up this v-table for possible deferred emission.
1253     CGM.addDeferredVTable(RD);
1254 
1255 #ifndef NDEBUG
1256     // Create all the vftables at once in order to make sure each vftable has
1257     // a unique mangled name.
1258     llvm::StringSet<> ObservedMangledNames;
1259     for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1260       SmallString<256> Name;
1261       mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1262       if (!ObservedMangledNames.insert(Name.str()))
1263         llvm_unreachable("Already saw this mangling before?");
1264     }
1265 #endif
1266   }
1267 
1268   for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1269     if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset)
1270       continue;
1271     SmallString<256> VFTableName;
1272     mangleVFTableName(getMangleContext(), RD, VFPtrs[J], VFTableName);
1273     StringRef VTableName = VFTableName;
1274 
1275     uint64_t NumVTableSlots =
1276         VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC)
1277             .getNumVTableComponents();
1278     llvm::GlobalValue::LinkageTypes VTableLinkage =
1279         llvm::GlobalValue::ExternalLinkage;
1280     llvm::ArrayType *VTableType =
1281         llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1282     if (getContext().getLangOpts().RTTIData) {
1283       VTableLinkage = llvm::GlobalValue::PrivateLinkage;
1284       VTableName = "";
1285     }
1286 
1287     VTable = CGM.getModule().getNamedGlobal(VFTableName);
1288     if (!VTable) {
1289       // Create a backing variable for the contents of VTable.  The VTable may
1290       // or may not include space for a pointer to RTTI data.
1291       llvm::GlobalValue *VFTable = VTable = new llvm::GlobalVariable(
1292           CGM.getModule(), VTableType, /*isConstant=*/true, VTableLinkage,
1293           /*Initializer=*/nullptr, VTableName);
1294       VTable->setUnnamedAddr(true);
1295 
1296       // Only insert a pointer into the VFTable for RTTI data if we are not
1297       // importing it.  We never reference the RTTI data directly so there is no
1298       // need to make room for it.
1299       if (getContext().getLangOpts().RTTIData &&
1300           !RD->hasAttr<DLLImportAttr>()) {
1301         llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1302                                      llvm::ConstantInt::get(CGM.IntTy, 1)};
1303         // Create a GEP which points just after the first entry in the VFTable,
1304         // this should be the location of the first virtual method.
1305         llvm::Constant *VTableGEP =
1306             llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, GEPIndices);
1307         // The symbol for the VFTable is an alias to the GEP.  It is
1308         // transparent, to other modules, what the nature of this symbol is; all
1309         // that matters is that the alias be the address of the first virtual
1310         // method.
1311         VFTable = llvm::GlobalAlias::create(
1312             cast<llvm::SequentialType>(VTableGEP->getType())->getElementType(),
1313             /*AddressSpace=*/0, llvm::GlobalValue::ExternalLinkage,
1314             VFTableName.str(), VTableGEP, &CGM.getModule());
1315       } else {
1316         // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1317         // be referencing any RTTI data.  The GlobalVariable will end up being
1318         // an appropriate definition of the VFTable.
1319         VTable->setName(VFTableName.str());
1320       }
1321 
1322       VFTable->setUnnamedAddr(true);
1323       if (RD->hasAttr<DLLImportAttr>())
1324         VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1325       else if (RD->hasAttr<DLLExportAttr>())
1326         VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1327 
1328       llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD);
1329       if (VFTable != VTable) {
1330         if (llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage)) {
1331           // AvailableExternally implies that we grabbed the data from another
1332           // executable.  No need to stick the alias in a Comdat.
1333         } else if (llvm::GlobalValue::isInternalLinkage(VFTableLinkage) ||
1334                    llvm::GlobalValue::isWeakODRLinkage(VFTableLinkage) ||
1335                    llvm::GlobalValue::isLinkOnceODRLinkage(VFTableLinkage)) {
1336           // The alias is going to be dropped into a Comdat, no need to make it
1337           // weak.
1338           if (!llvm::GlobalValue::isInternalLinkage(VFTableLinkage))
1339             VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1340           llvm::Comdat *C =
1341               CGM.getModule().getOrInsertComdat(VFTable->getName());
1342           // We must indicate which VFTable is larger to support linking between
1343           // translation units which do and do not have RTTI data.  The largest
1344           // VFTable contains the RTTI data; translation units which reference
1345           // the smaller VFTable always reference it relative to the first
1346           // virtual method.
1347           C->setSelectionKind(llvm::Comdat::Largest);
1348           VTable->setComdat(C);
1349         } else {
1350           llvm_unreachable("unexpected linkage for vftable!");
1351         }
1352       }
1353       VFTable->setLinkage(VFTableLinkage);
1354       CGM.setGlobalVisibility(VFTable, RD);
1355       VFTablesMap[ID] = VFTable;
1356     }
1357     break;
1358   }
1359 
1360   return VTable;
1361 }
1362 
1363 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1364                                                         GlobalDecl GD,
1365                                                         llvm::Value *This,
1366                                                         llvm::Type *Ty) {
1367   GD = GD.getCanonicalDecl();
1368   CGBuilderTy &Builder = CGF.Builder;
1369 
1370   Ty = Ty->getPointerTo()->getPointerTo();
1371   llvm::Value *VPtr =
1372       adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1373   llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
1374 
1375   MicrosoftVTableContext::MethodVFTableLocation ML =
1376       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1377   llvm::Value *VFuncPtr =
1378       Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1379   return Builder.CreateLoad(VFuncPtr);
1380 }
1381 
1382 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1383                                                 const CXXDestructorDecl *Dtor,
1384                                                 CXXDtorType DtorType,
1385                                                 SourceLocation CallLoc,
1386                                                 llvm::Value *This) {
1387   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1388 
1389   // We have only one destructor in the vftable but can get both behaviors
1390   // by passing an implicit int parameter.
1391   GlobalDecl GD(Dtor, Dtor_Deleting);
1392   const CGFunctionInfo *FInfo =
1393       &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
1394   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1395   llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
1396 
1397   ASTContext &Context = CGF.getContext();
1398   llvm::Value *ImplicitParam =
1399       llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1400                              DtorType == Dtor_Deleting);
1401 
1402   This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1403   CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1404                         ImplicitParam, Context.IntTy, nullptr, nullptr);
1405 }
1406 
1407 const VBTableGlobals &
1408 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1409   // At this layer, we can key the cache off of a single class, which is much
1410   // easier than caching each vbtable individually.
1411   llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1412   bool Added;
1413   std::tie(Entry, Added) =
1414       VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1415   VBTableGlobals &VBGlobals = Entry->second;
1416   if (!Added)
1417     return VBGlobals;
1418 
1419   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1420   VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1421 
1422   // Cache the globals for all vbtables so we don't have to recompute the
1423   // mangled names.
1424   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1425   for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1426                                       E = VBGlobals.VBTables->end();
1427        I != E; ++I) {
1428     VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1429   }
1430 
1431   return VBGlobals;
1432 }
1433 
1434 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1435     const CXXMethodDecl *MD,
1436     const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1437   // Calculate the mangled name.
1438   SmallString<256> ThunkName;
1439   llvm::raw_svector_ostream Out(ThunkName);
1440   getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1441   Out.flush();
1442 
1443   // If the thunk has been generated previously, just return it.
1444   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1445     return cast<llvm::Function>(GV);
1446 
1447   // Create the llvm::Function.
1448   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1449   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1450   llvm::Function *ThunkFn =
1451       llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1452                              ThunkName.str(), &CGM.getModule());
1453   assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1454 
1455   ThunkFn->setLinkage(MD->isExternallyVisible()
1456                           ? llvm::GlobalValue::LinkOnceODRLinkage
1457                           : llvm::GlobalValue::InternalLinkage);
1458 
1459   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1460   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1461 
1462   // Start codegen.
1463   CodeGenFunction CGF(CGM);
1464   CGF.StartThunk(ThunkFn, MD, FnInfo);
1465 
1466   // Load the vfptr and then callee from the vftable.  The callee should have
1467   // adjusted 'this' so that the vfptr is at offset zero.
1468   llvm::Value *This = CGF.LoadCXXThis();
1469   llvm::Value *VTable =
1470       CGF.GetVTablePtr(This, ThunkTy->getPointerTo()->getPointerTo());
1471   llvm::Value *VFuncPtr =
1472       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1473   llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr);
1474 
1475   CGF.EmitCallAndReturnForThunk(Callee, 0);
1476 
1477   return ThunkFn;
1478 }
1479 
1480 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1481   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1482   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1483     const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1484     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1485     emitVBTableDefinition(*VBT, RD, GV);
1486   }
1487 }
1488 
1489 llvm::GlobalVariable *
1490 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1491                                   llvm::GlobalVariable::LinkageTypes Linkage) {
1492   SmallString<256> OutName;
1493   llvm::raw_svector_ostream Out(OutName);
1494   getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1495   Out.flush();
1496   StringRef Name = OutName.str();
1497 
1498   llvm::ArrayType *VBTableType =
1499       llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1500 
1501   assert(!CGM.getModule().getNamedGlobal(Name) &&
1502          "vbtable with this name already exists: mangling bug?");
1503   llvm::GlobalVariable *GV =
1504       CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1505   GV->setUnnamedAddr(true);
1506 
1507   if (RD->hasAttr<DLLImportAttr>())
1508     GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1509   else if (RD->hasAttr<DLLExportAttr>())
1510     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1511 
1512   return GV;
1513 }
1514 
1515 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1516                                             const CXXRecordDecl *RD,
1517                                             llvm::GlobalVariable *GV) const {
1518   const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1519 
1520   assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1521          "should only emit vbtables for classes with vbtables");
1522 
1523   const ASTRecordLayout &BaseLayout =
1524       CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr);
1525   const ASTRecordLayout &DerivedLayout =
1526     CGM.getContext().getASTRecordLayout(RD);
1527 
1528   SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
1529                                            nullptr);
1530 
1531   // The offset from ReusingBase's vbptr to itself always leads.
1532   CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1533   Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1534 
1535   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1536   for (const auto &I : ReusingBase->vbases()) {
1537     const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
1538     CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1539     assert(!Offset.isNegative());
1540 
1541     // Make it relative to the subobject vbptr.
1542     CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1543     if (VBT.getVBaseWithVPtr())
1544       CompleteVBPtrOffset +=
1545           DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
1546     Offset -= CompleteVBPtrOffset;
1547 
1548     unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1549     assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
1550     Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1551   }
1552 
1553   assert(Offsets.size() ==
1554          cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1555                                ->getElementType())->getNumElements());
1556   llvm::ArrayType *VBTableType =
1557     llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1558   llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1559   GV->setInitializer(Init);
1560 
1561   // Set the right visibility.
1562   CGM.setGlobalVisibility(GV, RD);
1563 }
1564 
1565 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1566                                                     llvm::Value *This,
1567                                                     const ThisAdjustment &TA) {
1568   if (TA.isEmpty())
1569     return This;
1570 
1571   llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1572 
1573   if (!TA.Virtual.isEmpty()) {
1574     assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1575     // Adjust the this argument based on the vtordisp value.
1576     llvm::Value *VtorDispPtr =
1577         CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1578     VtorDispPtr =
1579         CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1580     llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1581     V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1582 
1583     if (TA.Virtual.Microsoft.VBPtrOffset) {
1584       // If the final overrider is defined in a virtual base other than the one
1585       // that holds the vfptr, we have to use a vtordispex thunk which looks up
1586       // the vbtable of the derived class.
1587       assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1588       assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1589       llvm::Value *VBPtr;
1590       llvm::Value *VBaseOffset =
1591           GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1592                                   TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1593       V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1594     }
1595   }
1596 
1597   if (TA.NonVirtual) {
1598     // Non-virtual adjustment might result in a pointer outside the allocated
1599     // object, e.g. if the final overrider class is laid out after the virtual
1600     // base that declares a method in the most derived class.
1601     V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1602   }
1603 
1604   // Don't need to bitcast back, the call CodeGen will handle this.
1605   return V;
1606 }
1607 
1608 llvm::Value *
1609 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1610                                          const ReturnAdjustment &RA) {
1611   if (RA.isEmpty())
1612     return Ret;
1613 
1614   llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1615 
1616   if (RA.Virtual.Microsoft.VBIndex) {
1617     assert(RA.Virtual.Microsoft.VBIndex > 0);
1618     int32_t IntSize =
1619         getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1620     llvm::Value *VBPtr;
1621     llvm::Value *VBaseOffset =
1622         GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1623                                 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1624     V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1625   }
1626 
1627   if (RA.NonVirtual)
1628     V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1629 
1630   // Cast back to the original type.
1631   return CGF.Builder.CreateBitCast(V, Ret->getType());
1632 }
1633 
1634 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1635                                    QualType elementType) {
1636   // Microsoft seems to completely ignore the possibility of a
1637   // two-argument usual deallocation function.
1638   return elementType.isDestructedType();
1639 }
1640 
1641 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1642   // Microsoft seems to completely ignore the possibility of a
1643   // two-argument usual deallocation function.
1644   return expr->getAllocatedType().isDestructedType();
1645 }
1646 
1647 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1648   // The array cookie is always a size_t; we then pad that out to the
1649   // alignment of the element type.
1650   ASTContext &Ctx = getContext();
1651   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1652                   Ctx.getTypeAlignInChars(type));
1653 }
1654 
1655 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1656                                                   llvm::Value *allocPtr,
1657                                                   CharUnits cookieSize) {
1658   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1659   llvm::Value *numElementsPtr =
1660     CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1661   return CGF.Builder.CreateLoad(numElementsPtr);
1662 }
1663 
1664 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1665                                                     llvm::Value *newPtr,
1666                                                     llvm::Value *numElements,
1667                                                     const CXXNewExpr *expr,
1668                                                     QualType elementType) {
1669   assert(requiresArrayCookie(expr));
1670 
1671   // The size of the cookie.
1672   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1673 
1674   // Compute an offset to the cookie.
1675   llvm::Value *cookiePtr = newPtr;
1676 
1677   // Write the number of elements into the appropriate slot.
1678   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1679   llvm::Value *numElementsPtr
1680     = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1681   CGF.Builder.CreateStore(numElements, numElementsPtr);
1682 
1683   // Finally, compute a pointer to the actual data buffer by skipping
1684   // over the cookie completely.
1685   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1686                                                 cookieSize.getQuantity());
1687 }
1688 
1689 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1690                                       llvm::GlobalVariable *GV,
1691                                       bool PerformInit) {
1692   // MSVC only uses guards for static locals.
1693   if (!D.isStaticLocal()) {
1694     assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
1695     // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
1696     CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
1697     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1698     return;
1699   }
1700 
1701   // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1702   // threadsafe.  Since the user may be linking in inline functions compiled by
1703   // cl.exe, there's no reason to provide a false sense of security by using
1704   // critical sections here.
1705 
1706   if (D.getTLSKind())
1707     CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1708 
1709   CGBuilderTy &Builder = CGF.Builder;
1710   llvm::IntegerType *GuardTy = CGF.Int32Ty;
1711   llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1712 
1713   // Get the guard variable for this function if we have one already.
1714   GuardInfo *GI = &GuardVariableMap[D.getDeclContext()];
1715 
1716   unsigned BitIndex;
1717   if (D.isStaticLocal() && D.isExternallyVisible()) {
1718     // Externally visible variables have to be numbered in Sema to properly
1719     // handle unreachable VarDecls.
1720     BitIndex = getContext().getStaticLocalNumber(&D);
1721     assert(BitIndex > 0);
1722     BitIndex--;
1723   } else {
1724     // Non-externally visible variables are numbered here in CodeGen.
1725     BitIndex = GI->BitIndex++;
1726   }
1727 
1728   if (BitIndex >= 32) {
1729     if (D.isExternallyVisible())
1730       ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1731     BitIndex %= 32;
1732     GI->Guard = nullptr;
1733   }
1734 
1735   // Lazily create the i32 bitfield for this function.
1736   if (!GI->Guard) {
1737     // Mangle the name for the guard.
1738     SmallString<256> GuardName;
1739     {
1740       llvm::raw_svector_ostream Out(GuardName);
1741       getMangleContext().mangleStaticGuardVariable(&D, Out);
1742       Out.flush();
1743     }
1744 
1745     // Create the guard variable with a zero-initializer. Just absorb linkage,
1746     // visibility and dll storage class from the guarded variable.
1747     GI->Guard =
1748         new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1749                                  GV->getLinkage(), Zero, GuardName.str());
1750     GI->Guard->setVisibility(GV->getVisibility());
1751     GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
1752   } else {
1753     assert(GI->Guard->getLinkage() == GV->getLinkage() &&
1754            "static local from the same function had different linkage");
1755   }
1756 
1757   // Pseudo code for the test:
1758   // if (!(GuardVar & MyGuardBit)) {
1759   //   GuardVar |= MyGuardBit;
1760   //   ... initialize the object ...;
1761   // }
1762 
1763   // Test our bit from the guard variable.
1764   llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1765   llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
1766   llvm::Value *IsInitialized =
1767       Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1768   llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1769   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1770   Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1771 
1772   // Set our bit in the guard variable and emit the initializer and add a global
1773   // destructor if appropriate.
1774   CGF.EmitBlock(InitBlock);
1775   Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
1776   CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1777   Builder.CreateBr(EndBlock);
1778 
1779   // Continue.
1780   CGF.EmitBlock(EndBlock);
1781 }
1782 
1783 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1784   // Null-ness for function memptrs only depends on the first field, which is
1785   // the function pointer.  The rest don't matter, so we can zero initialize.
1786   if (MPT->isMemberFunctionPointer())
1787     return true;
1788 
1789   // The virtual base adjustment field is always -1 for null, so if we have one
1790   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
1791   // valid field offset.
1792   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1793   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1794   return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
1795           RD->nullFieldOffsetIsZero());
1796 }
1797 
1798 llvm::Type *
1799 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1800   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1801   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1802   llvm::SmallVector<llvm::Type *, 4> fields;
1803   if (MPT->isMemberFunctionPointer())
1804     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
1805   else
1806     fields.push_back(CGM.IntTy);  // FieldOffset
1807 
1808   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1809                                           Inheritance))
1810     fields.push_back(CGM.IntTy);
1811   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1812     fields.push_back(CGM.IntTy);
1813   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1814     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
1815 
1816   if (fields.size() == 1)
1817     return fields[0];
1818   return llvm::StructType::get(CGM.getLLVMContext(), fields);
1819 }
1820 
1821 void MicrosoftCXXABI::
1822 GetNullMemberPointerFields(const MemberPointerType *MPT,
1823                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1824   assert(fields.empty());
1825   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1826   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1827   if (MPT->isMemberFunctionPointer()) {
1828     // FunctionPointerOrVirtualThunk
1829     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1830   } else {
1831     if (RD->nullFieldOffsetIsZero())
1832       fields.push_back(getZeroInt());  // FieldOffset
1833     else
1834       fields.push_back(getAllOnesInt());  // FieldOffset
1835   }
1836 
1837   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1838                                           Inheritance))
1839     fields.push_back(getZeroInt());
1840   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1841     fields.push_back(getZeroInt());
1842   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1843     fields.push_back(getAllOnesInt());
1844 }
1845 
1846 llvm::Constant *
1847 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1848   llvm::SmallVector<llvm::Constant *, 4> fields;
1849   GetNullMemberPointerFields(MPT, fields);
1850   if (fields.size() == 1)
1851     return fields[0];
1852   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1853   assert(Res->getType() == ConvertMemberPointerType(MPT));
1854   return Res;
1855 }
1856 
1857 llvm::Constant *
1858 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1859                                        bool IsMemberFunction,
1860                                        const CXXRecordDecl *RD,
1861                                        CharUnits NonVirtualBaseAdjustment)
1862 {
1863   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1864 
1865   // Single inheritance class member pointer are represented as scalars instead
1866   // of aggregates.
1867   if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
1868     return FirstField;
1869 
1870   llvm::SmallVector<llvm::Constant *, 4> fields;
1871   fields.push_back(FirstField);
1872 
1873   if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
1874     fields.push_back(llvm::ConstantInt::get(
1875       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
1876 
1877   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
1878     CharUnits Offs = CharUnits::Zero();
1879     if (RD->getNumVBases())
1880       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1881     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
1882   }
1883 
1884   // The rest of the fields are adjusted by conversions to a more derived class.
1885   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1886     fields.push_back(getZeroInt());
1887 
1888   return llvm::ConstantStruct::getAnon(fields);
1889 }
1890 
1891 llvm::Constant *
1892 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1893                                        CharUnits offset) {
1894   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1895   llvm::Constant *FirstField =
1896     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
1897   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1898                                CharUnits::Zero());
1899 }
1900 
1901 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1902   return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1903 }
1904 
1905 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1906                                                    QualType MPType) {
1907   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1908   const ValueDecl *MPD = MP.getMemberPointerDecl();
1909   if (!MPD)
1910     return EmitNullMemberPointer(MPT);
1911 
1912   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1913 
1914   // FIXME PR15713: Support virtual inheritance paths.
1915 
1916   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1917     return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
1918                               ThisAdjustment);
1919 
1920   CharUnits FieldOffset =
1921     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1922   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1923 }
1924 
1925 llvm::Constant *
1926 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1927                                     const CXXMethodDecl *MD,
1928                                     CharUnits NonVirtualBaseAdjustment) {
1929   assert(MD->isInstance() && "Member function must not be static!");
1930   MD = MD->getCanonicalDecl();
1931   RD = RD->getMostRecentDecl();
1932   CodeGenTypes &Types = CGM.getTypes();
1933 
1934   llvm::Constant *FirstField;
1935   if (!MD->isVirtual()) {
1936     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1937     llvm::Type *Ty;
1938     // Check whether the function has a computable LLVM signature.
1939     if (Types.isFuncTypeConvertible(FPT)) {
1940       // The function has a computable LLVM signature; use the correct type.
1941       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1942     } else {
1943       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1944       // function type is incomplete.
1945       Ty = CGM.PtrDiffTy;
1946     }
1947     FirstField = CGM.GetAddrOfFunction(MD, Ty);
1948     FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1949   } else {
1950     MicrosoftVTableContext::MethodVFTableLocation ML =
1951         CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1952     if (MD->isVariadic()) {
1953       CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1954       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1955     } else if (!CGM.getTypes().isFuncTypeConvertible(
1956                     MD->getType()->castAs<FunctionType>())) {
1957       CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1958                                "incomplete return or parameter type");
1959       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1960     } else if (ML.VBase) {
1961       CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1962                                "member function in virtual base class");
1963       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1964     } else {
1965       llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
1966       FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1967       // Include the vfptr adjustment if the method is in a non-primary vftable.
1968       NonVirtualBaseAdjustment += ML.VFPtrOffset;
1969     }
1970   }
1971 
1972   // The rest of the fields are common with data member pointers.
1973   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1974                                NonVirtualBaseAdjustment);
1975 }
1976 
1977 /// Member pointers are the same if they're either bitwise identical *or* both
1978 /// null.  Null-ness for function members is determined by the first field,
1979 /// while for data member pointers we must compare all fields.
1980 llvm::Value *
1981 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1982                                              llvm::Value *L,
1983                                              llvm::Value *R,
1984                                              const MemberPointerType *MPT,
1985                                              bool Inequality) {
1986   CGBuilderTy &Builder = CGF.Builder;
1987 
1988   // Handle != comparisons by switching the sense of all boolean operations.
1989   llvm::ICmpInst::Predicate Eq;
1990   llvm::Instruction::BinaryOps And, Or;
1991   if (Inequality) {
1992     Eq = llvm::ICmpInst::ICMP_NE;
1993     And = llvm::Instruction::Or;
1994     Or = llvm::Instruction::And;
1995   } else {
1996     Eq = llvm::ICmpInst::ICMP_EQ;
1997     And = llvm::Instruction::And;
1998     Or = llvm::Instruction::Or;
1999   }
2000 
2001   // If this is a single field member pointer (single inheritance), this is a
2002   // single icmp.
2003   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2004   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2005   if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2006                                          Inheritance))
2007     return Builder.CreateICmp(Eq, L, R);
2008 
2009   // Compare the first field.
2010   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2011   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2012   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2013 
2014   // Compare everything other than the first field.
2015   llvm::Value *Res = nullptr;
2016   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2017   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2018     llvm::Value *LF = Builder.CreateExtractValue(L, I);
2019     llvm::Value *RF = Builder.CreateExtractValue(R, I);
2020     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2021     if (Res)
2022       Res = Builder.CreateBinOp(And, Res, Cmp);
2023     else
2024       Res = Cmp;
2025   }
2026 
2027   // Check if the first field is 0 if this is a function pointer.
2028   if (MPT->isMemberFunctionPointer()) {
2029     // (l1 == r1 && ...) || l0 == 0
2030     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2031     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2032     Res = Builder.CreateBinOp(Or, Res, IsZero);
2033   }
2034 
2035   // Combine the comparison of the first field, which must always be true for
2036   // this comparison to succeeed.
2037   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2038 }
2039 
2040 llvm::Value *
2041 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2042                                             llvm::Value *MemPtr,
2043                                             const MemberPointerType *MPT) {
2044   CGBuilderTy &Builder = CGF.Builder;
2045   llvm::SmallVector<llvm::Constant *, 4> fields;
2046   // We only need one field for member functions.
2047   if (MPT->isMemberFunctionPointer())
2048     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2049   else
2050     GetNullMemberPointerFields(MPT, fields);
2051   assert(!fields.empty());
2052   llvm::Value *FirstField = MemPtr;
2053   if (MemPtr->getType()->isStructTy())
2054     FirstField = Builder.CreateExtractValue(MemPtr, 0);
2055   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2056 
2057   // For function member pointers, we only need to test the function pointer
2058   // field.  The other fields if any can be garbage.
2059   if (MPT->isMemberFunctionPointer())
2060     return Res;
2061 
2062   // Otherwise, emit a series of compares and combine the results.
2063   for (int I = 1, E = fields.size(); I < E; ++I) {
2064     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2065     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2066     Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2067   }
2068   return Res;
2069 }
2070 
2071 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2072                                                   llvm::Constant *Val) {
2073   // Function pointers are null if the pointer in the first field is null.
2074   if (MPT->isMemberFunctionPointer()) {
2075     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2076       Val->getAggregateElement(0U) : Val;
2077     return FirstField->isNullValue();
2078   }
2079 
2080   // If it's not a function pointer and it's zero initializable, we can easily
2081   // check zero.
2082   if (isZeroInitializable(MPT) && Val->isNullValue())
2083     return true;
2084 
2085   // Otherwise, break down all the fields for comparison.  Hopefully these
2086   // little Constants are reused, while a big null struct might not be.
2087   llvm::SmallVector<llvm::Constant *, 4> Fields;
2088   GetNullMemberPointerFields(MPT, Fields);
2089   if (Fields.size() == 1) {
2090     assert(Val->getType()->isIntegerTy());
2091     return Val == Fields[0];
2092   }
2093 
2094   unsigned I, E;
2095   for (I = 0, E = Fields.size(); I != E; ++I) {
2096     if (Val->getAggregateElement(I) != Fields[I])
2097       break;
2098   }
2099   return I == E;
2100 }
2101 
2102 llvm::Value *
2103 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2104                                          llvm::Value *This,
2105                                          llvm::Value *VBPtrOffset,
2106                                          llvm::Value *VBTableOffset,
2107                                          llvm::Value **VBPtrOut) {
2108   CGBuilderTy &Builder = CGF.Builder;
2109   // Load the vbtable pointer from the vbptr in the instance.
2110   This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
2111   llvm::Value *VBPtr =
2112     Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
2113   if (VBPtrOut) *VBPtrOut = VBPtr;
2114   VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
2115   llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
2116 
2117   // Load an i32 offset from the vb-table.
2118   llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
2119   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2120   return Builder.CreateLoad(VBaseOffs, "vbase_offs");
2121 }
2122 
2123 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2124 // it.
2125 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2126     CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2127     llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2128   CGBuilderTy &Builder = CGF.Builder;
2129   Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
2130   llvm::BasicBlock *OriginalBB = nullptr;
2131   llvm::BasicBlock *SkipAdjustBB = nullptr;
2132   llvm::BasicBlock *VBaseAdjustBB = nullptr;
2133 
2134   // In the unspecified inheritance model, there might not be a vbtable at all,
2135   // in which case we need to skip the virtual base lookup.  If there is a
2136   // vbtable, the first entry is a no-op entry that gives back the original
2137   // base, so look for a virtual base adjustment offset of zero.
2138   if (VBPtrOffset) {
2139     OriginalBB = Builder.GetInsertBlock();
2140     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2141     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2142     llvm::Value *IsVirtual =
2143       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2144                            "memptr.is_vbase");
2145     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2146     CGF.EmitBlock(VBaseAdjustBB);
2147   }
2148 
2149   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2150   // know the vbptr offset.
2151   if (!VBPtrOffset) {
2152     CharUnits offs = CharUnits::Zero();
2153     if (!RD->hasDefinition()) {
2154       DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2155       unsigned DiagID = Diags.getCustomDiagID(
2156           DiagnosticsEngine::Error,
2157           "member pointer representation requires a "
2158           "complete class type for %0 to perform this expression");
2159       Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2160     } else if (RD->getNumVBases())
2161       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2162     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2163   }
2164   llvm::Value *VBPtr = nullptr;
2165   llvm::Value *VBaseOffs =
2166     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2167   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2168 
2169   // Merge control flow with the case where we didn't have to adjust.
2170   if (VBaseAdjustBB) {
2171     Builder.CreateBr(SkipAdjustBB);
2172     CGF.EmitBlock(SkipAdjustBB);
2173     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2174     Phi->addIncoming(Base, OriginalBB);
2175     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2176     return Phi;
2177   }
2178   return AdjustedBase;
2179 }
2180 
2181 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2182     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
2183     const MemberPointerType *MPT) {
2184   assert(MPT->isMemberDataPointer());
2185   unsigned AS = Base->getType()->getPointerAddressSpace();
2186   llvm::Type *PType =
2187       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2188   CGBuilderTy &Builder = CGF.Builder;
2189   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2190   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2191 
2192   // Extract the fields we need, regardless of model.  We'll apply them if we
2193   // have them.
2194   llvm::Value *FieldOffset = MemPtr;
2195   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2196   llvm::Value *VBPtrOffset = nullptr;
2197   if (MemPtr->getType()->isStructTy()) {
2198     // We need to extract values.
2199     unsigned I = 0;
2200     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2201     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2202       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2203     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2204       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2205   }
2206 
2207   if (VirtualBaseAdjustmentOffset) {
2208     Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2209                              VBPtrOffset);
2210   }
2211 
2212   // Cast to char*.
2213   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
2214 
2215   // Apply the offset, which we assume is non-null.
2216   llvm::Value *Addr =
2217     Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
2218 
2219   // Cast the address to the appropriate pointer type, adopting the address
2220   // space of the base pointer.
2221   return Builder.CreateBitCast(Addr, PType);
2222 }
2223 
2224 static MSInheritanceAttr::Spelling
2225 getInheritanceFromMemptr(const MemberPointerType *MPT) {
2226   return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
2227 }
2228 
2229 llvm::Value *
2230 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
2231                                              const CastExpr *E,
2232                                              llvm::Value *Src) {
2233   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
2234          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
2235          E->getCastKind() == CK_ReinterpretMemberPointer);
2236 
2237   // Use constant emission if we can.
2238   if (isa<llvm::Constant>(Src))
2239     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
2240 
2241   // We may be adding or dropping fields from the member pointer, so we need
2242   // both types and the inheritance models of both records.
2243   const MemberPointerType *SrcTy =
2244     E->getSubExpr()->getType()->castAs<MemberPointerType>();
2245   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2246   bool IsFunc = SrcTy->isMemberFunctionPointer();
2247 
2248   // If the classes use the same null representation, reinterpret_cast is a nop.
2249   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
2250   if (IsReinterpret && IsFunc)
2251     return Src;
2252 
2253   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
2254   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
2255   if (IsReinterpret &&
2256       SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
2257     return Src;
2258 
2259   CGBuilderTy &Builder = CGF.Builder;
2260 
2261   // Branch past the conversion if Src is null.
2262   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
2263   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
2264 
2265   // C++ 5.2.10p9: The null member pointer value is converted to the null member
2266   //   pointer value of the destination type.
2267   if (IsReinterpret) {
2268     // For reinterpret casts, sema ensures that src and dst are both functions
2269     // or data and have the same size, which means the LLVM types should match.
2270     assert(Src->getType() == DstNull->getType());
2271     return Builder.CreateSelect(IsNotNull, Src, DstNull);
2272   }
2273 
2274   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
2275   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
2276   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
2277   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
2278   CGF.EmitBlock(ConvertBB);
2279 
2280   // Decompose src.
2281   llvm::Value *FirstField = Src;
2282   llvm::Value *NonVirtualBaseAdjustment = nullptr;
2283   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2284   llvm::Value *VBPtrOffset = nullptr;
2285   MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
2286   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2287     // We need to extract values.
2288     unsigned I = 0;
2289     FirstField = Builder.CreateExtractValue(Src, I++);
2290     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2291       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
2292     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2293       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
2294     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2295       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
2296   }
2297 
2298   // For data pointers, we adjust the field offset directly.  For functions, we
2299   // have a separate field.
2300   llvm::Constant *Adj = getMemberPointerAdjustment(E);
2301   if (Adj) {
2302     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2303     llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
2304     bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2305     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
2306       NVAdjustField = getZeroInt();
2307     if (isDerivedToBase)
2308       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
2309     else
2310       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
2311   }
2312 
2313   // FIXME PR15713: Support conversions through virtually derived classes.
2314 
2315   // Recompose dst from the null struct and the adjusted fields from src.
2316   MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
2317   llvm::Value *Dst;
2318   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2319     Dst = FirstField;
2320   } else {
2321     Dst = llvm::UndefValue::get(DstNull->getType());
2322     unsigned Idx = 0;
2323     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2324     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2325       Dst = Builder.CreateInsertValue(
2326         Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2327     if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2328       Dst = Builder.CreateInsertValue(
2329         Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2330     if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2331       Dst = Builder.CreateInsertValue(
2332         Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2333   }
2334   Builder.CreateBr(ContinueBB);
2335 
2336   // In the continuation, choose between DstNull and Dst.
2337   CGF.EmitBlock(ContinueBB);
2338   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2339   Phi->addIncoming(DstNull, OriginalBB);
2340   Phi->addIncoming(Dst, ConvertBB);
2341   return Phi;
2342 }
2343 
2344 llvm::Constant *
2345 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2346                                              llvm::Constant *Src) {
2347   const MemberPointerType *SrcTy =
2348     E->getSubExpr()->getType()->castAs<MemberPointerType>();
2349   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2350 
2351   // If src is null, emit a new null for dst.  We can't return src because dst
2352   // might have a new representation.
2353   if (MemberPointerConstantIsNull(SrcTy, Src))
2354     return EmitNullMemberPointer(DstTy);
2355 
2356   // We don't need to do anything for reinterpret_casts of non-null member
2357   // pointers.  We should only get here when the two type representations have
2358   // the same size.
2359   if (E->getCastKind() == CK_ReinterpretMemberPointer)
2360     return Src;
2361 
2362   MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2363   MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2364 
2365   // Decompose src.
2366   llvm::Constant *FirstField = Src;
2367   llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2368   llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2369   llvm::Constant *VBPtrOffset = nullptr;
2370   bool IsFunc = SrcTy->isMemberFunctionPointer();
2371   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2372     // We need to extract values.
2373     unsigned I = 0;
2374     FirstField = Src->getAggregateElement(I++);
2375     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2376       NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2377     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2378       VBPtrOffset = Src->getAggregateElement(I++);
2379     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2380       VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2381   }
2382 
2383   // For data pointers, we adjust the field offset directly.  For functions, we
2384   // have a separate field.
2385   llvm::Constant *Adj = getMemberPointerAdjustment(E);
2386   if (Adj) {
2387     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2388     llvm::Constant *&NVAdjustField =
2389       IsFunc ? NonVirtualBaseAdjustment : FirstField;
2390     bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2391     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
2392       NVAdjustField = getZeroInt();
2393     if (IsDerivedToBase)
2394       NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2395     else
2396       NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2397   }
2398 
2399   // FIXME PR15713: Support conversions through virtually derived classes.
2400 
2401   // Recompose dst from the null struct and the adjusted fields from src.
2402   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2403     return FirstField;
2404 
2405   llvm::SmallVector<llvm::Constant *, 4> Fields;
2406   Fields.push_back(FirstField);
2407   if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2408     Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2409   if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2410     Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2411   if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2412     Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2413   return llvm::ConstantStruct::getAnon(Fields);
2414 }
2415 
2416 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2417     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2418     llvm::Value *MemPtr, const MemberPointerType *MPT) {
2419   assert(MPT->isMemberFunctionPointer());
2420   const FunctionProtoType *FPT =
2421     MPT->getPointeeType()->castAs<FunctionProtoType>();
2422   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2423   llvm::FunctionType *FTy =
2424     CGM.getTypes().GetFunctionType(
2425       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2426   CGBuilderTy &Builder = CGF.Builder;
2427 
2428   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2429 
2430   // Extract the fields we need, regardless of model.  We'll apply them if we
2431   // have them.
2432   llvm::Value *FunctionPointer = MemPtr;
2433   llvm::Value *NonVirtualBaseAdjustment = nullptr;
2434   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2435   llvm::Value *VBPtrOffset = nullptr;
2436   if (MemPtr->getType()->isStructTy()) {
2437     // We need to extract values.
2438     unsigned I = 0;
2439     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2440     if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2441       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2442     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2443       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2444     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2445       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2446   }
2447 
2448   if (VirtualBaseAdjustmentOffset) {
2449     This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2450                              VBPtrOffset);
2451   }
2452 
2453   if (NonVirtualBaseAdjustment) {
2454     // Apply the adjustment and cast back to the original struct type.
2455     llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2456     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2457     This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2458   }
2459 
2460   return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2461 }
2462 
2463 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2464   return new MicrosoftCXXABI(CGM);
2465 }
2466 
2467 // MS RTTI Overview:
2468 // The run time type information emitted by cl.exe contains 5 distinct types of
2469 // structures.  Many of them reference each other.
2470 //
2471 // TypeInfo:  Static classes that are returned by typeid.
2472 //
2473 // CompleteObjectLocator:  Referenced by vftables.  They contain information
2474 //   required for dynamic casting, including OffsetFromTop.  They also contain
2475 //   a reference to the TypeInfo for the type and a reference to the
2476 //   CompleteHierarchyDescriptor for the type.
2477 //
2478 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
2479 //   Used during dynamic_cast to walk a class hierarchy.  References a base
2480 //   class array and the size of said array.
2481 //
2482 // BaseClassArray: Contains a list of classes in a hierarchy.  BaseClassArray is
2483 //   somewhat of a misnomer because the most derived class is also in the list
2484 //   as well as multiple copies of virtual bases (if they occur multiple times
2485 //   in the hiearchy.)  The BaseClassArray contains one BaseClassDescriptor for
2486 //   every path in the hierarchy, in pre-order depth first order.  Note, we do
2487 //   not declare a specific llvm type for BaseClassArray, it's merely an array
2488 //   of BaseClassDescriptor pointers.
2489 //
2490 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
2491 //   BaseClassDescriptor is also somewhat of a misnomer for the same reason that
2492 //   BaseClassArray is.  It contains information about a class within a
2493 //   hierarchy such as: is this base is ambiguous and what is its offset in the
2494 //   vbtable.  The names of the BaseClassDescriptors have all of their fields
2495 //   mangled into them so they can be aggressively deduplicated by the linker.
2496 
2497 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
2498   StringRef MangledName("\01??_7type_info@@6B@");
2499   if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
2500     return VTable;
2501   return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2502                                   /*Constant=*/true,
2503                                   llvm::GlobalVariable::ExternalLinkage,
2504                                   /*Initializer=*/nullptr, MangledName);
2505 }
2506 
2507 namespace {
2508 
2509 /// \brief A Helper struct that stores information about a class in a class
2510 /// hierarchy.  The information stored in these structs struct is used during
2511 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
2512 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
2513 // implicit depth first pre-order tree connectivity.  getFirstChild and
2514 // getNextSibling allow us to walk the tree efficiently.
2515 struct MSRTTIClass {
2516   enum {
2517     IsPrivateOnPath = 1 | 8,
2518     IsAmbiguous = 2,
2519     IsPrivate = 4,
2520     IsVirtual = 16,
2521     HasHierarchyDescriptor = 64
2522   };
2523   MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
2524   uint32_t initialize(const MSRTTIClass *Parent,
2525                       const CXXBaseSpecifier *Specifier);
2526 
2527   MSRTTIClass *getFirstChild() { return this + 1; }
2528   static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
2529     return Child + 1 + Child->NumBases;
2530   }
2531 
2532   const CXXRecordDecl *RD, *VirtualRoot;
2533   uint32_t Flags, NumBases, OffsetInVBase;
2534 };
2535 
2536 /// \brief Recursively initialize the base class array.
2537 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
2538                                  const CXXBaseSpecifier *Specifier) {
2539   Flags = HasHierarchyDescriptor;
2540   if (!Parent) {
2541     VirtualRoot = nullptr;
2542     OffsetInVBase = 0;
2543   } else {
2544     if (Specifier->getAccessSpecifier() != AS_public)
2545       Flags |= IsPrivate | IsPrivateOnPath;
2546     if (Specifier->isVirtual()) {
2547       Flags |= IsVirtual;
2548       VirtualRoot = RD;
2549       OffsetInVBase = 0;
2550     } else {
2551       if (Parent->Flags & IsPrivateOnPath)
2552         Flags |= IsPrivateOnPath;
2553       VirtualRoot = Parent->VirtualRoot;
2554       OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
2555           .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
2556     }
2557   }
2558   NumBases = 0;
2559   MSRTTIClass *Child = getFirstChild();
2560   for (const CXXBaseSpecifier &Base : RD->bases()) {
2561     NumBases += Child->initialize(this, &Base) + 1;
2562     Child = getNextChild(Child);
2563   }
2564   return NumBases;
2565 }
2566 
2567 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
2568   switch (Ty->getLinkage()) {
2569   case NoLinkage:
2570   case InternalLinkage:
2571   case UniqueExternalLinkage:
2572     return llvm::GlobalValue::InternalLinkage;
2573 
2574   case VisibleNoLinkage:
2575   case ExternalLinkage:
2576     return llvm::GlobalValue::LinkOnceODRLinkage;
2577   }
2578   llvm_unreachable("Invalid linkage!");
2579 }
2580 
2581 /// \brief An ephemeral helper class for building MS RTTI types.  It caches some
2582 /// calls to the module and information about the most derived class in a
2583 /// hierarchy.
2584 struct MSRTTIBuilder {
2585   enum {
2586     HasBranchingHierarchy = 1,
2587     HasVirtualBranchingHierarchy = 2,
2588     HasAmbiguousBases = 4
2589   };
2590 
2591   MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
2592       : CGM(ABI.CGM), Context(CGM.getContext()),
2593         VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
2594         Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
2595         ABI(ABI) {}
2596 
2597   llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
2598   llvm::GlobalVariable *
2599   getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
2600   llvm::GlobalVariable *getClassHierarchyDescriptor();
2601   llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
2602 
2603   CodeGenModule &CGM;
2604   ASTContext &Context;
2605   llvm::LLVMContext &VMContext;
2606   llvm::Module &Module;
2607   const CXXRecordDecl *RD;
2608   llvm::GlobalVariable::LinkageTypes Linkage;
2609   MicrosoftCXXABI &ABI;
2610 };
2611 
2612 } // namespace
2613 
2614 /// \brief Recursively serializes a class hierarchy in pre-order depth first
2615 /// order.
2616 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
2617                                     const CXXRecordDecl *RD) {
2618   Classes.push_back(MSRTTIClass(RD));
2619   for (const CXXBaseSpecifier &Base : RD->bases())
2620     serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
2621 }
2622 
2623 /// \brief Find ambiguity among base classes.
2624 static void
2625 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
2626   llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
2627   llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
2628   llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
2629   for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
2630     if ((Class->Flags & MSRTTIClass::IsVirtual) &&
2631         !VirtualBases.insert(Class->RD)) {
2632       Class = MSRTTIClass::getNextChild(Class);
2633       continue;
2634     }
2635     if (!UniqueBases.insert(Class->RD))
2636       AmbiguousBases.insert(Class->RD);
2637     Class++;
2638   }
2639   if (AmbiguousBases.empty())
2640     return;
2641   for (MSRTTIClass &Class : Classes)
2642     if (AmbiguousBases.count(Class.RD))
2643       Class.Flags |= MSRTTIClass::IsAmbiguous;
2644 }
2645 
2646 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
2647   SmallString<256> MangledName;
2648   {
2649     llvm::raw_svector_ostream Out(MangledName);
2650     ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
2651   }
2652 
2653   // Check to see if we've already declared this ClassHierarchyDescriptor.
2654   if (auto CHD = Module.getNamedGlobal(MangledName))
2655     return CHD;
2656 
2657   // Serialize the class hierarchy and initialize the CHD Fields.
2658   SmallVector<MSRTTIClass, 8> Classes;
2659   serializeClassHierarchy(Classes, RD);
2660   Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
2661   detectAmbiguousBases(Classes);
2662   int Flags = 0;
2663   for (auto Class : Classes) {
2664     if (Class.RD->getNumBases() > 1)
2665       Flags |= HasBranchingHierarchy;
2666     // Note: cl.exe does not calculate "HasAmbiguousBases" correctly.  We
2667     // believe the field isn't actually used.
2668     if (Class.Flags & MSRTTIClass::IsAmbiguous)
2669       Flags |= HasAmbiguousBases;
2670   }
2671   if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
2672     Flags |= HasVirtualBranchingHierarchy;
2673   // These gep indices are used to get the address of the first element of the
2674   // base class array.
2675   llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
2676                                llvm::ConstantInt::get(CGM.IntTy, 0)};
2677 
2678   // Forward-declare the class hierarchy descriptor
2679   auto Type = ABI.getClassHierarchyDescriptorType();
2680   auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2681                                       /*Initializer=*/nullptr,
2682                                       MangledName.c_str());
2683 
2684   // Initialize the base class ClassHierarchyDescriptor.
2685   llvm::Constant *Fields[] = {
2686       llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
2687       llvm::ConstantInt::get(CGM.IntTy, Flags),
2688       llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
2689       ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
2690           getBaseClassArray(Classes),
2691           llvm::ArrayRef<llvm::Value *>(GEPIndices))),
2692   };
2693   CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
2694   return CHD;
2695 }
2696 
2697 llvm::GlobalVariable *
2698 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
2699   SmallString<256> MangledName;
2700   {
2701     llvm::raw_svector_ostream Out(MangledName);
2702     ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
2703   }
2704 
2705   // Forward-declare the base class array.
2706   // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
2707   // mode) bytes of padding.  We provide a pointer sized amount of padding by
2708   // adding +1 to Classes.size().  The sections have pointer alignment and are
2709   // marked pick-any so it shouldn't matter.
2710   llvm::Type *PtrType = ABI.getImageRelativeType(
2711       ABI.getBaseClassDescriptorType()->getPointerTo());
2712   auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
2713   auto *BCA = new llvm::GlobalVariable(
2714       Module, ArrType,
2715       /*Constant=*/true, Linkage, /*Initializer=*/nullptr, MangledName.c_str());
2716 
2717   // Initialize the BaseClassArray.
2718   SmallVector<llvm::Constant *, 8> BaseClassArrayData;
2719   for (MSRTTIClass &Class : Classes)
2720     BaseClassArrayData.push_back(
2721         ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
2722   BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
2723   BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
2724   return BCA;
2725 }
2726 
2727 llvm::GlobalVariable *
2728 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
2729   // Compute the fields for the BaseClassDescriptor.  They are computed up front
2730   // because they are mangled into the name of the object.
2731   uint32_t OffsetInVBTable = 0;
2732   int32_t VBPtrOffset = -1;
2733   if (Class.VirtualRoot) {
2734     auto &VTableContext = CGM.getMicrosoftVTableContext();
2735     OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
2736     VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
2737   }
2738 
2739   SmallString<256> MangledName;
2740   {
2741     llvm::raw_svector_ostream Out(MangledName);
2742     ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
2743         Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
2744         Class.Flags, Out);
2745   }
2746 
2747   // Check to see if we've already declared this object.
2748   if (auto BCD = Module.getNamedGlobal(MangledName))
2749     return BCD;
2750 
2751   // Forward-declare the base class descriptor.
2752   auto Type = ABI.getBaseClassDescriptorType();
2753   auto BCD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2754                                       /*Initializer=*/nullptr,
2755                                       MangledName.c_str());
2756 
2757   // Initialize the BaseClassDescriptor.
2758   llvm::Constant *Fields[] = {
2759       ABI.getImageRelativeConstant(
2760           ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
2761       llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
2762       llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
2763       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
2764       llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
2765       llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
2766       ABI.getImageRelativeConstant(
2767           MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
2768   };
2769   BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
2770   return BCD;
2771 }
2772 
2773 llvm::GlobalVariable *
2774 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
2775   SmallString<256> MangledName;
2776   {
2777     llvm::raw_svector_ostream Out(MangledName);
2778     ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
2779   }
2780 
2781   // Check to see if we've already computed this complete object locator.
2782   if (auto COL = Module.getNamedGlobal(MangledName))
2783     return COL;
2784 
2785   // Compute the fields of the complete object locator.
2786   int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
2787   int VFPtrOffset = 0;
2788   // The offset includes the vtordisp if one exists.
2789   if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
2790     if (Context.getASTRecordLayout(RD)
2791       .getVBaseOffsetsMap()
2792       .find(VBase)
2793       ->second.hasVtorDisp())
2794       VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
2795 
2796   // Forward-declare the complete object locator.
2797   llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
2798   auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2799     /*Initializer=*/nullptr, MangledName.c_str());
2800 
2801   // Initialize the CompleteObjectLocator.
2802   llvm::Constant *Fields[] = {
2803       llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
2804       llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
2805       llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
2806       ABI.getImageRelativeConstant(
2807           CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
2808       ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
2809       ABI.getImageRelativeConstant(COL),
2810   };
2811   llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
2812   if (!ABI.isImageRelative())
2813     FieldsRef = FieldsRef.drop_back();
2814   COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
2815   return COL;
2816 }
2817 
2818 /// \brief Gets a TypeDescriptor.  Returns a llvm::Constant * rather than a
2819 /// llvm::GlobalVariable * because different type descriptors have different
2820 /// types, and need to be abstracted.  They are abstracting by casting the
2821 /// address to an Int8PtrTy.
2822 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
2823   SmallString<256> MangledName, TypeInfoString;
2824   {
2825     llvm::raw_svector_ostream Out(MangledName);
2826     getMangleContext().mangleCXXRTTI(Type, Out);
2827   }
2828 
2829   // Check to see if we've already declared this TypeDescriptor.
2830   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
2831     return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2832 
2833   // Compute the fields for the TypeDescriptor.
2834   {
2835     llvm::raw_svector_ostream Out(TypeInfoString);
2836     getMangleContext().mangleCXXRTTIName(Type, Out);
2837   }
2838 
2839   // Declare and initialize the TypeDescriptor.
2840   llvm::Constant *Fields[] = {
2841     getTypeInfoVTable(CGM),                        // VFPtr
2842     llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
2843     llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
2844   llvm::StructType *TypeDescriptorType =
2845       getTypeDescriptorType(TypeInfoString);
2846   return llvm::ConstantExpr::getBitCast(
2847       new llvm::GlobalVariable(
2848           CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
2849           getLinkageForRTTI(Type),
2850           llvm::ConstantStruct::get(TypeDescriptorType, Fields),
2851           MangledName.c_str()),
2852       CGM.Int8PtrTy);
2853 }
2854 
2855 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
2856 llvm::GlobalVariable *
2857 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
2858                                             const VPtrInfo *Info) {
2859   return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
2860 }
2861