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