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