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