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