Coverage Report

Created: 2020-02-15 09:57

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/ItaniumCXXABI.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------- ItaniumCXXABI.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 Itanium C++ ABI.  The class
10
// in this file generates structures that follow the Itanium C++ ABI, which is
11
// documented at:
12
//  http://www.codesourcery.com/public/cxx-abi/abi.html
13
//  http://www.codesourcery.com/public/cxx-abi/abi-eh.html
14
//
15
// It also supports the closely-related ARM ABI, documented at:
16
// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
17
//
18
//===----------------------------------------------------------------------===//
19
20
#include "CGCXXABI.h"
21
#include "CGCleanup.h"
22
#include "CGRecordLayout.h"
23
#include "CGVTables.h"
24
#include "CodeGenFunction.h"
25
#include "CodeGenModule.h"
26
#include "TargetInfo.h"
27
#include "clang/AST/Attr.h"
28
#include "clang/AST/Mangle.h"
29
#include "clang/AST/StmtCXX.h"
30
#include "clang/AST/Type.h"
31
#include "clang/CodeGen/ConstantInitBuilder.h"
32
#include "llvm/IR/DataLayout.h"
33
#include "llvm/IR/GlobalValue.h"
34
#include "llvm/IR/Instructions.h"
35
#include "llvm/IR/Intrinsics.h"
36
#include "llvm/IR/Value.h"
37
#include "llvm/Support/ScopedPrinter.h"
38
39
using namespace clang;
40
using namespace CodeGen;
41
42
namespace {
43
class ItaniumCXXABI : public CodeGen::CGCXXABI {
44
  /// VTables - All the vtables which have been defined.
45
  llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
46
47
  /// All the thread wrapper functions that have been used.
48
  llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
49
      ThreadWrappers;
50
51
protected:
52
  bool UseARMMethodPtrABI;
53
  bool UseARMGuardVarABI;
54
  bool Use32BitVTableOffsetABI;
55
56
9.16k
  ItaniumMangleContext &getMangleContext() {
57
9.16k
    return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
58
9.16k
  }
59
60
public:
61
  ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
62
                bool UseARMMethodPtrABI = false,
63
                bool UseARMGuardVarABI = false) :
64
    CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
65
    UseARMGuardVarABI(UseARMGuardVarABI),
66
25.0k
    Use32BitVTableOffsetABI(false) { }
67
68
  bool classifyReturnType(CGFunctionInfo &FI) const override;
69
70
154k
  RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
71
154k
    // If C++ prohibits us from making a copy, pass by address.
72
154k
    if (!RD->canPassInRegisters())
73
13.2k
      return RAA_Indirect;
74
141k
    return RAA_Default;
75
141k
  }
76
77
985
  bool isThisCompleteObject(GlobalDecl GD) const override {
78
985
    // The Itanium ABI has separate complete-object vs.  base-object
79
985
    // variants of both constructors and destructors.
80
985
    if (isa<CXXDestructorDecl>(GD.getDecl())) {
81
373
      switch (GD.getDtorType()) {
82
273
      case Dtor_Complete:
83
273
      case Dtor_Deleting:
84
273
        return true;
85
273
86
273
      case Dtor_Base:
87
100
        return false;
88
273
89
273
      case Dtor_Comdat:
90
0
        llvm_unreachable("emitting dtor comdat as function?");
91
0
      }
92
0
      llvm_unreachable("bad dtor kind");
93
0
    }
94
612
    if (isa<CXXConstructorDecl>(GD.getDecl())) {
95
357
      switch (GD.getCtorType()) {
96
208
      case Ctor_Complete:
97
208
        return true;
98
0
99
149
      case Ctor_Base:
100
149
        return false;
101
0
102
0
      case Ctor_CopyingClosure:
103
0
      case Ctor_DefaultClosure:
104
0
        llvm_unreachable("closure ctors in Itanium ABI?");
105
0
106
0
      case Ctor_Comdat:
107
0
        llvm_unreachable("emitting ctor comdat as function?");
108
0
      }
109
0
      llvm_unreachable("bad dtor kind");
110
0
    }
111
255
112
255
    // No other kinds.
113
255
    return false;
114
255
  }
115
116
  bool isZeroInitializable(const MemberPointerType *MPT) override;
117
118
  llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
119
120
  CGCallee
121
    EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
122
                                    const Expr *E,
123
                                    Address This,
124
                                    llvm::Value *&ThisPtrForCall,
125
                                    llvm::Value *MemFnPtr,
126
                                    const MemberPointerType *MPT) override;
127
128
  llvm::Value *
129
    EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
130
                                 Address Base,
131
                                 llvm::Value *MemPtr,
132
                                 const MemberPointerType *MPT) override;
133
134
  llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
135
                                           const CastExpr *E,
136
                                           llvm::Value *Src) override;
137
  llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
138
                                              llvm::Constant *Src) override;
139
140
  llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
141
142
  llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
143
  llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
144
                                        CharUnits offset) override;
145
  llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
146
  llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
147
                                     CharUnits ThisAdjustment);
148
149
  llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
150
                                           llvm::Value *L, llvm::Value *R,
151
                                           const MemberPointerType *MPT,
152
                                           bool Inequality) override;
153
154
  llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
155
                                         llvm::Value *Addr,
156
                                         const MemberPointerType *MPT) override;
157
158
  void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
159
                               Address Ptr, QualType ElementType,
160
                               const CXXDestructorDecl *Dtor) override;
161
162
  void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
163
  void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
164
165
  void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
166
167
  llvm::CallInst *
168
  emitTerminateForUnexpectedException(CodeGenFunction &CGF,
169
                                      llvm::Value *Exn) override;
170
171
  void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
172
  llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
173
  CatchTypeInfo
174
  getAddrOfCXXCatchHandlerType(QualType Ty,
175
120
                               QualType CatchHandlerType) override {
176
120
    return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
177
120
  }
178
179
  bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
180
  void EmitBadTypeidCall(CodeGenFunction &CGF) override;
181
  llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
182
                          Address ThisPtr,
183
                          llvm::Type *StdTypeInfoPtrTy) override;
184
185
  bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
186
                                          QualType SrcRecordTy) override;
187
188
  llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
189
                                   QualType SrcRecordTy, QualType DestTy,
190
                                   QualType DestRecordTy,
191
                                   llvm::BasicBlock *CastEnd) override;
192
193
  llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
194
                                     QualType SrcRecordTy,
195
                                     QualType DestTy) override;
196
197
  bool EmitBadCastCall(CodeGenFunction &CGF) override;
198
199
  llvm::Value *
200
    GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
201
                              const CXXRecordDecl *ClassDecl,
202
                              const CXXRecordDecl *BaseClassDecl) override;
203
204
  void EmitCXXConstructors(const CXXConstructorDecl *D) override;
205
206
  AddedStructorArgs
207
  buildStructorSignature(GlobalDecl GD,
208
                         SmallVectorImpl<CanQualType> &ArgTys) override;
209
210
  bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
211
14.6k
                              CXXDtorType DT) const override {
212
14.6k
    // Itanium does not emit any destructor variant as an inline thunk.
213
14.6k
    // Delegating may occur as an optimization, but all variants are either
214
14.6k
    // emitted with external linkage or as linkonce if they are inline and used.
215
14.6k
    return false;
216
14.6k
  }
217
218
  void EmitCXXDestructors(const CXXDestructorDecl *D) override;
219
220
  void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
221
                                 FunctionArgList &Params) override;
222
223
  void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
224
225
  AddedStructorArgs
226
  addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
227
                             CXXCtorType Type, bool ForVirtualBase,
228
                             bool Delegating, CallArgList &Args) override;
229
230
  void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
231
                          CXXDtorType Type, bool ForVirtualBase,
232
                          bool Delegating, Address This,
233
                          QualType ThisTy) override;
234
235
  void emitVTableDefinitions(CodeGenVTables &CGVT,
236
                             const CXXRecordDecl *RD) override;
237
238
  bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
239
                                           CodeGenFunction::VPtr Vptr) override;
240
241
2.00k
  bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
242
2.00k
    return true;
243
2.00k
  }
244
245
  llvm::Constant *
246
  getVTableAddressPoint(BaseSubobject Base,
247
                        const CXXRecordDecl *VTableClass) override;
248
249
  llvm::Value *getVTableAddressPointInStructor(
250
      CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
251
      BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
252
253
  llvm::Value *getVTableAddressPointInStructorWithVTT(
254
      CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
255
      BaseSubobject Base, const CXXRecordDecl *NearestVBase);
256
257
  llvm::Constant *
258
  getVTableAddressPointForConstExpr(BaseSubobject Base,
259
                                    const CXXRecordDecl *VTableClass) override;
260
261
  llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
262
                                        CharUnits VPtrOffset) override;
263
264
  CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
265
                                     Address This, llvm::Type *Ty,
266
                                     SourceLocation Loc) override;
267
268
  llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
269
                                         const CXXDestructorDecl *Dtor,
270
                                         CXXDtorType DtorType, Address This,
271
                                         DeleteOrMemberCallExpr E) override;
272
273
  void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
274
275
  bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
276
  bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
277
278
  void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
279
355
                       bool ReturnAdjustment) override {
280
355
    // Allow inlining of thunks by emitting them with available_externally
281
355
    // linkage together with vtables when needed.
282
355
    if (ForVTable && 
!Thunk->hasLocalLinkage()41
)
283
31
      Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
284
355
    CGM.setGVProperties(Thunk, GD);
285
355
  }
286
287
355
  bool exportThunk() override { return true; }
288
289
  llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
290
                                     const ThisAdjustment &TA) override;
291
292
  llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
293
                                       const ReturnAdjustment &RA) override;
294
295
  size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
296
228
                              FunctionArgList &Args) const override {
297
228
    assert(!Args.empty() && "expected the arglist to not be empty!");
298
228
    return Args.size() - 1;
299
228
  }
300
301
57
  StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
302
  StringRef GetDeletedVirtualCallName() override
303
3
    { return "__cxa_deleted_virtual"; }
304
305
  CharUnits getArrayCookieSizeImpl(QualType elementType) override;
306
  Address InitializeArrayCookie(CodeGenFunction &CGF,
307
                                Address NewPtr,
308
                                llvm::Value *NumElements,
309
                                const CXXNewExpr *expr,
310
                                QualType ElementType) override;
311
  llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
312
                                   Address allocPtr,
313
                                   CharUnits cookieSize) override;
314
315
  void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
316
                       llvm::GlobalVariable *DeclPtr,
317
                       bool PerformInit) override;
318
  void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
319
                          llvm::FunctionCallee dtor,
320
                          llvm::Constant *addr) override;
321
322
  llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
323
                                                llvm::Value *Val);
324
  void EmitThreadLocalInitFuncs(
325
      CodeGenModule &CGM,
326
      ArrayRef<const VarDecl *> CXXThreadLocals,
327
      ArrayRef<llvm::Function *> CXXThreadLocalInits,
328
      ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
329
330
  /// Determine whether we will definitely emit this variable with a constant
331
  /// initializer, either because the language semantics demand it or because
332
  /// we know that the initializer is a constant.
333
370
  bool isEmittedWithConstantInitializer(const VarDecl *VD) const {
334
370
    VD = VD->getMostRecentDecl();
335
370
    if (VD->hasAttr<ConstInitAttr>())
336
4
      return true;
337
366
338
366
    // All later checks examine the initializer specified on the variable. If
339
366
    // the variable is weak, such examination would not be correct.
340
366
    if (VD->isWeak() || VD->hasAttr<SelectAnyAttr>())
341
0
      return false;
342
366
343
366
    const VarDecl *InitDecl = VD->getInitializingDeclaration();
344
366
    if (!InitDecl)
345
132
      return false;
346
234
347
234
    // If there's no initializer to run, this is constant initialization.
348
234
    if (!InitDecl->hasInit())
349
39
      return true;
350
195
351
195
    // If we have the only definition, we don't need a thread wrapper if we
352
195
    // will emit the value as a constant.
353
195
    if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))
354
133
      return !VD->needsDestruction(getContext()) && 
InitDecl->evaluateValue()98
;
355
62
356
62
    // Otherwise, we need a thread wrapper unless we know that every
357
62
    // translation unit will emit the value as a constant. We rely on
358
62
    // ICE-ness not varying between translation units, which isn't actually
359
62
    // guaranteed by the standard but is necessary for sanity.
360
62
    return InitDecl->isInitKnownICE() && 
InitDecl->isInitICE()46
;
361
62
  }
362
363
370
  bool usesThreadWrapperFunction(const VarDecl *VD) const override {
364
370
    return !isEmittedWithConstantInitializer(VD) ||
365
370
           
VD->needsDestruction(getContext())110
;
366
370
  }
367
  LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
368
                                      QualType LValType) override;
369
370
  bool NeedsVTTParameter(GlobalDecl GD) override;
371
372
  /**************************** RTTI Uniqueness ******************************/
373
374
protected:
375
  /// Returns true if the ABI requires RTTI type_info objects to be unique
376
  /// across a program.
377
4.14k
  virtual bool shouldRTTIBeUnique() const { return true; }
378
379
public:
380
  /// What sort of unique-RTTI behavior should we use?
381
  enum RTTIUniquenessKind {
382
    /// We are guaranteeing, or need to guarantee, that the RTTI string
383
    /// is unique.
384
    RUK_Unique,
385
386
    /// We are not guaranteeing uniqueness for the RTTI string, so we
387
    /// can demote to hidden visibility but must use string comparisons.
388
    RUK_NonUniqueHidden,
389
390
    /// We are not guaranteeing uniqueness for the RTTI string, so we
391
    /// have to use string comparisons, but we also have to emit it with
392
    /// non-hidden visibility.
393
    RUK_NonUniqueVisible
394
  };
395
396
  /// Return the required visibility status for the given type and linkage in
397
  /// the current ABI.
398
  RTTIUniquenessKind
399
  classifyRTTIUniqueness(QualType CanTy,
400
                         llvm::GlobalValue::LinkageTypes Linkage) const;
401
  friend class ItaniumRTTIBuilder;
402
403
  void emitCXXStructor(GlobalDecl GD) override;
404
405
  std::pair<llvm::Value *, const CXXRecordDecl *>
406
  LoadVTablePtr(CodeGenFunction &CGF, Address This,
407
                const CXXRecordDecl *RD) override;
408
409
 private:
410
332
   bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
411
332
     const auto &VtableLayout =
412
332
         CGM.getItaniumVTableContext().getVTableLayout(RD);
413
332
414
1.40k
     for (const auto &VtableComponent : VtableLayout.vtable_components()) {
415
1.40k
       // Skip empty slot.
416
1.40k
       if (!VtableComponent.isUsedFunctionPointerKind())
417
835
         continue;
418
570
419
570
       const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
420
570
       if (!Method->getCanonicalDecl()->isInlined())
421
417
         continue;
422
153
423
153
       StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
424
153
       auto *Entry = CGM.GetGlobalValue(Name);
425
153
       // This checks if virtual inline function has already been emitted.
426
153
       // Note that it is possible that this inline function would be emitted
427
153
       // after trying to emit vtable speculatively. Because of this we do
428
153
       // an extra pass after emitting all deferred vtables to find and emit
429
153
       // these vtables opportunistically.
430
153
       if (!Entry || 
Entry->isDeclaration()50
)
431
142
         return true;
432
153
     }
433
332
     
return false190
;
434
332
  }
435
436
403
  bool isVTableHidden(const CXXRecordDecl *RD) const {
437
403
    const auto &VtableLayout =
438
403
            CGM.getItaniumVTableContext().getVTableLayout(RD);
439
403
440
1.96k
    for (const auto &VtableComponent : VtableLayout.vtable_components()) {
441
1.96k
      if (VtableComponent.isRTTIKind()) {
442
448
        const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
443
448
        if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
444
12
          return true;
445
1.52k
      } else if (VtableComponent.isUsedFunctionPointerKind()) {
446
926
        const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
447
926
        if (Method->getVisibility() == Visibility::HiddenVisibility &&
448
926
            
!Method->isDefined()7
)
449
7
          return true;
450
926
      }
451
1.96k
    }
452
403
    
return false384
;
453
403
  }
454
};
455
456
class ARMCXXABI : public ItaniumCXXABI {
457
public:
458
  ARMCXXABI(CodeGen::CodeGenModule &CGM) :
459
    ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
460
551
                  /*UseARMGuardVarABI=*/true) {}
461
462
14.3k
  bool HasThisReturn(GlobalDecl GD) const override {
463
14.3k
    return (isa<CXXConstructorDecl>(GD.getDecl()) || (
464
12.6k
              isa<CXXDestructorDecl>(GD.getDecl()) &&
465
12.6k
              
GD.getDtorType() != Dtor_Deleting1.27k
));
466
14.3k
  }
467
468
  void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
469
                           QualType ResTy) override;
470
471
  CharUnits getArrayCookieSizeImpl(QualType elementType) override;
472
  Address InitializeArrayCookie(CodeGenFunction &CGF,
473
                                Address NewPtr,
474
                                llvm::Value *NumElements,
475
                                const CXXNewExpr *expr,
476
                                QualType ElementType) override;
477
  llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
478
                                   CharUnits cookieSize) override;
479
};
480
481
class iOS64CXXABI : public ARMCXXABI {
482
public:
483
78
  iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
484
78
    Use32BitVTableOffsetABI = true;
485
78
  }
486
487
  // ARM64 libraries are prepared for non-unique RTTI.
488
28
  bool shouldRTTIBeUnique() const override { return false; }
489
};
490
491
class FuchsiaCXXABI final : public ItaniumCXXABI {
492
public:
493
  explicit FuchsiaCXXABI(CodeGen::CodeGenModule &CGM)
494
2
      : ItaniumCXXABI(CGM) {}
495
496
private:
497
318
  bool HasThisReturn(GlobalDecl GD) const override {
498
318
    return isa<CXXConstructorDecl>(GD.getDecl()) ||
499
318
           
(222
isa<CXXDestructorDecl>(GD.getDecl())222
&&
500
222
            
GD.getDtorType() != Dtor_Deleting216
);
501
318
  }
502
};
503
504
class WebAssemblyCXXABI final : public ItaniumCXXABI {
505
public:
506
  explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
507
      : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
508
33
                      /*UseARMGuardVarABI=*/true) {}
509
  void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
510
511
private:
512
852
  bool HasThisReturn(GlobalDecl GD) const override {
513
852
    return isa<CXXConstructorDecl>(GD.getDecl()) ||
514
852
           
(764
isa<CXXDestructorDecl>(GD.getDecl())764
&&
515
764
            
GD.getDtorType() != Dtor_Deleting277
);
516
852
  }
517
1
  bool canCallMismatchedFunctionType() const override { return false; }
518
};
519
}
520
521
25.0k
CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
522
25.0k
  switch (CGM.getTarget().getCXXABI().getKind()) {
523
0
  // For IR-generation purposes, there's no significant difference
524
0
  // between the ARM and iOS ABIs.
525
473
  case TargetCXXABI::GenericARM:
526
473
  case TargetCXXABI::iOS:
527
473
  case TargetCXXABI::WatchOS:
528
473
    return new ARMCXXABI(CGM);
529
473
530
473
  case TargetCXXABI::iOS64:
531
78
    return new iOS64CXXABI(CGM);
532
473
533
473
  case TargetCXXABI::Fuchsia:
534
2
    return new FuchsiaCXXABI(CGM);
535
473
536
473
  // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
537
473
  // include the other 32-bit ARM oddities: constructor/destructor return values
538
473
  // and array cookies.
539
473
  case TargetCXXABI::GenericAArch64:
540
181
    return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
541
181
                             /*UseARMGuardVarABI=*/true);
542
473
543
473
  case TargetCXXABI::GenericMIPS:
544
154
    return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
545
473
546
473
  case TargetCXXABI::WebAssembly:
547
33
    return new WebAssemblyCXXABI(CGM);
548
473
549
24.1k
  case TargetCXXABI::GenericItanium:
550
24.1k
    if (CGM.getContext().getTargetInfo().getTriple().getArch()
551
24.1k
        == llvm::Triple::le32) {
552
13
      // For PNaCl, use ARM-style method pointers so that PNaCl code
553
13
      // does not assume anything about the alignment of function
554
13
      // pointers.
555
13
      return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
556
13
    }
557
24.1k
    return new ItaniumCXXABI(CGM);
558
24.1k
559
24.1k
  case TargetCXXABI::Microsoft:
560
0
    llvm_unreachable("Microsoft ABI is not Itanium-based");
561
0
  }
562
0
  llvm_unreachable("bad ABI kind");
563
0
}
564
565
llvm::Type *
566
423
ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
567
423
  if (MPT->isMemberDataPointer())
568
85
    return CGM.PtrDiffTy;
569
338
  return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
570
338
}
571
572
/// In the Itanium and ARM ABIs, method pointers have the form:
573
///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
574
///
575
/// In the Itanium ABI:
576
///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
577
///  - the this-adjustment is (memptr.adj)
578
///  - the virtual offset is (memptr.ptr - 1)
579
///
580
/// In the ARM ABI:
581
///  - method pointers are virtual if (memptr.adj & 1) is nonzero
582
///  - the this-adjustment is (memptr.adj >> 1)
583
///  - the virtual offset is (memptr.ptr)
584
/// ARM uses 'adj' for the virtual flag because Thumb functions
585
/// may be only single-byte aligned.
586
///
587
/// If the member is virtual, the adjusted 'this' pointer points
588
/// to a vtable pointer from which the virtual offset is applied.
589
///
590
/// If the member is non-virtual, memptr.ptr is the address of
591
/// the function to call.
592
CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
593
    CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
594
    llvm::Value *&ThisPtrForCall,
595
88
    llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
596
88
  CGBuilderTy &Builder = CGF.Builder;
597
88
598
88
  const FunctionProtoType *FPT =
599
88
    MPT->getPointeeType()->getAs<FunctionProtoType>();
600
88
  auto *RD =
601
88
      cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
602
88
603
88
  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
604
88
      CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
605
88
606
88
  llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
607
88
608
88
  llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
609
88
  llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
610
88
  llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
611
88
612
88
  // Extract memptr.adj, which is in the second field.
613
88
  llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
614
88
615
88
  // Compute the true adjustment.
616
88
  llvm::Value *Adj = RawAdj;
617
88
  if (UseARMMethodPtrABI)
618
19
    Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
619
88
620
88
  // Apply the adjustment and cast back to the original struct type
621
88
  // for consistency.
622
88
  llvm::Value *This = ThisAddr.getPointer();
623
88
  llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
624
88
  Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
625
88
  This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
626
88
  ThisPtrForCall = This;
627
88
628
88
  // Load the function pointer.
629
88
  llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
630
88
631
88
  // If the LSB in the function pointer is 1, the function pointer points to
632
88
  // a virtual function.
633
88
  llvm::Value *IsVirtual;
634
88
  if (UseARMMethodPtrABI)
635
19
    IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
636
69
  else
637
69
    IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
638
88
  IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
639
88
  Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
640
88
641
88
  // In the virtual path, the adjustment left 'This' pointing to the
642
88
  // vtable of the correct base subobject.  The "function pointer" is an
643
88
  // offset within the vtable (+1 for the virtual flag on non-ARM).
644
88
  CGF.EmitBlock(FnVirtual);
645
88
646
88
  // Cast the adjusted this to a pointer to vtable pointer and load.
647
88
  llvm::Type *VTableTy = Builder.getInt8PtrTy();
648
88
  CharUnits VTablePtrAlign =
649
88
    CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
650
88
                                      CGF.getPointerAlign());
651
88
  llvm::Value *VTable =
652
88
    CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
653
88
654
88
  // Apply the offset.
655
88
  // On ARM64, to reserve extra space in virtual member function pointers,
656
88
  // we only pay attention to the low 32 bits of the offset.
657
88
  llvm::Value *VTableOffset = FnAsInt;
658
88
  if (!UseARMMethodPtrABI)
659
69
    VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
660
88
  if (Use32BitVTableOffsetABI) {
661
2
    VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
662
2
    VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
663
2
  }
664
88
665
88
  // Check the address of the function pointer if CFI on member function
666
88
  // pointers is enabled.
667
88
  llvm::Constant *CheckSourceLocation;
668
88
  llvm::Constant *CheckTypeDesc;
669
88
  bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
670
88
                            
CGM.HasHiddenLTOVisibility(RD)3
;
671
88
  bool ShouldEmitVFEInfo = CGM.getCodeGenOpts().VirtualFunctionElimination &&
672
88
                           
CGM.HasHiddenLTOVisibility(RD)1
;
673
88
  bool ShouldEmitWPDInfo =
674
88
      CGM.getCodeGenOpts().WholeProgramVTables &&
675
88
      // Don't insert type tests if we are forcing public std visibility.
676
88
      
!CGM.HasLTOVisibilityPublicStd(RD)2
;
677
88
  llvm::Value *VirtualFn = nullptr;
678
88
679
88
  {
680
88
    CodeGenFunction::SanitizerScope SanScope(&CGF);
681
88
    llvm::Value *TypeId = nullptr;
682
88
    llvm::Value *CheckResult = nullptr;
683
88
684
88
    if (ShouldEmitCFICheck || 
ShouldEmitVFEInfo86
||
ShouldEmitWPDInfo85
) {
685
4
      // If doing CFI, VFE or WPD, we will need the metadata node to check
686
4
      // against.
687
4
      llvm::Metadata *MD =
688
4
          CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
689
4
      TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
690
4
    }
691
88
692
88
    llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
693
88
694
88
    if (ShouldEmitVFEInfo) {
695
1
      // If doing VFE, load from the vtable with a type.checked.load intrinsic
696
1
      // call. Note that we use the GEP to calculate the address to load from
697
1
      // and pass 0 as the offset to the intrinsic. This is because every
698
1
      // vtable slot of the correct type is marked with matching metadata, and
699
1
      // we know that the load must be from one of these slots.
700
1
      llvm::Value *CheckedLoad = Builder.CreateCall(
701
1
          CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
702
1
          {VFPAddr, llvm::ConstantInt::get(CGM.Int32Ty, 0), TypeId});
703
1
      CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
704
1
      VirtualFn = Builder.CreateExtractValue(CheckedLoad, 0);
705
1
      VirtualFn = Builder.CreateBitCast(VirtualFn, FTy->getPointerTo(),
706
1
                                        "memptr.virtualfn");
707
87
    } else {
708
87
      // When not doing VFE, emit a normal load, as it allows more
709
87
      // optimisations than type.checked.load.
710
87
      if (ShouldEmitCFICheck || 
ShouldEmitWPDInfo85
) {
711
3
        CheckResult = Builder.CreateCall(
712
3
            CGM.getIntrinsic(llvm::Intrinsic::type_test),
713
3
            {Builder.CreateBitCast(VFPAddr, CGF.Int8PtrTy), TypeId});
714
3
      }
715
87
      VFPAddr =
716
87
          Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
717
87
      VirtualFn = Builder.CreateAlignedLoad(VFPAddr, CGF.getPointerAlign(),
718
87
                                            "memptr.virtualfn");
719
87
    }
720
88
    assert(VirtualFn && "Virtual fuction pointer not created!");
721
88
    assert((!ShouldEmitCFICheck || !ShouldEmitVFEInfo || !ShouldEmitWPDInfo ||
722
88
            CheckResult) &&
723
88
           "Check result required but not created!");
724
88
725
88
    if (ShouldEmitCFICheck) {
726
2
      // If doing CFI, emit the check.
727
2
      CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
728
2
      CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
729
2
      llvm::Constant *StaticData[] = {
730
2
          llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
731
2
          CheckSourceLocation,
732
2
          CheckTypeDesc,
733
2
      };
734
2
735
2
      if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
736
2
        CGF.EmitTrapCheck(CheckResult);
737
2
      } else {
738
0
        llvm::Value *AllVtables = llvm::MetadataAsValue::get(
739
0
            CGM.getLLVMContext(),
740
0
            llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
741
0
        llvm::Value *ValidVtable = Builder.CreateCall(
742
0
            CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
743
0
        CGF.EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIMFCall),
744
0
                      SanitizerHandler::CFICheckFail, StaticData,
745
0
                      {VTable, ValidVtable});
746
0
      }
747
2
748
2
      FnVirtual = Builder.GetInsertBlock();
749
2
    }
750
88
  } // End of sanitizer scope
751
88
752
88
  CGF.EmitBranch(FnEnd);
753
88
754
88
  // In the non-virtual path, the function pointer is actually a
755
88
  // function pointer.
756
88
  CGF.EmitBlock(FnNonVirtual);
757
88
  llvm::Value *NonVirtualFn =
758
88
    Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
759
88
760
88
  // Check the function pointer if CFI on member function pointers is enabled.
761
88
  if (ShouldEmitCFICheck) {
762
2
    CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
763
2
    if (RD->hasDefinition()) {
764
1
      CodeGenFunction::SanitizerScope SanScope(&CGF);
765
1
766
1
      llvm::Constant *StaticData[] = {
767
1
          llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
768
1
          CheckSourceLocation,
769
1
          CheckTypeDesc,
770
1
      };
771
1
772
1
      llvm::Value *Bit = Builder.getFalse();
773
1
      llvm::Value *CastedNonVirtualFn =
774
1
          Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
775
2
      for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
776
2
        llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
777
2
            getContext().getMemberPointerType(
778
2
                MPT->getPointeeType(),
779
2
                getContext().getRecordType(Base).getTypePtr()));
780
2
        llvm::Value *TypeId =
781
2
            llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
782
2
783
2
        llvm::Value *TypeTest =
784
2
            Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
785
2
                               {CastedNonVirtualFn, TypeId});
786
2
        Bit = Builder.CreateOr(Bit, TypeTest);
787
2
      }
788
1
789
1
      CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
790
1
                    SanitizerHandler::CFICheckFail, StaticData,
791
1
                    {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
792
1
793
1
      FnNonVirtual = Builder.GetInsertBlock();
794
1
    }
795
2
  }
796
88
797
88
  // We're done.
798
88
  CGF.EmitBlock(FnEnd);
799
88
  llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
800
88
  CalleePtr->addIncoming(VirtualFn, FnVirtual);
801
88
  CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
802
88
803
88
  CGCallee Callee(FPT, CalleePtr);
804
88
  return Callee;
805
88
}
806
807
/// Compute an l-value by applying the given pointer-to-member to a
808
/// base object.
809
llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
810
    CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
811
57
    const MemberPointerType *MPT) {
812
57
  assert(MemPtr->getType() == CGM.PtrDiffTy);
813
57
814
57
  CGBuilderTy &Builder = CGF.Builder;
815
57
816
57
  // Cast to char*.
817
57
  Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
818
57
819
57
  // Apply the offset, which we assume is non-null.
820
57
  llvm::Value *Addr =
821
57
    Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
822
57
823
57
  // Cast the address to the appropriate pointer type, adopting the
824
57
  // address space of the base pointer.
825
57
  llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
826
57
                            ->getPointerTo(Base.getAddressSpace());
827
57
  return Builder.CreateBitCast(Addr, PType);
828
57
}
829
830
/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
831
/// conversion.
832
///
833
/// Bitcast conversions are always a no-op under Itanium.
834
///
835
/// Obligatory offset/adjustment diagram:
836
///         <-- offset -->          <-- adjustment -->
837
///   |--------------------------|----------------------|--------------------|
838
///   ^Derived address point     ^Base address point    ^Member address point
839
///
840
/// So when converting a base member pointer to a derived member pointer,
841
/// we add the offset to the adjustment because the address point has
842
/// decreased;  and conversely, when converting a derived MP to a base MP
843
/// we subtract the offset from the adjustment because the address point
844
/// has increased.
845
///
846
/// The standard forbids (at compile time) conversion to and from
847
/// virtual bases, which is why we don't have to consider them here.
848
///
849
/// The standard forbids (at run time) casting a derived MP to a base
850
/// MP when the derived MP does not point to a member of the base.
851
/// This is why -1 is a reasonable choice for null data member
852
/// pointers.
853
llvm::Value *
854
ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
855
                                           const CastExpr *E,
856
54
                                           llvm::Value *src) {
857
54
  assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
858
54
         E->getCastKind() == CK_BaseToDerivedMemberPointer ||
859
54
         E->getCastKind() == CK_ReinterpretMemberPointer);
860
54
861
54
  // Under Itanium, reinterprets don't require any additional processing.
862
54
  if (E->getCastKind() == CK_ReinterpretMemberPointer) 
return src3
;
863
51
864
51
  // Use constant emission if we can.
865
51
  if (isa<llvm::Constant>(src))
866
30
    return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
867
21
868
21
  llvm::Constant *adj = getMemberPointerAdjustment(E);
869
21
  if (!adj) 
return src3
;
870
18
871
18
  CGBuilderTy &Builder = CGF.Builder;
872
18
  bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
873
18
874
18
  const MemberPointerType *destTy =
875
18
    E->getType()->castAs<MemberPointerType>();
876
18
877
18
  // For member data pointers, this is just a matter of adding the
878
18
  // offset if the source is non-null.
879
18
  if (destTy->isMemberDataPointer()) {
880
2
    llvm::Value *dst;
881
2
    if (isDerivedToBase)
882
1
      dst = Builder.CreateNSWSub(src, adj, "adj");
883
1
    else
884
1
      dst = Builder.CreateNSWAdd(src, adj, "adj");
885
2
886
2
    // Null check.
887
2
    llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
888
2
    llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
889
2
    return Builder.CreateSelect(isNull, src, dst);
890
2
  }
891
16
892
16
  // The this-adjustment is left-shifted by 1 on ARM.
893
16
  if (UseARMMethodPtrABI) {
894
8
    uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
895
8
    offset <<= 1;
896
8
    adj = llvm::ConstantInt::get(adj->getType(), offset);
897
8
  }
898
16
899
16
  llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
900
16
  llvm::Value *dstAdj;
901
16
  if (isDerivedToBase)
902
8
    dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
903
8
  else
904
8
    dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
905
16
906
16
  return Builder.CreateInsertValue(src, dstAdj, 1);
907
16
}
908
909
llvm::Constant *
910
ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
911
71
                                           llvm::Constant *src) {
912
71
  assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
913
71
         E->getCastKind() == CK_BaseToDerivedMemberPointer ||
914
71
         E->getCastKind() == CK_ReinterpretMemberPointer);
915
71
916
71
  // Under Itanium, reinterprets don't require any additional processing.
917
71
  if (E->getCastKind() == CK_ReinterpretMemberPointer) 
return src33
;
918
38
919
38
  // If the adjustment is trivial, we don't need to do anything.
920
38
  llvm::Constant *adj = getMemberPointerAdjustment(E);
921
38
  if (!adj) 
return src30
;
922
8
923
8
  bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
924
8
925
8
  const MemberPointerType *destTy =
926
8
    E->getType()->castAs<MemberPointerType>();
927
8
928
8
  // For member data pointers, this is just a matter of adding the
929
8
  // offset if the source is non-null.
930
8
  if (destTy->isMemberDataPointer()) {
931
0
    // null maps to null.
932
0
    if (src->isAllOnesValue()) return src;
933
0
934
0
    if (isDerivedToBase)
935
0
      return llvm::ConstantExpr::getNSWSub(src, adj);
936
0
    else
937
0
      return llvm::ConstantExpr::getNSWAdd(src, adj);
938
8
  }
939
8
940
8
  // The this-adjustment is left-shifted by 1 on ARM.
941
8
  if (UseARMMethodPtrABI) {
942
4
    uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
943
4
    offset <<= 1;
944
4
    adj = llvm::ConstantInt::get(adj->getType(), offset);
945
4
  }
946
8
947
8
  llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
948
8
  llvm::Constant *dstAdj;
949
8
  if (isDerivedToBase)
950
0
    dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
951
8
  else
952
8
    dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
953
8
954
8
  return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
955
8
}
956
957
llvm::Constant *
958
79
ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
959
79
  // Itanium C++ ABI 2.3:
960
79
  //   A NULL pointer is represented as -1.
961
79
  if (MPT->isMemberDataPointer())
962
54
    return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
963
25
964
25
  llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
965
25
  llvm::Constant *Values[2] = { Zero, Zero };
966
25
  return llvm::ConstantStruct::getAnon(Values);
967
25
}
968
969
llvm::Constant *
970
ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
971
59
                                     CharUnits offset) {
972
59
  // Itanium C++ ABI 2.3:
973
59
  //   A pointer to data member is an offset from the base address of
974
59
  //   the class object containing it, represented as a ptrdiff_t
975
59
  return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
976
59
}
977
978
llvm::Constant *
979
243
ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
980
243
  return BuildMemberPointer(MD, CharUnits::Zero());
981
243
}
982
983
llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
984
434
                                                  CharUnits ThisAdjustment) {
985
434
  assert(MD->isInstance() && "Member function must not be static!");
986
434
987
434
  CodeGenTypes &Types = CGM.getTypes();
988
434
989
434
  // Get the function pointer (or index if this is a virtual function).
990
434
  llvm::Constant *MemPtr[2];
991
434
  if (MD->isVirtual()) {
992
126
    uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
993
126
994
126
    const ASTContext &Context = getContext();
995
126
    CharUnits PointerWidth =
996
126
      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
997
126
    uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
998
126
999
126
    if (UseARMMethodPtrABI) {
1000
50
      // ARM C++ ABI 3.2.1:
1001
50
      //   This ABI specifies that adj contains twice the this
1002
50
      //   adjustment, plus 1 if the member function is virtual. The
1003
50
      //   least significant bit of adj then makes exactly the same
1004
50
      //   discrimination as the least significant bit of ptr does for
1005
50
      //   Itanium.
1006
50
      MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
1007
50
      MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1008
50
                                         2 * ThisAdjustment.getQuantity() + 1);
1009
76
    } else {
1010
76
      // Itanium C++ ABI 2.3:
1011
76
      //   For a virtual function, [the pointer field] is 1 plus the
1012
76
      //   virtual table offset (in bytes) of the function,
1013
76
      //   represented as a ptrdiff_t.
1014
76
      MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
1015
76
      MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1016
76
                                         ThisAdjustment.getQuantity());
1017
76
    }
1018
308
  } else {
1019
308
    const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1020
308
    llvm::Type *Ty;
1021
308
    // Check whether the function has a computable LLVM signature.
1022
308
    if (Types.isFuncTypeConvertible(FPT)) {
1023
306
      // The function has a computable LLVM signature; use the correct type.
1024
306
      Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1025
306
    } else {
1026
2
      // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1027
2
      // function type is incomplete.
1028
2
      Ty = CGM.PtrDiffTy;
1029
2
    }
1030
308
    llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
1031
308
1032
308
    MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
1033
308
    MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1034
308
                                       (UseARMMethodPtrABI ? 
256
:
1252
) *
1035
308
                                       ThisAdjustment.getQuantity());
1036
308
  }
1037
434
1038
434
  return llvm::ConstantStruct::getAnon(MemPtr);
1039
434
}
1040
1041
llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
1042
220
                                                 QualType MPType) {
1043
220
  const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1044
220
  const ValueDecl *MPD = MP.getMemberPointerDecl();
1045
220
  if (!MPD)
1046
4
    return EmitNullMemberPointer(MPT);
1047
216
1048
216
  CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1049
216
1050
216
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1051
191
    return BuildMemberPointer(MD, ThisAdjustment);
1052
25
1053
25
  CharUnits FieldOffset =
1054
25
    getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1055
25
  return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1056
25
}
1057
1058
/// The comparison algorithm is pretty easy: the member pointers are
1059
/// the same if they're either bitwise identical *or* both null.
1060
///
1061
/// ARM is different here only because null-ness is more complicated.
1062
llvm::Value *
1063
ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1064
                                           llvm::Value *L,
1065
                                           llvm::Value *R,
1066
                                           const MemberPointerType *MPT,
1067
12
                                           bool Inequality) {
1068
12
  CGBuilderTy &Builder = CGF.Builder;
1069
12
1070
12
  llvm::ICmpInst::Predicate Eq;
1071
12
  llvm::Instruction::BinaryOps And, Or;
1072
12
  if (Inequality) {
1073
2
    Eq = llvm::ICmpInst::ICMP_NE;
1074
2
    And = llvm::Instruction::Or;
1075
2
    Or = llvm::Instruction::And;
1076
10
  } else {
1077
10
    Eq = llvm::ICmpInst::ICMP_EQ;
1078
10
    And = llvm::Instruction::And;
1079
10
    Or = llvm::Instruction::Or;
1080
10
  }
1081
12
1082
12
  // Member data pointers are easy because there's a unique null
1083
12
  // value, so it just comes down to bitwise equality.
1084
12
  if (MPT->isMemberDataPointer())
1085
4
    return Builder.CreateICmp(Eq, L, R);
1086
8
1087
8
  // For member function pointers, the tautologies are more complex.
1088
8
  // The Itanium tautology is:
1089
8
  //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
1090
8
  // The ARM tautology is:
1091
8
  //   (L == R) <==> (L.ptr == R.ptr &&
1092
8
  //                  (L.adj == R.adj ||
1093
8
  //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
1094
8
  // The inequality tautologies have exactly the same structure, except
1095
8
  // applying De Morgan's laws.
1096
8
1097
8
  llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1098
8
  llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1099
8
1100
8
  // This condition tests whether L.ptr == R.ptr.  This must always be
1101
8
  // true for equality to hold.
1102
8
  llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1103
8
1104
8
  // This condition, together with the assumption that L.ptr == R.ptr,
1105
8
  // tests whether the pointers are both null.  ARM imposes an extra
1106
8
  // condition.
1107
8
  llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1108
8
  llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1109
8
1110
8
  // This condition tests whether L.adj == R.adj.  If this isn't
1111
8
  // true, the pointers are unequal unless they're both null.
1112
8
  llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1113
8
  llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
1114
8
  llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1115
8
1116
8
  // Null member function pointers on ARM clear the low bit of Adj,
1117
8
  // so the zero condition has to check that neither low bit is set.
1118
8
  if (UseARMMethodPtrABI) {
1119
4
    llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1120
4
1121
4
    // Compute (l.adj | r.adj) & 1 and test it against zero.
1122
4
    llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1123
4
    llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1124
4
    llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1125
4
                                                      "cmp.or.adj");
1126
4
    EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1127
4
  }
1128
8
1129
8
  // Tie together all our conditions.
1130
8
  llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1131
8
  Result = Builder.CreateBinOp(And, PtrEq, Result,
1132
8
                               Inequality ? 
"memptr.ne"0
: "memptr.eq");
1133
8
  return Result;
1134
8
}
1135
1136
llvm::Value *
1137
ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1138
                                          llvm::Value *MemPtr,
1139
52
                                          const MemberPointerType *MPT) {
1140
52
  CGBuilderTy &Builder = CGF.Builder;
1141
52
1142
52
  /// For member data pointers, this is just a check against -1.
1143
52
  if (MPT->isMemberDataPointer()) {
1144
5
    assert(MemPtr->getType() == CGM.PtrDiffTy);
1145
5
    llvm::Value *NegativeOne =
1146
5
      llvm::Constant::getAllOnesValue(MemPtr->getType());
1147
5
    return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1148
5
  }
1149
47
1150
47
  // In Itanium, a member function pointer is not null if 'ptr' is not null.
1151
47
  llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
1152
47
1153
47
  llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1154
47
  llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1155
47
1156
47
  // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1157
47
  // (the virtual bit) is set.
1158
47
  if (UseARMMethodPtrABI) {
1159
20
    llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
1160
20
    llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
1161
20
    llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
1162
20
    llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1163
20
                                                  "memptr.isvirtual");
1164
20
    Result = Builder.CreateOr(Result, IsVirtual);
1165
20
  }
1166
47
1167
47
  return Result;
1168
47
}
1169
1170
171k
bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1171
171k
  const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1172
171k
  if (!RD)
1173
167k
    return false;
1174
3.75k
1175
3.75k
  // If C++ prohibits us from making a copy, return by address.
1176
3.75k
  if (!RD->canPassInRegisters()) {
1177
614
    auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1178
614
    FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1179
614
    return true;
1180
614
  }
1181
3.13k
  return false;
1182
3.13k
}
1183
1184
/// The Itanium ABI requires non-zero initialization only for data
1185
/// member pointers, for which '0' is a valid offset.
1186
176
bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1187
176
  return MPT->isMemberFunctionPointer();
1188
176
}
1189
1190
/// The Itanium ABI always places an offset to the complete object
1191
/// at entry -2 in the vtable.
1192
void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1193
                                            const CXXDeleteExpr *DE,
1194
                                            Address Ptr,
1195
                                            QualType ElementType,
1196
28
                                            const CXXDestructorDecl *Dtor) {
1197
28
  bool UseGlobalDelete = DE->isGlobalDelete();
1198
28
  if (UseGlobalDelete) {
1199
5
    // Derive the complete-object pointer, which is what we need
1200
5
    // to pass to the deallocation function.
1201
5
1202
5
    // Grab the vtable pointer as an intptr_t*.
1203
5
    auto *ClassDecl =
1204
5
        cast<CXXRecordDecl>(ElementType->castAs<RecordType>()->getDecl());
1205
5
    llvm::Value *VTable =
1206
5
        CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
1207
5
1208
5
    // Track back to entry -2 and pull out the offset there.
1209
5
    llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1210
5
        VTable, -2, "complete-offset.ptr");
1211
5
    llvm::Value *Offset =
1212
5
      CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
1213
5
1214
5
    // Apply the offset.
1215
5
    llvm::Value *CompletePtr =
1216
5
      CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
1217
5
    CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1218
5
1219
5
    // If we're supposed to call the global delete, make sure we do so
1220
5
    // even if the destructor throws.
1221
5
    CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1222
5
                                    ElementType);
1223
5
  }
1224
28
1225
28
  // FIXME: Provide a source location here even though there's no
1226
28
  // CXXMemberCallExpr for dtor call.
1227
28
  CXXDtorType DtorType = UseGlobalDelete ? 
Dtor_Complete5
:
Dtor_Deleting23
;
1228
28
  EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
1229
28
1230
28
  if (UseGlobalDelete)
1231
5
    CGF.PopCleanupBlock();
1232
28
}
1233
1234
55
void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1235
55
  // void __cxa_rethrow();
1236
55
1237
55
  llvm::FunctionType *FTy =
1238
55
    llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1239
55
1240
55
  llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1241
55
1242
55
  if (isNoReturn)
1243
42
    CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1244
13
  else
1245
13
    CGF.EmitRuntimeCallOrInvoke(Fn);
1246
55
}
1247
1248
417
static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
1249
417
  // void *__cxa_allocate_exception(size_t thrown_size);
1250
417
1251
417
  llvm::FunctionType *FTy =
1252
417
    llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
1253
417
1254
417
  return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1255
417
}
1256
1257
417
static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
1258
417
  // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1259
417
  //                  void (*dest) (void *));
1260
417
1261
417
  llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1262
417
  llvm::FunctionType *FTy =
1263
417
    llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
1264
417
1265
417
  return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1266
417
}
1267
1268
417
void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1269
417
  QualType ThrowType = E->getSubExpr()->getType();
1270
417
  // Now allocate the exception object.
1271
417
  llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1272
417
  uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1273
417
1274
417
  llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
1275
417
  llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1276
417
      AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1277
417
1278
417
  CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
1279
417
  CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
1280
417
1281
417
  // Now throw the exception.
1282
417
  llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1283
417
                                                         /*ForEH=*/true);
1284
417
1285
417
  // The address of the destructor.  If the exception type has a
1286
417
  // trivial destructor (or isn't a record), we just pass null.
1287
417
  llvm::Constant *Dtor = nullptr;
1288
417
  if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1289
312
    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1290
312
    if (!Record->hasTrivialDestructor()) {
1291
296
      CXXDestructorDecl *DtorD = Record->getDestructor();
1292
296
      Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
1293
296
      Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1294
296
    }
1295
312
  }
1296
417
  if (!Dtor) 
Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy)121
;
1297
417
1298
417
  llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1299
417
  CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1300
417
}
1301
1302
55
static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1303
55
  // void *__dynamic_cast(const void *sub,
1304
55
  //                      const abi::__class_type_info *src,
1305
55
  //                      const abi::__class_type_info *dst,
1306
55
  //                      std::ptrdiff_t src2dst_offset);
1307
55
1308
55
  llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1309
55
  llvm::Type *PtrDiffTy =
1310
55
    CGF.ConvertType(CGF.getContext().getPointerDiffType());
1311
55
1312
55
  llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1313
55
1314
55
  llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1315
55
1316
55
  // Mark the function as nounwind readonly.
1317
55
  llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1318
55
                                            llvm::Attribute::ReadOnly };
1319
55
  llvm::AttributeList Attrs = llvm::AttributeList::get(
1320
55
      CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
1321
55
1322
55
  return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1323
55
}
1324
1325
9
static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
1326
9
  // void __cxa_bad_cast();
1327
9
  llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1328
9
  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1329
9
}
1330
1331
/// Compute the src2dst_offset hint as described in the
1332
/// Itanium C++ ABI [2.9.7]
1333
static CharUnits computeOffsetHint(ASTContext &Context,
1334
                                   const CXXRecordDecl *Src,
1335
55
                                   const CXXRecordDecl *Dst) {
1336
55
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1337
55
                     /*DetectVirtual=*/false);
1338
55
1339
55
  // If Dst is not derived from Src we can skip the whole computation below and
1340
55
  // return that Src is not a public base of Dst.  Record all inheritance paths.
1341
55
  if (!Dst->isDerivedFrom(Src, Paths))
1342
5
    return CharUnits::fromQuantity(-2ULL);
1343
50
1344
50
  unsigned NumPublicPaths = 0;
1345
50
  CharUnits Offset;
1346
50
1347
50
  // Now walk all possible inheritance paths.
1348
56
  for (const CXXBasePath &Path : Paths) {
1349
56
    if (Path.Access != AS_public)  // Ignore non-public inheritance.
1350
9
      continue;
1351
47
1352
47
    ++NumPublicPaths;
1353
47
1354
74
    for (const CXXBasePathElement &PathElement : Path) {
1355
74
      // If the path contains a virtual base class we can't give any hint.
1356
74
      // -1: no hint.
1357
74
      if (PathElement.Base->isVirtual())
1358
9
        return CharUnits::fromQuantity(-1ULL);
1359
65
1360
65
      if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1361
9
        continue;
1362
56
1363
56
      // Accumulate the base class offsets.
1364
56
      const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1365
56
      Offset += L.getBaseClassOffset(
1366
56
          PathElement.Base->getType()->getAsCXXRecordDecl());
1367
56
    }
1368
47
  }
1369
50
1370
50
  // -2: Src is not a public base of Dst.
1371
50
  
if (41
NumPublicPaths == 041
)
1372
9
    return CharUnits::fromQuantity(-2ULL);
1373
32
1374
32
  // -3: Src is a multiple public base type but never a virtual base type.
1375
32
  if (NumPublicPaths > 1)
1376
0
    return CharUnits::fromQuantity(-3ULL);
1377
32
1378
32
  // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1379
32
  // Return the offset of Src from the origin of Dst.
1380
32
  return Offset;
1381
32
}
1382
1383
18
static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
1384
18
  // void __cxa_bad_typeid();
1385
18
  llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1386
18
1387
18
  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1388
18
}
1389
1390
bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1391
27
                                              QualType SrcRecordTy) {
1392
27
  return IsDeref;
1393
27
}
1394
1395
18
void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1396
18
  llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
1397
18
  llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1398
18
  Call->setDoesNotReturn();
1399
18
  CGF.Builder.CreateUnreachable();
1400
18
}
1401
1402
llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1403
                                       QualType SrcRecordTy,
1404
                                       Address ThisPtr,
1405
27
                                       llvm::Type *StdTypeInfoPtrTy) {
1406
27
  auto *ClassDecl =
1407
27
      cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
1408
27
  llvm::Value *Value =
1409
27
      CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
1410
27
1411
27
  // Load the type info.
1412
27
  Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1413
27
  return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
1414
27
}
1415
1416
bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1417
57
                                                       QualType SrcRecordTy) {
1418
57
  return SrcIsPtr;
1419
57
}
1420
1421
llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1422
    CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1423
55
    QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1424
55
  llvm::Type *PtrDiffLTy =
1425
55
      CGF.ConvertType(CGF.getContext().getPointerDiffType());
1426
55
  llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1427
55
1428
55
  llvm::Value *SrcRTTI =
1429
55
      CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1430
55
  llvm::Value *DestRTTI =
1431
55
      CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1432
55
1433
55
  // Compute the offset hint.
1434
55
  const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1435
55
  const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1436
55
  llvm::Value *OffsetHint = llvm::ConstantInt::get(
1437
55
      PtrDiffLTy,
1438
55
      computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1439
55
1440
55
  // Emit the call to __dynamic_cast.
1441
55
  llvm::Value *Value = ThisAddr.getPointer();
1442
55
  Value = CGF.EmitCastToVoidPtr(Value);
1443
55
1444
55
  llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1445
55
  Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1446
55
  Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1447
55
1448
55
  /// C++ [expr.dynamic.cast]p9:
1449
55
  ///   A failed cast to reference type throws std::bad_cast
1450
55
  if (DestTy->isReferenceType()) {
1451
8
    llvm::BasicBlock *BadCastBlock =
1452
8
        CGF.createBasicBlock("dynamic_cast.bad_cast");
1453
8
1454
8
    llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1455
8
    CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1456
8
1457
8
    CGF.EmitBlock(BadCastBlock);
1458
8
    EmitBadCastCall(CGF);
1459
8
  }
1460
55
1461
55
  return Value;
1462
55
}
1463
1464
llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1465
                                                  Address ThisAddr,
1466
                                                  QualType SrcRecordTy,
1467
2
                                                  QualType DestTy) {
1468
2
  llvm::Type *PtrDiffLTy =
1469
2
      CGF.ConvertType(CGF.getContext().getPointerDiffType());
1470
2
  llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1471
2
1472
2
  auto *ClassDecl =
1473
2
      cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
1474
2
  // Get the vtable pointer.
1475
2
  llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1476
2
      ClassDecl);
1477
2
1478
2
  // Get the offset-to-top from the vtable.
1479
2
  llvm::Value *OffsetToTop =
1480
2
      CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1481
2
  OffsetToTop =
1482
2
    CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1483
2
                                  "offset.to.top");
1484
2
1485
2
  // Finally, add the offset to the pointer.
1486
2
  llvm::Value *Value = ThisAddr.getPointer();
1487
2
  Value = CGF.EmitCastToVoidPtr(Value);
1488
2
  Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1489
2
1490
2
  return CGF.Builder.CreateBitCast(Value, DestLTy);
1491
2
}
1492
1493
9
bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1494
9
  llvm::FunctionCallee Fn = getBadCastFn(CGF);
1495
9
  llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1496
9
  Call->setDoesNotReturn();
1497
9
  CGF.Builder.CreateUnreachable();
1498
9
  return true;
1499
9
}
1500
1501
llvm::Value *
1502
ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1503
                                         Address This,
1504
                                         const CXXRecordDecl *ClassDecl,
1505
504
                                         const CXXRecordDecl *BaseClassDecl) {
1506
504
  llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
1507
504
  CharUnits VBaseOffsetOffset =
1508
504
      CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1509
504
                                                               BaseClassDecl);
1510
504
1511
504
  llvm::Value *VBaseOffsetPtr =
1512
504
    CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1513
504
                                   "vbase.offset.ptr");
1514
504
  VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1515
504
                                             CGM.PtrDiffTy->getPointerTo());
1516
504
1517
504
  llvm::Value *VBaseOffset =
1518
504
    CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1519
504
                                  "vbase.offset");
1520
504
1521
504
  return VBaseOffset;
1522
504
}
1523
1524
45.1k
void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1525
45.1k
  // Just make sure we're in sync with TargetCXXABI.
1526
45.1k
  assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1527
45.1k
1528
45.1k
  // The constructor used for constructing this as a base class;
1529
45.1k
  // ignores virtual bases.
1530
45.1k
  CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1531
45.1k
1532
45.1k
  // The constructor used for constructing this as a complete class;
1533
45.1k
  // constructs the virtual bases, then calls the base constructor.
1534
45.1k
  if (!D->getParent()->isAbstract()) {
1535
44.3k
    // We don't need to emit the complete ctor if the class is abstract.
1536
44.3k
    CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1537
44.3k
  }
1538
45.1k
}
1539
1540
CGCXXABI::AddedStructorArgs
1541
ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
1542
243k
                                      SmallVectorImpl<CanQualType> &ArgTys) {
1543
243k
  ASTContext &Context = getContext();
1544
243k
1545
243k
  // All parameters are already in place except VTT, which goes after 'this'.
1546
243k
  // These are Clang types, so we don't need to worry about sret yet.
1547
243k
1548
243k
  // Check if we need to add a VTT parameter (which has type void **).
1549
243k
  if ((isa<CXXConstructorDecl>(GD.getDecl()) ? 
GD.getCtorType() == Ctor_Base147k
1550
243k
                                             : 
GD.getDtorType() == Dtor_Base96.1k
) &&
1551
243k
      
cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0113k
) {
1552
1.10k
    ArgTys.insert(ArgTys.begin() + 1,
1553
1.10k
                  Context.getPointerType(Context.VoidPtrTy));
1554
1.10k
    return AddedStructorArgs::prefix(1);
1555
1.10k
  }
1556
242k
  return AddedStructorArgs{};
1557
242k
}
1558
1559
6.92k
void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1560
6.92k
  // The destructor used for destructing this as a base class; ignores
1561
6.92k
  // virtual bases.
1562
6.92k
  CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1563
6.92k
1564
6.92k
  // The destructor used for destructing this as a most-derived class;
1565
6.92k
  // call the base destructor and then destructs any virtual bases.
1566
6.92k
  CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1567
6.92k
1568
6.92k
  // The destructor in a virtual table is always a 'deleting'
1569
6.92k
  // destructor, which calls the complete destructor and then uses the
1570
6.92k
  // appropriate operator delete.
1571
6.92k
  if (D->isVirtual())
1572
472
    CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1573
6.92k
}
1574
1575
void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1576
                                              QualType &ResTy,
1577
47.1k
                                              FunctionArgList &Params) {
1578
47.1k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1579
47.1k
  assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1580
47.1k
1581
47.1k
  // Check if we need a VTT parameter as well.
1582
47.1k
  if (NeedsVTTParameter(CGF.CurGD)) {
1583
249
    ASTContext &Context = getContext();
1584
249
1585
249
    // FIXME: avoid the fake decl
1586
249
    QualType T = Context.getPointerType(Context.VoidPtrTy);
1587
249
    auto *VTTDecl = ImplicitParamDecl::Create(
1588
249
        Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1589
249
        T, ImplicitParamDecl::CXXVTT);
1590
249
    Params.insert(Params.begin() + 1, VTTDecl);
1591
249
    getStructorImplicitParamDecl(CGF) = VTTDecl;
1592
249
  }
1593
47.1k
}
1594
1595
85.2k
void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1596
85.2k
  // Naked functions have no prolog.
1597
85.2k
  if (CGF.CurFuncDecl && 
CGF.CurFuncDecl->hasAttr<NakedAttr>()84.9k
)
1598
1
    return;
1599
85.2k
1600
85.2k
  /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1601
85.2k
  /// adjustments are required, because they are all handled by thunks.
1602
85.2k
  setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
1603
85.2k
1604
85.2k
  /// Initialize the 'vtt' slot if needed.
1605
85.2k
  if (getStructorImplicitParamDecl(CGF)) {
1606
249
    getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1607
249
        CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1608
249
  }
1609
85.2k
1610
85.2k
  /// If this is a function that the ABI specifies returns 'this', initialize
1611
85.2k
  /// the return slot to 'this' at the start of the function.
1612
85.2k
  ///
1613
85.2k
  /// Unlike the setting of return types, this is done within the ABI
1614
85.2k
  /// implementation instead of by clients of CGCXXABI because:
1615
85.2k
  /// 1) getThisValue is currently protected
1616
85.2k
  /// 2) in theory, an ABI could implement 'this' returns some other way;
1617
85.2k
  ///    HasThisReturn only specifies a contract, not the implementation
1618
85.2k
  if (HasThisReturn(CGF.CurGD))
1619
372
    CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1620
85.2k
}
1621
1622
CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
1623
    CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1624
45.0k
    bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1625
45.0k
  if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1626
44.9k
    return AddedStructorArgs{};
1627
127
1628
127
  // Insert the implicit 'vtt' argument as the second argument.
1629
127
  llvm::Value *VTT =
1630
127
      CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1631
127
  QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1632
127
  Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
1633
127
  return AddedStructorArgs::prefix(1);  // Added one arg.
1634
127
}
1635
1636
void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1637
                                       const CXXDestructorDecl *DD,
1638
                                       CXXDtorType Type, bool ForVirtualBase,
1639
                                       bool Delegating, Address This,
1640
24.4k
                                       QualType ThisTy) {
1641
24.4k
  GlobalDecl GD(DD, Type);
1642
24.4k
  llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1643
24.4k
  QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1644
24.4k
1645
24.4k
  CGCallee Callee;
1646
24.4k
  if (getContext().getLangOpts().AppleKext &&
1647
24.4k
      
Type != Dtor_Base13
&&
DD->isVirtual()7
)
1648
7
    Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1649
24.4k
  else
1650
24.4k
    Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1651
24.4k
1652
24.4k
  CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, VTT, VTTTy,
1653
24.4k
                            nullptr);
1654
24.4k
}
1655
1656
void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1657
2.05k
                                          const CXXRecordDecl *RD) {
1658
2.05k
  llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1659
2.05k
  if (VTable->hasInitializer())
1660
590
    return;
1661
1.46k
1662
1.46k
  ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1663
1.46k
  const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1664
1.46k
  llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1665
1.46k
  llvm::Constant *RTTI =
1666
1.46k
      CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
1667
1.46k
1668
1.46k
  // Create and set the initializer.
1669
1.46k
  ConstantInitBuilder Builder(CGM);
1670
1.46k
  auto Components = Builder.beginStruct();
1671
1.46k
  CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1672
1.46k
  Components.finishAndSetAsInitializer(VTable);
1673
1.46k
1674
1.46k
  // Set the correct linkage.
1675
1.46k
  VTable->setLinkage(Linkage);
1676
1.46k
1677
1.46k
  if (CGM.supportsCOMDAT() && 
VTable->isWeakForLinker()588
)
1678
341
    VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1679
1.46k
1680
1.46k
  // Set the right visibility.
1681
1.46k
  CGM.setGVProperties(VTable, RD);
1682
1.46k
1683
1.46k
  // If this is the magic class __cxxabiv1::__fundamental_type_info,
1684
1.46k
  // we will emit the typeinfo for the fundamental types. This is the
1685
1.46k
  // same behaviour as GCC.
1686
1.46k
  const DeclContext *DC = RD->getDeclContext();
1687
1.46k
  if (RD->getIdentifier() &&
1688
1.46k
      
RD->getIdentifier()->isStr("__fundamental_type_info")1.45k
&&
1689
1.46k
      
isa<NamespaceDecl>(DC)4
&&
cast<NamespaceDecl>(DC)->getIdentifier()4
&&
1690
1.46k
      
cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1")4
&&
1691
1.46k
      
DC->getParent()->isTranslationUnit()4
)
1692
4
    EmitFundamentalRTTIDescriptors(RD);
1693
1.46k
1694
1.46k
  if (!VTable->isDeclarationForLinker())
1695
1.33k
    CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout);
1696
1.46k
}
1697
1698
bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1699
2.24k
    CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1700
2.24k
  if (Vptr.NearestVBase == nullptr)
1701
2.02k
    return false;
1702
221
  return NeedsVTTParameter(CGF.CurGD);
1703
221
}
1704
1705
llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1706
    CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1707
2.24k
    const CXXRecordDecl *NearestVBase) {
1708
2.24k
1709
2.24k
  if ((Base.getBase()->getNumVBases() || 
NearestVBase != nullptr1.80k
) &&
1710
2.24k
      
NeedsVTTParameter(CGF.CurGD)650
) {
1711
273
    return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1712
273
                                                  NearestVBase);
1713
273
  }
1714
1.97k
  return getVTableAddressPoint(Base, VTableClass);
1715
1.97k
}
1716
1717
llvm::Constant *
1718
ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1719
2.14k
                                     const CXXRecordDecl *VTableClass) {
1720
2.14k
  llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
1721
2.14k
1722
2.14k
  // Find the appropriate vtable within the vtable group, and the address point
1723
2.14k
  // within that vtable.
1724
2.14k
  VTableLayout::AddressPointLocation AddressPoint =
1725
2.14k
      CGM.getItaniumVTableContext()
1726
2.14k
          .getVTableLayout(VTableClass)
1727
2.14k
          .getAddressPoint(Base);
1728
2.14k
  llvm::Value *Indices[] = {
1729
2.14k
    llvm::ConstantInt::get(CGM.Int32Ty, 0),
1730
2.14k
    llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1731
2.14k
    llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
1732
2.14k
  };
1733
2.14k
1734
2.14k
  return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1735
2.14k
                                              Indices, /*InBounds=*/true,
1736
2.14k
                                              /*InRangeIndex=*/1);
1737
2.14k
}
1738
1739
llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1740
    CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1741
273
    const CXXRecordDecl *NearestVBase) {
1742
273
  assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1743
273
         NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1744
273
1745
273
  // Get the secondary vpointer index.
1746
273
  uint64_t VirtualPointerIndex =
1747
273
      CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1748
273
1749
273
  /// Load the VTT.
1750
273
  llvm::Value *VTT = CGF.LoadCXXVTT();
1751
273
  if (VirtualPointerIndex)
1752
92
    VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1753
273
1754
273
  // And load the address point from the VTT.
1755
273
  return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1756
273
}
1757
1758
llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1759
104
    BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1760
104
  return getVTableAddressPoint(Base, VTableClass);
1761
104
}
1762
1763
llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1764
5.14k
                                                     CharUnits VPtrOffset) {
1765
5.14k
  assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1766
5.14k
1767
5.14k
  llvm::GlobalVariable *&VTable = VTables[RD];
1768
5.14k
  if (VTable)
1769
3.16k
    return VTable;
1770
1.97k
1771
1.97k
  // Queue up this vtable for possible deferred emission.
1772
1.97k
  CGM.addDeferredVTable(RD);
1773
1.97k
1774
1.97k
  SmallString<256> Name;
1775
1.97k
  llvm::raw_svector_ostream Out(Name);
1776
1.97k
  getMangleContext().mangleCXXVTable(RD, Out);
1777
1.97k
1778
1.97k
  const VTableLayout &VTLayout =
1779
1.97k
      CGM.getItaniumVTableContext().getVTableLayout(RD);
1780
1.97k
  llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1781
1.97k
1782
1.97k
  // Use pointer alignment for the vtable. Otherwise we would align them based
1783
1.97k
  // on the size of the initializer which doesn't make sense as only single
1784
1.97k
  // values are read.
1785
1.97k
  unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1786
1.97k
1787
1.97k
  VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1788
1.97k
      Name, VTableType, llvm::GlobalValue::ExternalLinkage,
1789
1.97k
      getContext().toCharUnitsFromBits(PAlign).getQuantity());
1790
1.97k
  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1791
1.97k
1792
1.97k
  CGM.setGVProperties(VTable, RD);
1793
1.97k
1794
1.97k
  return VTable;
1795
1.97k
}
1796
1797
CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1798
                                                  GlobalDecl GD,
1799
                                                  Address This,
1800
                                                  llvm::Type *Ty,
1801
770
                                                  SourceLocation Loc) {
1802
770
  Ty = Ty->getPointerTo()->getPointerTo();
1803
770
  auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1804
770
  llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
1805
770
1806
770
  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1807
770
  llvm::Value *VFunc;
1808
770
  if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1809
8
    VFunc = CGF.EmitVTableTypeCheckedLoad(
1810
8
        MethodDecl->getParent(), VTable,
1811
8
        VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1812
762
  } else {
1813
762
    CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1814
762
1815
762
    llvm::Value *VFuncPtr =
1816
762
        CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1817
762
    auto *VFuncLoad =
1818
762
        CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1819
762
1820
762
    // Add !invariant.load md to virtual function load to indicate that
1821
762
    // function didn't change inside vtable.
1822
762
    // It's safe to add it without -fstrict-vtable-pointers, but it would not
1823
762
    // help in devirtualization because it will only matter if we will have 2
1824
762
    // the same virtual function loads from the same vtable load, which won't
1825
762
    // happen without enabled devirtualization with -fstrict-vtable-pointers.
1826
762
    if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1827
762
        
CGM.getCodeGenOpts().StrictVTablePointers68
)
1828
44
      VFuncLoad->setMetadata(
1829
44
          llvm::LLVMContext::MD_invariant_load,
1830
44
          llvm::MDNode::get(CGM.getLLVMContext(),
1831
44
                            llvm::ArrayRef<llvm::Metadata *>()));
1832
762
    VFunc = VFuncLoad;
1833
762
  }
1834
770
1835
770
  CGCallee Callee(GD, VFunc);
1836
770
  return Callee;
1837
770
}
1838
1839
llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1840
    CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1841
36
    Address This, DeleteOrMemberCallExpr E) {
1842
36
  auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1843
36
  auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1844
36
  assert((CE != nullptr) ^ (D != nullptr));
1845
36
  assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1846
36
  assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1847
36
1848
36
  GlobalDecl GD(Dtor, DtorType);
1849
36
  const CGFunctionInfo *FInfo =
1850
36
      &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1851
36
  llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1852
36
  CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1853
36
1854
36
  QualType ThisTy;
1855
36
  if (CE) {
1856
8
    ThisTy = CE->getObjectType();
1857
28
  } else {
1858
28
    ThisTy = D->getDestroyedType();
1859
28
  }
1860
36
1861
36
  CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, nullptr,
1862
36
                            QualType(), nullptr);
1863
36
  return nullptr;
1864
36
}
1865
1866
352
void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1867
352
  CodeGenVTables &VTables = CGM.getVTables();
1868
352
  llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1869
352
  VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1870
352
}
1871
1872
bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
1873
403
    const CXXRecordDecl *RD) const {
1874
403
  // We don't emit available_externally vtables if we are in -fapple-kext mode
1875
403
  // because kext mode does not permit devirtualization.
1876
403
  if (CGM.getLangOpts().AppleKext)
1877
0
    return false;
1878
403
1879
403
  // If the vtable is hidden then it is not safe to emit an available_externally
1880
403
  // copy of vtable.
1881
403
  if (isVTableHidden(RD))
1882
19
    return false;
1883
384
1884
384
  if (CGM.getCodeGenOpts().ForceEmitVTables)
1885
52
    return true;
1886
332
1887
332
  // If we don't have any not emitted inline virtual function then we are safe
1888
332
  // to emit an available_externally copy of vtable.
1889
332
  // FIXME we can still emit a copy of the vtable if we
1890
332
  // can emit definition of the inline functions.
1891
332
  if (hasAnyUnusedVirtualInlineFunction(RD))
1892
142
    return false;
1893
190
1894
190
  // For a class with virtual bases, we must also be able to speculatively
1895
190
  // emit the VTT, because CodeGen doesn't have separate notions of "can emit
1896
190
  // the vtable" and "can emit the VTT". For a base subobject, this means we
1897
190
  // need to be able to emit non-virtual base vtables.
1898
190
  if (RD->getNumVBases()) {
1899
40
    for (const auto &B : RD->bases()) {
1900
40
      auto *BRD = B.getType()->getAsCXXRecordDecl();
1901
40
      assert(BRD && "no class for base specifier");
1902
40
      if (B.isVirtual() || 
!BRD->isDynamicClass()22
)
1903
19
        continue;
1904
21
      if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1905
8
        return false;
1906
21
    }
1907
35
  }
1908
190
1909
190
  
return true182
;
1910
190
}
1911
1912
370
bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1913
370
  if (!canSpeculativelyEmitVTableAsBaseClass(RD))
1914
161
    return false;
1915
209
1916
209
  // For a complete-object vtable (or more specifically, for the VTT), we need
1917
209
  // to be able to speculatively emit the vtables of all dynamic virtual bases.
1918
209
  for (const auto &B : RD->vbases()) {
1919
18
    auto *BRD = B.getType()->getAsCXXRecordDecl();
1920
18
    assert(BRD && "no class for base specifier");
1921
18
    if (!BRD->isDynamicClass())
1922
6
      continue;
1923
12
    if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1924
0
      return false;
1925
12
  }
1926
209
1927
209
  return true;
1928
209
}
1929
static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1930
                                          Address InitialPtr,
1931
                                          int64_t NonVirtualAdjustment,
1932
                                          int64_t VirtualAdjustment,
1933
352
                                          bool IsReturnAdjustment) {
1934
352
  if (!NonVirtualAdjustment && 
!VirtualAdjustment204
)
1935
13
    return InitialPtr.getPointer();
1936
339
1937
339
  Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
1938
339
1939
339
  // In a base-to-derived cast, the non-virtual adjustment is applied first.
1940
339
  if (NonVirtualAdjustment && 
!IsReturnAdjustment148
) {
1941
137
    V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1942
137
                              CharUnits::fromQuantity(NonVirtualAdjustment));
1943
137
  }
1944
339
1945
339
  // Perform the virtual adjustment if we have one.
1946
339
  llvm::Value *ResultPtr;
1947
339
  if (VirtualAdjustment) {
1948
205
    llvm::Type *PtrDiffTy =
1949
205
        CGF.ConvertType(CGF.getContext().getPointerDiffType());
1950
205
1951
205
    Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
1952
205
    llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1953
205
1954
205
    llvm::Value *OffsetPtr =
1955
205
        CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1956
205
1957
205
    OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1958
205
1959
205
    // Load the adjustment offset from the vtable.
1960
205
    llvm::Value *Offset =
1961
205
      CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
1962
205
1963
205
    // Adjust our pointer.
1964
205
    ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1965
205
  } else {
1966
134
    ResultPtr = V.getPointer();
1967
134
  }
1968
339
1969
339
  // In a derived-to-base conversion, the non-virtual adjustment is
1970
339
  // applied second.
1971
339
  if (NonVirtualAdjustment && 
IsReturnAdjustment148
) {
1972
11
    ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1973
11
                                                       NonVirtualAdjustment);
1974
11
  }
1975
339
1976
339
  // Cast back to the original type.
1977
339
  return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
1978
339
}
1979
1980
llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1981
                                                  Address This,
1982
323
                                                  const ThisAdjustment &TA) {
1983
323
  return performTypeAdjustment(CGF, This, TA.NonVirtual,
1984
323
                               TA.Virtual.Itanium.VCallOffsetOffset,
1985
323
                               /*IsReturnAdjustment=*/false);
1986
323
}
1987
1988
llvm::Value *
1989
ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
1990
29
                                       const ReturnAdjustment &RA) {
1991
29
  return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1992
29
                               RA.Virtual.Itanium.VBaseOffsetOffset,
1993
29
                               /*IsReturnAdjustment=*/true);
1994
29
}
1995
1996
void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1997
6
                                    RValue RV, QualType ResultType) {
1998
6
  if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1999
0
    return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
2000
6
2001
6
  // Destructor thunks in the ARM ABI have indeterminate results.
2002
6
  llvm::Type *T = CGF.ReturnValue.getElementType();
2003
6
  RValue Undef = RValue::get(llvm::UndefValue::get(T));
2004
6
  return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
2005
6
}
2006
2007
/************************** Array allocation cookies **************************/
2008
2009
167
CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2010
167
  // The array cookie is a size_t; pad that up to the element alignment.
2011
167
  // The cookie is actually right-justified in that space.
2012
167
  return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
2013
167
                  CGM.getContext().getTypeAlignInChars(elementType));
2014
167
}
2015
2016
Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2017
                                             Address NewPtr,
2018
                                             llvm::Value *NumElements,
2019
                                             const CXXNewExpr *expr,
2020
41
                                             QualType ElementType) {
2021
41
  assert(requiresArrayCookie(expr));
2022
41
2023
41
  unsigned AS = NewPtr.getAddressSpace();
2024
41
2025
41
  ASTContext &Ctx = getContext();
2026
41
  CharUnits SizeSize = CGF.getSizeSize();
2027
41
2028
41
  // The size of the cookie.
2029
41
  CharUnits CookieSize =
2030
41
    std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
2031
41
  assert(CookieSize == getArrayCookieSizeImpl(ElementType));
2032
41
2033
41
  // Compute an offset to the cookie.
2034
41
  Address CookiePtr = NewPtr;
2035
41
  CharUnits CookieOffset = CookieSize - SizeSize;
2036
41
  if (!CookieOffset.isZero())
2037
5
    CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
2038
41
2039
41
  // Write the number of elements into the appropriate slot.
2040
41
  Address NumElementsPtr =
2041
41
      CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
2042
41
  llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
2043
41
2044
41
  // Handle the array cookie specially in ASan.
2045
41
  if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && 
AS == 08
&&
2046
41
      
(8
expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()8
||
2047
8
       
CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie4
)) {
2048
6
    // The store to the CookiePtr does not need to be instrumented.
2049
6
    CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
2050
6
    llvm::FunctionType *FTy =
2051
6
        llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
2052
6
    llvm::FunctionCallee F =
2053
6
        CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
2054
6
    CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
2055
6
  }
2056
41
2057
41
  // Finally, compute a pointer to the actual data buffer by skipping
2058
41
  // over the cookie completely.
2059
41
  return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
2060
41
}
2061
2062
llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2063
                                                Address allocPtr,
2064
44
                                                CharUnits cookieSize) {
2065
44
  // The element size is right-justified in the cookie.
2066
44
  Address numElementsPtr = allocPtr;
2067
44
  CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
2068
44
  if (!numElementsOffset.isZero())
2069
5
    numElementsPtr =
2070
5
      CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
2071
44
2072
44
  unsigned AS = allocPtr.getAddressSpace();
2073
44
  numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
2074
44
  if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || 
AS != 02
)
2075
42
    return CGF.Builder.CreateLoad(numElementsPtr);
2076
2
  // In asan mode emit a function call instead of a regular load and let the
2077
2
  // run-time deal with it: if the shadow is properly poisoned return the
2078
2
  // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2079
2
  // We can't simply ignore this load using nosanitize metadata because
2080
2
  // the metadata may be lost.
2081
2
  llvm::FunctionType *FTy =
2082
2
      llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
2083
2
  llvm::FunctionCallee F =
2084
2
      CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
2085
2
  return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
2086
2
}
2087
2088
64
CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2089
64
  // ARM says that the cookie is always:
2090
64
  //   struct array_cookie {
2091
64
  //     std::size_t element_size; // element_size != 0
2092
64
  //     std::size_t element_count;
2093
64
  //   };
2094
64
  // But the base ABI doesn't give anything an alignment greater than
2095
64
  // 8, so we can dismiss this as typical ABI-author blindness to
2096
64
  // actual language complexity and round up to the element alignment.
2097
64
  return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2098
64
                  CGM.getContext().getTypeAlignInChars(elementType));
2099
64
}
2100
2101
Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2102
                                         Address newPtr,
2103
                                         llvm::Value *numElements,
2104
                                         const CXXNewExpr *expr,
2105
18
                                         QualType elementType) {
2106
18
  assert(requiresArrayCookie(expr));
2107
18
2108
18
  // The cookie is always at the start of the buffer.
2109
18
  Address cookie = newPtr;
2110
18
2111
18
  // The first element is the element size.
2112
18
  cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
2113
18
  llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2114
18
                 getContext().getTypeSizeInChars(elementType).getQuantity());
2115
18
  CGF.Builder.CreateStore(elementSize, cookie);
2116
18
2117
18
  // The second element is the element count.
2118
18
  cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
2119
18
  CGF.Builder.CreateStore(numElements, cookie);
2120
18
2121
18
  // Finally, compute a pointer to the actual data buffer by skipping
2122
18
  // over the cookie completely.
2123
18
  CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
2124
18
  return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2125
18
}
2126
2127
llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2128
                                            Address allocPtr,
2129
10
                                            CharUnits cookieSize) {
2130
10
  // The number of elements is at offset sizeof(size_t) relative to
2131
10
  // the allocated pointer.
2132
10
  Address numElementsPtr
2133
10
    = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
2134
10
2135
10
  numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
2136
10
  return CGF.Builder.CreateLoad(numElementsPtr);
2137
10
}
2138
2139
/*********************** Static local initialization **************************/
2140
2141
static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2142
164
                                              llvm::PointerType *GuardPtrTy) {
2143
164
  // int __cxa_guard_acquire(__guard *guard_object);
2144
164
  llvm::FunctionType *FTy =
2145
164
    llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
2146
164
                            GuardPtrTy, /*isVarArg=*/false);
2147
164
  return CGM.CreateRuntimeFunction(
2148
164
      FTy, "__cxa_guard_acquire",
2149
164
      llvm::AttributeList::get(CGM.getLLVMContext(),
2150
164
                               llvm::AttributeList::FunctionIndex,
2151
164
                               llvm::Attribute::NoUnwind));
2152
164
}
2153
2154
static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2155
164
                                              llvm::PointerType *GuardPtrTy) {
2156
164
  // void __cxa_guard_release(__guard *guard_object);
2157
164
  llvm::FunctionType *FTy =
2158
164
    llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2159
164
  return CGM.CreateRuntimeFunction(
2160
164
      FTy, "__cxa_guard_release",
2161
164
      llvm::AttributeList::get(CGM.getLLVMContext(),
2162
164
                               llvm::AttributeList::FunctionIndex,
2163
164
                               llvm::Attribute::NoUnwind));
2164
164
}
2165
2166
static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2167
32
                                            llvm::PointerType *GuardPtrTy) {
2168
32
  // void __cxa_guard_abort(__guard *guard_object);
2169
32
  llvm::FunctionType *FTy =
2170
32
    llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2171
32
  return CGM.CreateRuntimeFunction(
2172
32
      FTy, "__cxa_guard_abort",
2173
32
      llvm::AttributeList::get(CGM.getLLVMContext(),
2174
32
                               llvm::AttributeList::FunctionIndex,
2175
32
                               llvm::Attribute::NoUnwind));
2176
32
}
2177
2178
namespace {
2179
  struct CallGuardAbort final : EHScopeStack::Cleanup {
2180
    llvm::GlobalVariable *Guard;
2181
164
    CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
2182
2183
32
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2184
32
      CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2185
32
                                  Guard);
2186
32
    }
2187
  };
2188
}
2189
2190
/// The ARM code here follows the Itanium code closely enough that we
2191
/// just special-case it at particular places.
2192
void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2193
                                    const VarDecl &D,
2194
                                    llvm::GlobalVariable *var,
2195
6.75k
                                    bool shouldPerformInit) {
2196
6.75k
  CGBuilderTy &Builder = CGF.Builder;
2197
6.75k
2198
6.75k
  // Inline variables that weren't instantiated from variable templates have
2199
6.75k
  // partially-ordered initialization within their translation unit.
2200
6.75k
  bool NonTemplateInline =
2201
6.75k
      D.isInline() &&
2202
6.75k
      
!isTemplateInstantiation(D.getTemplateSpecializationKind())50
;
2203
6.75k
2204
6.75k
  // We only need to use thread-safe statics for local non-TLS variables and
2205
6.75k
  // inline variables; other global initialization is always single-threaded
2206
6.75k
  // or (through lazy dynamic loading in multiple threads) unsequenced.
2207
6.75k
  bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
2208
6.75k
                    
(383
D.isLocalVarDecl()383
||
NonTemplateInline163
) &&
2209
6.75k
                    
!D.getTLSKind()229
;
2210
6.75k
2211
6.75k
  // If we have a global variable with internal linkage and thread-safe statics
2212
6.75k
  // are disabled, we can just let the guard variable be of type i8.
2213
6.75k
  bool useInt8GuardVariable = !threadsafe && 
var->hasInternalLinkage()6.59k
;
2214
6.75k
2215
6.75k
  llvm::IntegerType *guardTy;
2216
6.75k
  CharUnits guardAlignment;
2217
6.75k
  if (useInt8GuardVariable) {
2218
6.42k
    guardTy = CGF.Int8Ty;
2219
6.42k
    guardAlignment = CharUnits::One();
2220
6.42k
  } else {
2221
331
    // Guard variables are 64 bits in the generic ABI and size width on ARM
2222
331
    // (i.e. 32-bit on AArch32, 64-bit on AArch64).
2223
331
    if (UseARMGuardVarABI) {
2224
13
      guardTy = CGF.SizeTy;
2225
13
      guardAlignment = CGF.getSizeAlign();
2226
318
    } else {
2227
318
      guardTy = CGF.Int64Ty;
2228
318
      guardAlignment = CharUnits::fromQuantity(
2229
318
                             CGM.getDataLayout().getABITypeAlignment(guardTy));
2230
318
    }
2231
331
  }
2232
6.75k
  llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
2233
6.75k
2234
6.75k
  // Create the guard variable if we don't already have it (as we
2235
6.75k
  // might if we're double-emitting this function body).
2236
6.75k
  llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2237
6.75k
  if (!guard) {
2238
6.75k
    // Mangle the name for the guard.
2239
6.75k
    SmallString<256> guardName;
2240
6.75k
    {
2241
6.75k
      llvm::raw_svector_ostream out(guardName);
2242
6.75k
      getMangleContext().mangleStaticGuardVariable(&D, out);
2243
6.75k
    }
2244
6.75k
2245
6.75k
    // Create the guard variable with a zero-initializer.
2246
6.75k
    // Just absorb linkage and visibility from the guarded variable.
2247
6.75k
    guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2248
6.75k
                                     false, var->getLinkage(),
2249
6.75k
                                     llvm::ConstantInt::get(guardTy, 0),
2250
6.75k
                                     guardName.str());
2251
6.75k
    guard->setDSOLocal(var->isDSOLocal());
2252
6.75k
    guard->setVisibility(var->getVisibility());
2253
6.75k
    // If the variable is thread-local, so is its guard variable.
2254
6.75k
    guard->setThreadLocalMode(var->getThreadLocalMode());
2255
6.75k
    guard->setAlignment(guardAlignment.getAsAlign());
2256
6.75k
2257
6.75k
    // The ABI says: "It is suggested that it be emitted in the same COMDAT
2258
6.75k
    // group as the associated data object." In practice, this doesn't work for
2259
6.75k
    // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
2260
6.75k
    llvm::Comdat *C = var->getComdat();
2261
6.75k
    if (!D.isLocalVarDecl() && 
C163
&&
2262
6.75k
        
(130
CGM.getTarget().getTriple().isOSBinFormatELF()130
||
2263
130
         
CGM.getTarget().getTriple().isOSBinFormatWasm()0
)) {
2264
130
      guard->setComdat(C);
2265
130
      // An inline variable's guard function is run from the per-TU
2266
130
      // initialization function, not via a dedicated global ctor function, so
2267
130
      // we can't put it in a comdat.
2268
130
      if (!NonTemplateInline)
2269
121
        CGF.CurFn->setComdat(C);
2270
6.62k
    } else if (CGM.supportsCOMDAT() && 
guard->isWeakForLinker()156
) {
2271
31
      guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
2272
31
    }
2273
6.75k
2274
6.75k
    CGM.setStaticLocalDeclGuardAddress(&D, guard);
2275
6.75k
  }
2276
6.75k
2277
6.75k
  Address guardAddr = Address(guard, guardAlignment);
2278
6.75k
2279
6.75k
  // Test whether the variable has completed initialization.
2280
6.75k
  //
2281
6.75k
  // Itanium C++ ABI 3.3.2:
2282
6.75k
  //   The following is pseudo-code showing how these functions can be used:
2283
6.75k
  //     if (obj_guard.first_byte == 0) {
2284
6.75k
  //       if ( __cxa_guard_acquire (&obj_guard) ) {
2285
6.75k
  //         try {
2286
6.75k
  //           ... initialize the object ...;
2287
6.75k
  //         } catch (...) {
2288
6.75k
  //            __cxa_guard_abort (&obj_guard);
2289
6.75k
  //            throw;
2290
6.75k
  //         }
2291
6.75k
  //         ... queue object destructor with __cxa_atexit() ...;
2292
6.75k
  //         __cxa_guard_release (&obj_guard);
2293
6.75k
  //       }
2294
6.75k
  //     }
2295
6.75k
2296
6.75k
  // Load the first byte of the guard variable.
2297
6.75k
  llvm::LoadInst *LI =
2298
6.75k
      Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
2299
6.75k
2300
6.75k
  // Itanium ABI:
2301
6.75k
  //   An implementation supporting thread-safety on multiprocessor
2302
6.75k
  //   systems must also guarantee that references to the initialized
2303
6.75k
  //   object do not occur before the load of the initialization flag.
2304
6.75k
  //
2305
6.75k
  // In LLVM, we do this by marking the load Acquire.
2306
6.75k
  if (threadsafe)
2307
164
    LI->setAtomic(llvm::AtomicOrdering::Acquire);
2308
6.75k
2309
6.75k
  // For ARM, we should only check the first bit, rather than the entire byte:
2310
6.75k
  //
2311
6.75k
  // ARM C++ ABI 3.2.3.1:
2312
6.75k
  //   To support the potential use of initialization guard variables
2313
6.75k
  //   as semaphores that are the target of ARM SWP and LDREX/STREX
2314
6.75k
  //   synchronizing instructions we define a static initialization
2315
6.75k
  //   guard variable to be a 4-byte aligned, 4-byte word with the
2316
6.75k
  //   following inline access protocol.
2317
6.75k
  //     #define INITIALIZED 1
2318
6.75k
  //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
2319
6.75k
  //       if (__cxa_guard_acquire(&obj_guard))
2320
6.75k
  //         ...
2321
6.75k
  //     }
2322
6.75k
  //
2323
6.75k
  // and similarly for ARM64:
2324
6.75k
  //
2325
6.75k
  // ARM64 C++ ABI 3.2.2:
2326
6.75k
  //   This ABI instead only specifies the value bit 0 of the static guard
2327
6.75k
  //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
2328
6.75k
  //   variable is not initialized and 1 when it is.
2329
6.75k
  llvm::Value *V =
2330
6.75k
      (UseARMGuardVarABI && 
!useInt8GuardVariable13
)
2331
6.75k
          ? 
Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))13
2332
6.75k
          : 
LI6.74k
;
2333
6.75k
  llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
2334
6.75k
2335
6.75k
  llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2336
6.75k
  llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2337
6.75k
2338
6.75k
  // Check if the first byte of the guard variable is zero.
2339
6.75k
  CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2340
6.75k
                               CodeGenFunction::GuardKind::VariableGuard, &D);
2341
6.75k
2342
6.75k
  CGF.EmitBlock(InitCheckBlock);
2343
6.75k
2344
6.75k
  // Variables used when coping with thread-safe statics and exceptions.
2345
6.75k
  if (threadsafe) {
2346
164
    // Call __cxa_guard_acquire.
2347
164
    llvm::Value *V
2348
164
      = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2349
164
2350
164
    llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2351
164
2352
164
    Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2353
164
                         InitBlock, EndBlock);
2354
164
2355
164
    // Call __cxa_guard_abort along the exceptional edge.
2356
164
    CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2357
164
2358
164
    CGF.EmitBlock(InitBlock);
2359
164
  }
2360
6.75k
2361
6.75k
  // Emit the initializer and add a global destructor if appropriate.
2362
6.75k
  CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2363
6.75k
2364
6.75k
  if (threadsafe) {
2365
164
    // Pop the guard-abort cleanup if we pushed one.
2366
164
    CGF.PopCleanupBlock();
2367
164
2368
164
    // Call __cxa_guard_release.  This cannot throw.
2369
164
    CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2370
164
                                guardAddr.getPointer());
2371
6.59k
  } else {
2372
6.59k
    Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
2373
6.59k
  }
2374
6.75k
2375
6.75k
  CGF.EmitBlock(EndBlock);
2376
6.75k
}
2377
2378
/// Register a global destructor using __cxa_atexit.
2379
static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2380
                                        llvm::FunctionCallee dtor,
2381
3.10k
                                        llvm::Constant *addr, bool TLS) {
2382
3.10k
  assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2383
3.10k
         "__cxa_atexit is disabled");
2384
3.10k
  const char *Name = "__cxa_atexit";
2385
3.10k
  if (TLS) {
2386
99
    const llvm::Triple &T = CGF.getTarget().getTriple();
2387
99
    Name = T.isOSDarwin() ?  
"_tlv_atexit"19
:
"__cxa_thread_atexit"80
;
2388
99
  }
2389
3.10k
2390
3.10k
  // We're assuming that the destructor function is something we can
2391
3.10k
  // reasonably call with the default CC.  Go ahead and cast it to the
2392
3.10k
  // right prototype.
2393
3.10k
  llvm::Type *dtorTy =
2394
3.10k
    llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2395
3.10k
2396
3.10k
  // Preserve address space of addr.
2397
3.10k
  auto AddrAS = addr ? 
addr->getType()->getPointerAddressSpace()3.10k
:
05
;
2398
3.10k
  auto AddrInt8PtrTy =
2399
3.10k
      AddrAS ? 
CGF.Int8Ty->getPointerTo(AddrAS)0
: CGF.Int8PtrTy;
2400
3.10k
2401
3.10k
  // Create a variable that binds the atexit to this shared object.
2402
3.10k
  llvm::Constant *handle =
2403
3.10k
      CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2404
3.10k
  auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2405
3.10k
  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2406
3.10k
2407
3.10k
  // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2408
3.10k
  llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
2409
3.10k
  llvm::FunctionType *atexitTy =
2410
3.10k
    llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2411
3.10k
2412
3.10k
  // Fetch the actual function.
2413
3.10k
  llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2414
3.10k
  if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
2415
3.10k
    fn->setDoesNotThrow();
2416
3.10k
2417
3.10k
  if (!addr)
2418
5
    // addr is null when we are trying to register a dtor annotated with
2419
5
    // __attribute__((destructor)) in a constructor function. Using null here is
2420
5
    // okay because this argument is just passed back to the destructor
2421
5
    // function.
2422
5
    addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2423
3.10k
2424
3.10k
  llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
2425
3.10k
                             cast<llvm::Constant>(dtor.getCallee()), dtorTy),
2426
3.10k
                         llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
2427
3.10k
                         handle};
2428
3.10k
  CGF.EmitNounwindRuntimeCall(atexit, args);
2429
3.10k
}
2430
2431
24.9k
void CodeGenModule::registerGlobalDtorsWithAtExit() {
2432
24.9k
  for (const auto &I : DtorsUsingAtExit) {
2433
6
    int Priority = I.first;
2434
6
    const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2435
6
2436
6
    // Create a function that registers destructors that have the same priority.
2437
6
    //
2438
6
    // Since constructor functions are run in non-descending order of their
2439
6
    // priorities, destructors are registered in non-descending order of their
2440
6
    // priorities, and since destructor functions are run in the reverse order
2441
6
    // of their registration, destructor functions are run in non-ascending
2442
6
    // order of their priorities.
2443
6
    CodeGenFunction CGF(*this);
2444
6
    std::string GlobalInitFnName =
2445
6
        std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2446
6
    llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2447
6
    llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2448
6
        FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2449
6
        SourceLocation());
2450
6
    ASTContext &Ctx = getContext();
2451
6
    QualType ReturnTy = Ctx.VoidTy;
2452
6
    QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
2453
6
    FunctionDecl *FD = FunctionDecl::Create(
2454
6
        Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
2455
6
        &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
2456
6
        false, false);
2457
6
    CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
2458
6
                      getTypes().arrangeNullaryFunction(), FunctionArgList(),
2459
6
                      SourceLocation(), SourceLocation());
2460
6
2461
10
    for (auto *Dtor : Dtors) {
2462
10
      // Register the destructor function calling __cxa_atexit if it is
2463
10
      // available. Otherwise fall back on calling atexit.
2464
10
      if (getCodeGenOpts().CXAAtExit)
2465
5
        emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2466
5
      else
2467
5
        CGF.registerGlobalDtorWithAtExit(Dtor);
2468
10
    }
2469
6
2470
6
    CGF.FinishFunction();
2471
6
    AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2472
6
  }
2473
24.9k
}
2474
2475
/// Register a global destructor as best as we know how.
2476
void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2477
                                       llvm::FunctionCallee dtor,
2478
3.12k
                                       llvm::Constant *addr) {
2479
3.12k
  if (D.isNoDestroy(CGM.getContext()))
2480
0
    return;
2481
3.12k
2482
3.12k
  // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
2483
3.12k
  // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
2484
3.12k
  // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
2485
3.12k
  // We can always use __cxa_thread_atexit.
2486
3.12k
  if (CGM.getCodeGenOpts().CXAAtExit || 
D.getTLSKind()44
)
2487
3.10k
    return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2488
24
2489
24
  // In Apple kexts, we want to add a global destructor entry.
2490
24
  // FIXME: shouldn't this be guarded by some variable?
2491
24
  if (CGM.getLangOpts().AppleKext) {
2492
6
    // Generate a global destructor entry.
2493
6
    return CGM.AddCXXDtorEntry(dtor, addr);
2494
6
  }
2495
18
2496
18
  CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
2497
18
}
2498
2499
static bool isThreadWrapperReplaceable(const VarDecl *VD,
2500
733
                                       CodeGen::CodeGenModule &CGM) {
2501
733
  assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2502
733
  // Darwin prefers to have references to thread local variables to go through
2503
733
  // the thread wrapper instead of directly referencing the backing variable.
2504
733
  return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2505
733
         CGM.getTarget().getTriple().isOSDarwin();
2506
733
}
2507
2508
/// Get the appropriate linkage for the wrapper function. This is essentially
2509
/// the weak form of the variable's linkage; every translation unit which needs
2510
/// the wrapper emits a copy, and we want the linker to merge them.
2511
static llvm::GlobalValue::LinkageTypes
2512
203
getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2513
203
  llvm::GlobalValue::LinkageTypes VarLinkage =
2514
203
      CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
2515
203
2516
203
  // For internal linkage variables, we don't need an external or weak wrapper.
2517
203
  if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2518
12
    return VarLinkage;
2519
191
2520
191
  // If the thread wrapper is replaceable, give it appropriate linkage.
2521
191
  if (isThreadWrapperReplaceable(VD, CGM))
2522
52
    if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2523
52
        
!llvm::GlobalVariable::isWeakODRLinkage(VarLinkage)45
)
2524
38
      return VarLinkage;
2525
153
  return llvm::GlobalValue::WeakODRLinkage;
2526
153
}
2527
2528
llvm::Function *
2529
ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
2530
232
                                             llvm::Value *Val) {
2531
232
  // Mangle the name for the thread_local wrapper function.
2532
232
  SmallString<256> WrapperName;
2533
232
  {
2534
232
    llvm::raw_svector_ostream Out(WrapperName);
2535
232
    getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2536
232
  }
2537
232
2538
232
  // FIXME: If VD is a definition, we should regenerate the function attributes
2539
232
  // before returning.
2540
232
  if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
2541
29
    return cast<llvm::Function>(V);
2542
203
2543
203
  QualType RetQT = VD->getType();
2544
203
  if (RetQT->isReferenceType())
2545
2
    RetQT = RetQT.getNonReferenceType();
2546
203
2547
203
  const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2548
203
      getContext().getPointerType(RetQT), FunctionArgList());
2549
203
2550
203
  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
2551
203
  llvm::Function *Wrapper =
2552
203
      llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2553
203
                             WrapperName.str(), &CGM.getModule());
2554
203
2555
203
  if (CGM.supportsCOMDAT() && 
Wrapper->isWeakForLinker()149
)
2556
139
    Wrapper->setComdat(CGM.getModule().getOrInsertComdat(Wrapper->getName()));
2557
203
2558
203
  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
2559
203
2560
203
  // Always resolve references to the wrapper at link time.
2561
203
  if (!Wrapper->hasLocalLinkage())
2562
191
    if (!isThreadWrapperReplaceable(VD, CGM) ||
2563
191
        
llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage())52
||
2564
191
        
llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())52
||
2565
191
        
VD->getVisibility() == HiddenVisibility38
)
2566
154
      Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
2567
203
2568
203
  if (isThreadWrapperReplaceable(VD, CGM)) {
2569
54
    Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2570
54
    Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2571
54
  }
2572
203
2573
203
  ThreadWrappers.push_back({VD, Wrapper});
2574
203
  return Wrapper;
2575
203
}
2576
2577
void ItaniumCXXABI::EmitThreadLocalInitFuncs(
2578
    CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2579
    ArrayRef<llvm::Function *> CXXThreadLocalInits,
2580
24.2k
    ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2581
24.2k
  llvm::Function *InitFunc = nullptr;
2582
24.2k
2583
24.2k
  // Separate initializers into those with ordered (or partially-ordered)
2584
24.2k
  // initialization and those with unordered initialization.
2585
24.2k
  llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2586
24.2k
  llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2587
24.4k
  for (unsigned I = 0; I != CXXThreadLocalInits.size(); 
++I147
) {
2588
147
    if (isTemplateInstantiation(
2589
147
            CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2590
73
      UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2591
73
          CXXThreadLocalInits[I];
2592
74
    else
2593
74
      OrderedInits.push_back(CXXThreadLocalInits[I]);
2594
147
  }
2595
24.2k
2596
24.2k
  if (!OrderedInits.empty()) {
2597
40
    // Generate a guarded initialization function.
2598
40
    llvm::FunctionType *FTy =
2599
40
        llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2600
40
    const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2601
40
    InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
2602
40
                                                      SourceLocation(),
2603
40
                                                      /*TLS=*/true);
2604
40
    llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2605
40
        CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2606
40
        llvm::GlobalVariable::InternalLinkage,
2607
40
        llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2608
40
    Guard->setThreadLocal(true);
2609
40
2610
40
    CharUnits GuardAlign = CharUnits::One();
2611
40
    Guard->setAlignment(GuardAlign.getAsAlign());
2612
40
2613
40
    CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
2614
40
        InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
2615
40
    // On Darwin platforms, use CXX_FAST_TLS calling convention.
2616
40
    if (CGM.getTarget().getTriple().isOSDarwin()) {
2617
11
      InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2618
11
      InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2619
11
    }
2620
40
  }
2621
24.2k
2622
24.2k
  // Create declarations for thread wrappers for all thread-local variables
2623
24.2k
  // with non-discardable definitions in this translation unit.
2624
24.2k
  for (const VarDecl *VD : CXXThreadLocals) {
2625
268
    if (VD->hasDefinition() &&
2626
268
        
!isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))218
) {
2627
108
      llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
2628
108
      getOrCreateThreadLocalWrapper(VD, GV);
2629
108
    }
2630
268
  }
2631
24.2k
2632
24.2k
  // Emit all referenced thread wrappers.
2633
24.2k
  for (auto VDAndWrapper : ThreadWrappers) {
2634
203
    const VarDecl *VD = VDAndWrapper.first;
2635
203
    llvm::GlobalVariable *Var =
2636
203
        cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
2637
203
    llvm::Function *Wrapper = VDAndWrapper.second;
2638
203
2639
203
    // Some targets require that all access to thread local variables go through
2640
203
    // the thread wrapper.  This means that we cannot attempt to create a thread
2641
203
    // wrapper or a thread helper.
2642
203
    if (!VD->hasDefinition()) {
2643
49
      if (isThreadWrapperReplaceable(VD, CGM)) {
2644
11
        Wrapper->setLinkage(llvm::Function::ExternalLinkage);
2645
11
        continue;
2646
11
      }
2647
38
2648
38
      // If this isn't a TU in which this variable is defined, the thread
2649
38
      // wrapper is discardable.
2650
38
      if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
2651
38
        Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
2652
38
    }
2653
203
2654
203
    CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2655
192
2656
192
    // Mangle the name for the thread_local initialization function.
2657
192
    SmallString<256> InitFnName;
2658
192
    {
2659
192
      llvm::raw_svector_ostream Out(InitFnName);
2660
192
      getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2661
192
    }
2662
192
2663
192
    llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2664
192
2665
192
    // If we have a definition for the variable, emit the initialization
2666
192
    // function as an alias to the global Init function (if any). Otherwise,
2667
192
    // produce a declaration of the initialization function.
2668
192
    llvm::GlobalValue *Init = nullptr;
2669
192
    bool InitIsInitFunc = false;
2670
192
    bool HasConstantInitialization = false;
2671
192
    if (!usesThreadWrapperFunction(VD)) {
2672
53
      HasConstantInitialization = true;
2673
139
    } else if (VD->hasDefinition()) {
2674
101
      InitIsInitFunc = true;
2675
101
      llvm::Function *InitFuncToUse = InitFunc;
2676
101
      if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2677
37
        InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2678
101
      if (InitFuncToUse)
2679
99
        Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2680
99
                                         InitFuncToUse);
2681
101
    } else {
2682
38
      // Emit a weak global function referring to the initialization function.
2683
38
      // This function will not exist if the TU defining the thread_local
2684
38
      // variable in question does not need any dynamic initialization for
2685
38
      // its thread_local variables.
2686
38
      Init = llvm::Function::Create(InitFnTy,
2687
38
                                    llvm::GlobalVariable::ExternalWeakLinkage,
2688
38
                                    InitFnName.str(), &CGM.getModule());
2689
38
      const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2690
38
      CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
2691
38
                                    cast<llvm::Function>(Init));
2692
38
    }
2693
192
2694
192
    if (Init) {
2695
137
      Init->setVisibility(Var->getVisibility());
2696
137
      // Don't mark an extern_weak function DSO local on windows.
2697
137
      if (!CGM.getTriple().isOSWindows() || 
!Init->hasExternalWeakLinkage()16
)
2698
135
        Init->setDSOLocal(Var->isDSOLocal());
2699
137
    }
2700
192
2701
192
    llvm::LLVMContext &Context = CGM.getModule().getContext();
2702
192
    llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2703
192
    CGBuilderTy Builder(CGM, Entry);
2704
192
    if (HasConstantInitialization) {
2705
53
      // No dynamic initialization to invoke.
2706
139
    } else if (InitIsInitFunc) {
2707
101
      if (Init) {
2708
99
        llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
2709
99
        if (isThreadWrapperReplaceable(VD, CGM)) {
2710
25
          CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2711
25
          llvm::Function *Fn =
2712
25
              cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2713
25
          Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2714
25
        }
2715
99
      }
2716
101
    } else {
2717
38
      // Don't know whether we have an init function. Call it if it exists.
2718
38
      llvm::Value *Have = Builder.CreateIsNotNull(Init);
2719
38
      llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2720
38
      llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2721
38
      Builder.CreateCondBr(Have, InitBB, ExitBB);
2722
38
2723
38
      Builder.SetInsertPoint(InitBB);
2724
38
      Builder.CreateCall(InitFnTy, Init);
2725
38
      Builder.CreateBr(ExitBB);
2726
38
2727
38
      Builder.SetInsertPoint(ExitBB);
2728
38
    }
2729
192
2730
192
    // For a reference, the result of the wrapper function is a pointer to
2731
192
    // the referenced object.
2732
192
    llvm::Value *Val = Var;
2733
192
    if (VD->getType()->isReferenceType()) {
2734
2
      CharUnits Align = CGM.getContext().getDeclAlign(VD);
2735
2
      Val = Builder.CreateAlignedLoad(Val, Align);
2736
2
    }
2737
192
    if (Val->getType() != Wrapper->getReturnType())
2738
0
      Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2739
0
          Val, Wrapper->getReturnType(), "");
2740
192
    Builder.CreateRet(Val);
2741
192
  }
2742
24.2k
}
2743
2744
LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2745
                                                   const VarDecl *VD,
2746
124
                                                   QualType LValType) {
2747
124
  llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
2748
124
  llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
2749
124
2750
124
  llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
2751
124
  CallVal->setCallingConv(Wrapper->getCallingConv());
2752
124
2753
124
  LValue LV;
2754
124
  if (VD->getType()->isReferenceType())
2755
2
    LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
2756
122
  else
2757
122
    LV = CGF.MakeAddrLValue(CallVal, LValType,
2758
122
                            CGF.getContext().getDeclAlign(VD));
2759
124
  // FIXME: need setObjCGCLValueClass?
2760
124
  return LV;
2761
124
}
2762
2763
/// Return whether the given global decl needs a VTT parameter, which it does
2764
/// if it's a base constructor or destructor with virtual bases.
2765
132k
bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2766
132k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2767
132k
2768
132k
  // We don't have any virtual bases, just return early.
2769
132k
  if (!MD->getParent()->getNumVBases())
2770
129k
    return false;
2771
2.93k
2772
2.93k
  // Check if we have a base constructor.
2773
2.93k
  if (isa<CXXConstructorDecl>(MD) && 
GD.getCtorType() == Ctor_Base1.96k
)
2774
942
    return true;
2775
1.99k
2776
1.99k
  // Check if we have a base destructor.
2777
1.99k
  if (isa<CXXDestructorDecl>(MD) && 
GD.getDtorType() == Dtor_Base964
)
2778
376
    return true;
2779
1.61k
2780
1.61k
  return false;
2781
1.61k
}
2782
2783
namespace {
2784
class ItaniumRTTIBuilder {
2785
  CodeGenModule &CGM;  // Per-module state.
2786
  llvm::LLVMContext &VMContext;
2787
  const ItaniumCXXABI &CXXABI;  // Per-module state.
2788
2789
  /// Fields - The fields of the RTTI descriptor currently being built.
2790
  SmallVector<llvm::Constant *, 16> Fields;
2791
2792
  /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2793
  llvm::GlobalVariable *
2794
  GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2795
2796
  /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2797
  /// descriptor of the given type.
2798
  llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2799
2800
  /// BuildVTablePointer - Build the vtable pointer for the given type.
2801
  void BuildVTablePointer(const Type *Ty);
2802
2803
  /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2804
  /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2805
  void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2806
2807
  /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2808
  /// classes with bases that do not satisfy the abi::__si_class_type_info
2809
  /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2810
  void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2811
2812
  /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2813
  /// for pointer types.
2814
  void BuildPointerTypeInfo(QualType PointeeTy);
2815
2816
  /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2817
  /// type_info for an object type.
2818
  void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2819
2820
  /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2821
  /// struct, used for member pointer types.
2822
  void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2823
2824
public:
2825
  ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2826
4.67k
      : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2827
2828
  // Pointer type info flags.
2829
  enum {
2830
    /// PTI_Const - Type has const qualifier.
2831
    PTI_Const = 0x1,
2832
2833
    /// PTI_Volatile - Type has volatile qualifier.
2834
    PTI_Volatile = 0x2,
2835
2836
    /// PTI_Restrict - Type has restrict qualifier.
2837
    PTI_Restrict = 0x4,
2838
2839
    /// PTI_Incomplete - Type is incomplete.
2840
    PTI_Incomplete = 0x8,
2841
2842
    /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2843
    /// (in pointer to member).
2844
    PTI_ContainingClassIncomplete = 0x10,
2845
2846
    /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2847
    //PTI_TransactionSafe = 0x20,
2848
2849
    /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2850
    PTI_Noexcept = 0x40,
2851
  };
2852
2853
  // VMI type info flags.
2854
  enum {
2855
    /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2856
    VMI_NonDiamondRepeat = 0x1,
2857
2858
    /// VMI_DiamondShaped - Class is diamond shaped.
2859
    VMI_DiamondShaped = 0x2
2860
  };
2861
2862
  // Base class type info flags.
2863
  enum {
2864
    /// BCTI_Virtual - Base class is virtual.
2865
    BCTI_Virtual = 0x1,
2866
2867
    /// BCTI_Public - Base class is public.
2868
    BCTI_Public = 0x2
2869
  };
2870
2871
  /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
2872
  /// link to an existing RTTI descriptor if one already exists.
2873
  llvm::Constant *BuildTypeInfo(QualType Ty);
2874
2875
  /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2876
  llvm::Constant *BuildTypeInfo(
2877
      QualType Ty,
2878
      llvm::GlobalVariable::LinkageTypes Linkage,
2879
      llvm::GlobalValue::VisibilityTypes Visibility,
2880
      llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
2881
};
2882
}
2883
2884
llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2885
2.32k
    QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2886
2.32k
  SmallString<256> Name;
2887
2.32k
  llvm::raw_svector_ostream Out(Name);
2888
2.32k
  CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2889
2.32k
2890
2.32k
  // We know that the mangled name of the type starts at index 4 of the
2891
2.32k
  // mangled name of the typename, so we can just index into it in order to
2892
2.32k
  // get the mangled name of the type.
2893
2.32k
  llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2894
2.32k
                                                            Name.substr(4));
2895
2.32k
  auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
2896
2.32k
2897
2.32k
  llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2898
2.32k
      Name, Init->getType(), Linkage, Align.getQuantity());
2899
2.32k
2900
2.32k
  GV->setInitializer(Init);
2901
2.32k
2902
2.32k
  return GV;
2903
2.32k
}
2904
2905
llvm::Constant *
2906
1.05k
ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2907
1.05k
  // Mangle the RTTI name.
2908
1.05k
  SmallString<256> Name;
2909
1.05k
  llvm::raw_svector_ostream Out(Name);
2910
1.05k
  CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2911
1.05k
2912
1.05k
  // Look for an existing global.
2913
1.05k
  llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2914
1.05k
2915
1.05k
  if (!GV) {
2916
759
    // Create a new global variable.
2917
759
    // Note for the future: If we would ever like to do deferred emission of
2918
759
    // RTTI, check if emitting vtables opportunistically need any adjustment.
2919
759
2920
759
    GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2921
759
                                  /*isConstant=*/true,
2922
759
                                  llvm::GlobalValue::ExternalLinkage, nullptr,
2923
759
                                  Name);
2924
759
    const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2925
759
    CGM.setGVProperties(GV, RD);
2926
759
  }
2927
1.05k
2928
1.05k
  return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2929
1.05k
}
2930
2931
/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2932
/// info for that type is defined in the standard library.
2933
247
static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2934
247
  // Itanium C++ ABI 2.9.2:
2935
247
  //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
2936
247
  //   the run-time support library. Specifically, the run-time support
2937
247
  //   library should contain type_info objects for the types X, X* and
2938
247
  //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2939
247
  //   unsigned char, signed char, short, unsigned short, int, unsigned int,
2940
247
  //   long, unsigned long, long long, unsigned long long, float, double,
2941
247
  //   long double, char16_t, char32_t, and the IEEE 754r decimal and
2942
247
  //   half-precision floating point types.
2943
247
  //
2944
247
  // GCC also emits RTTI for __int128.
2945
247
  // FIXME: We do not emit RTTI information for decimal types here.
2946
247
2947
247
  // Types added here must also be added to EmitFundamentalRTTIDescriptors.
2948
247
  switch (Ty->getKind()) {
2949
223
    case BuiltinType::Void:
2950
223
    case BuiltinType::NullPtr:
2951
223
    case BuiltinType::Bool:
2952
223
    case BuiltinType::WChar_S:
2953
223
    case BuiltinType::WChar_U:
2954
223
    case BuiltinType::Char_U:
2955
223
    case BuiltinType::Char_S:
2956
223
    case BuiltinType::UChar:
2957
223
    case BuiltinType::SChar:
2958
223
    case BuiltinType::Short:
2959
223
    case BuiltinType::UShort:
2960
223
    case BuiltinType::Int:
2961
223
    case BuiltinType::UInt:
2962
223
    case BuiltinType::Long:
2963
223
    case BuiltinType::ULong:
2964
223
    case BuiltinType::LongLong:
2965
223
    case BuiltinType::ULongLong:
2966
223
    case BuiltinType::Half:
2967
223
    case BuiltinType::Float:
2968
223
    case BuiltinType::Double:
2969
223
    case BuiltinType::LongDouble:
2970
223
    case BuiltinType::Float16:
2971
223
    case BuiltinType::Float128:
2972
223
    case BuiltinType::Char8:
2973
223
    case BuiltinType::Char16:
2974
223
    case BuiltinType::Char32:
2975
223
    case BuiltinType::Int128:
2976
223
    case BuiltinType::UInt128:
2977
223
      return true;
2978
223
2979
223
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2980
864
    case BuiltinType::Id:
2981
864
#include 
"clang/Basic/OpenCLImageTypes.def"223
2982
864
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2983
864
    
case BuiltinType::Id:288
2984
864
#include 
"clang/Basic/OpenCLExtensionTypes.def"24
2985
288
    case BuiltinType::OCLSampler:
2986
24
    case BuiltinType::OCLEvent:
2987
24
    case BuiltinType::OCLClkEvent:
2988
24
    case BuiltinType::OCLQueue:
2989
24
    case BuiltinType::OCLReserveID:
2990
24
#define SVE_TYPE(Name, Id, SingletonId) \
2991
288
    case BuiltinType::Id:
2992
288
#include 
"clang/Basic/AArch64SVEACLETypes.def"24
2993
288
    case BuiltinType::ShortAccum:
2994
24
    case BuiltinType::Accum:
2995
24
    case BuiltinType::LongAccum:
2996
24
    case BuiltinType::UShortAccum:
2997
24
    case BuiltinType::UAccum:
2998
24
    case BuiltinType::ULongAccum:
2999
24
    case BuiltinType::ShortFract:
3000
24
    case BuiltinType::Fract:
3001
24
    case BuiltinType::LongFract:
3002
24
    case BuiltinType::UShortFract:
3003
24
    case BuiltinType::UFract:
3004
24
    case BuiltinType::ULongFract:
3005
24
    case BuiltinType::SatShortAccum:
3006
24
    case BuiltinType::SatAccum:
3007
24
    case BuiltinType::SatLongAccum:
3008
24
    case BuiltinType::SatUShortAccum:
3009
24
    case BuiltinType::SatUAccum:
3010
24
    case BuiltinType::SatULongAccum:
3011
24
    case BuiltinType::SatShortFract:
3012
24
    case BuiltinType::SatFract:
3013
24
    case BuiltinType::SatLongFract:
3014
24
    case BuiltinType::SatUShortFract:
3015
24
    case BuiltinType::SatUFract:
3016
24
    case BuiltinType::SatULongFract:
3017
24
      return false;
3018
24
3019
24
    case BuiltinType::Dependent:
3020
0
#define BUILTIN_TYPE(Id, SingletonId)
3021
0
#define PLACEHOLDER_TYPE(Id, SingletonId) \
3022
0
    case BuiltinType::Id:
3023
0
#include "clang/AST/BuiltinTypes.def"
3024
0
      llvm_unreachable("asking for RRTI for a placeholder type!");
3025
0
3026
0
    case BuiltinType::ObjCId:
3027
0
    case BuiltinType::ObjCClass:
3028
0
    case BuiltinType::ObjCSel:
3029
0
      llvm_unreachable("FIXME: Objective-C types are unsupported!");
3030
0
  }
3031
0
3032
0
  llvm_unreachable("Invalid BuiltinType Kind!");
3033
0
}
3034
3035
60
static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
3036
60
  QualType PointeeTy = PointerTy->getPointeeType();
3037
60
  const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
3038
60
  if (!BuiltinTy)
3039
48
    return false;
3040
12
3041
12
  // Check the qualifiers.
3042
12
  Qualifiers Quals = PointeeTy.getQualifiers();
3043
12
  Quals.removeConst();
3044
12
3045
12
  if (!Quals.empty())
3046
0
    return false;
3047
12
3048
12
  return TypeInfoIsInStandardLibrary(BuiltinTy);
3049
12
}
3050
3051
/// IsStandardLibraryRTTIDescriptor - Returns whether the type
3052
/// information for the given type exists in the standard library.
3053
3.07k
static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
3054
3.07k
  // Type info for builtin types is defined in the standard library.
3055
3.07k
  if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
3056
235
    return TypeInfoIsInStandardLibrary(BuiltinTy);
3057
2.83k
3058
2.83k
  // Type info for some pointer types to builtin types is defined in the
3059
2.83k
  // standard library.
3060
2.83k
  if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3061
60
    return TypeInfoIsInStandardLibrary(PointerTy);
3062
2.77k
3063
2.77k
  return false;
3064
2.77k
}
3065
3066
/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3067
/// the given type exists somewhere else, and that we should not emit the type
3068
/// information in this translation unit.  Assumes that it is not a
3069
/// standard-library type.
3070
static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
3071
2.84k
                                            QualType Ty) {
3072
2.84k
  ASTContext &Context = CGM.getContext();
3073
2.84k
3074
2.84k
  // If RTTI is disabled, assume it might be disabled in the
3075
2.84k
  // translation unit that defines any potential key function, too.
3076
2.84k
  if (!Context.getLangOpts().RTTI) 
return false7
;
3077
2.84k
3078
2.84k
  if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3079
2.63k
    const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
3080
2.63k
    if (!RD->hasDefinition())
3081
3
      return false;
3082
2.63k
3083
2.63k
    if (!RD->isDynamicClass())
3084
274
      return false;
3085
2.35k
3086
2.35k
    // FIXME: this may need to be reconsidered if the key function
3087
2.35k
    // changes.
3088
2.35k
    // N.B. We must always emit the RTTI data ourselves if there exists a key
3089
2.35k
    // function.
3090
2.35k
    bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
3091
2.35k
3092
2.35k
    // Don't import the RTTI but emit it locally.
3093
2.35k
    if (CGM.getTriple().isWindowsGNUEnvironment())
3094
88
      return false;
3095
2.27k
3096
2.27k
    if (CGM.getVTables().isVTableExternal(RD))
3097
827
      return IsDLLImport && 
!CGM.getTriple().isWindowsItaniumEnvironment()2
3098
827
                 ? 
false0
3099
827
                 : true;
3100
1.44k
3101
1.44k
    if (IsDLLImport)
3102
0
      return true;
3103
1.64k
  }
3104
1.64k
3105
1.64k
  return false;
3106
1.64k
}
3107
3108
/// IsIncompleteClassType - Returns whether the given record type is incomplete.
3109
1.93k
static bool IsIncompleteClassType(const RecordType *RecordTy) {
3110
1.93k
  return !RecordTy->getDecl()->isCompleteDefinition();
3111
1.93k
}
3112
3113
/// ContainsIncompleteClassType - Returns whether the given type contains an
3114
/// incomplete class type. This is true if
3115
///
3116
///   * The given type is an incomplete class type.
3117
///   * The given type is a pointer type whose pointee type contains an
3118
///     incomplete class type.
3119
///   * The given type is a member pointer type whose class is an incomplete
3120
///     class type.
3121
///   * The given type is a member pointer type whoise pointee type contains an
3122
///     incomplete class type.
3123
/// is an indirect or direct pointer to an incomplete class type.
3124
2.37k
static bool ContainsIncompleteClassType(QualType Ty) {
3125
2.37k
  if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3126
1.88k
    if (IsIncompleteClassType(RecordTy))
3127
32
      return true;
3128
2.34k
  }
3129
2.34k
3130
2.34k
  if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3131
68
    return ContainsIncompleteClassType(PointerTy->getPointeeType());
3132
2.27k
3133
2.27k
  if (const MemberPointerType *MemberPointerTy =
3134
25
      dyn_cast<MemberPointerType>(Ty)) {
3135
25
    // Check if the class type is incomplete.
3136
25
    const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
3137
25
    if (IsIncompleteClassType(ClassType))
3138
12
      return true;
3139
13
3140
13
    return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3141
13
  }
3142
2.25k
3143
2.25k
  return false;
3144
2.25k
}
3145
3146
// CanUseSingleInheritance - Return whether the given record decl has a "single,
3147
// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3148
// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3149
1.86k
static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3150
1.86k
  // Check the number of bases.
3151
1.86k
  if (RD->getNumBases() != 1)
3152
398
    return false;
3153
1.46k
3154
1.46k
  // Get the base.
3155
1.46k
  CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3156
1.46k
3157
1.46k
  // Check that the base is not virtual.
3158
1.46k
  if (Base->isVirtual())
3159
378
    return false;
3160
1.08k
3161
1.08k
  // Check that the base is public.
3162
1.08k
  if (Base->getAccessSpecifier() != AS_public)
3163
50
    return false;
3164
1.03k
3165
1.03k
  // Check that the class is dynamic iff the base is.
3166
1.03k
  auto *BaseDecl =
3167
1.03k
      cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
3168
1.03k
  if (!BaseDecl->isEmpty() &&
3169
1.03k
      
BaseDecl->isDynamicClass() != RD->isDynamicClass()1.01k
)
3170
4
    return false;
3171
1.03k
3172
1.03k
  return true;
3173
1.03k
}
3174
3175
2.32k
void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
3176
2.32k
  // abi::__class_type_info.
3177
2.32k
  static const char * const ClassTypeInfo =
3178
2.32k
    "_ZTVN10__cxxabiv117__class_type_infoE";
3179
2.32k
  // abi::__si_class_type_info.
3180
2.32k
  static const char * const SIClassTypeInfo =
3181
2.32k
    "_ZTVN10__cxxabiv120__si_class_type_infoE";
3182
2.32k
  // abi::__vmi_class_type_info.
3183
2.32k
  static const char * const VMIClassTypeInfo =
3184
2.32k
    "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3185
2.32k
3186
2.32k
  const char *VTableName = nullptr;
3187
2.32k
3188
2.32k
  switch (Ty->getTypeClass()) {
3189
0
#define TYPE(Class, Base)
3190
0
#define ABSTRACT_TYPE(Class, Base)
3191
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3192
0
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3193
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3194
0
#include "clang/AST/TypeNodes.inc"
3195
0
    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3196
0
3197
0
  case Type::LValueReference:
3198
0
  case Type::RValueReference:
3199
0
    llvm_unreachable("References shouldn't get here");
3200
0
3201
0
  case Type::Auto:
3202
0
  case Type::DeducedTemplateSpecialization:
3203
0
    llvm_unreachable("Undeduced type shouldn't get here");
3204
0
3205
0
  case Type::Pipe:
3206
0
    llvm_unreachable("Pipe types shouldn't get here");
3207
0
3208
127
  case Type::Builtin:
3209
127
  // GCC treats vector and complex types as fundamental types.
3210
127
  case Type::Vector:
3211
127
  case Type::ExtVector:
3212
127
  case Type::Complex:
3213
127
  case Type::Atomic:
3214
127
  // FIXME: GCC treats block pointers as fundamental types?!
3215
127
  case Type::BlockPointer:
3216
127
    // abi::__fundamental_type_info.
3217
127
    VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3218
127
    break;
3219
127
3220
127
  case Type::ConstantArray:
3221
5
  case Type::IncompleteArray:
3222
5
  case Type::VariableArray:
3223
5
    // abi::__array_type_info.
3224
5
    VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3225
5
    break;
3226
5
3227
87
  case Type::FunctionNoProto:
3228
87
  case Type::FunctionProto:
3229
87
    // abi::__function_type_info.
3230
87
    VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
3231
87
    break;
3232
87
3233
87
  case Type::Enum:
3234
2
    // abi::__enum_type_info.
3235
2
    VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3236
2
    break;
3237
87
3238
1.81k
  case Type::Record: {
3239
1.81k
    const CXXRecordDecl *RD =
3240
1.81k
      cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3241
1.81k
3242
1.81k
    if (!RD->hasDefinition() || 
!RD->getNumBases()1.81k
) {
3243
883
      VTableName = ClassTypeInfo;
3244
930
    } else if (CanUseSingleInheritance(RD)) {
3245
515
      VTableName = SIClassTypeInfo;
3246
515
    } else {
3247
415
      VTableName = VMIClassTypeInfo;
3248
415
    }
3249
1.81k
3250
1.81k
    break;
3251
87
  }
3252
87
3253
87
  case Type::ObjCObject:
3254
7
    // Ignore protocol qualifiers.
3255
7
    Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
3256
7
3257
7
    // Handle id and Class.
3258
7
    if (isa<BuiltinType>(Ty)) {
3259
6
      VTableName = ClassTypeInfo;
3260
6
      break;
3261
6
    }
3262
1
3263
1
    assert(isa<ObjCInterfaceType>(Ty));
3264
1
    LLVM_FALLTHROUGH;
3265
1
3266
3
  case Type::ObjCInterface:
3267
3
    if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3268
1
      VTableName = SIClassTypeInfo;
3269
2
    } else {
3270
2
      VTableName = ClassTypeInfo;
3271
2
    }
3272
3
    break;
3273
1
3274
256
  case Type::ObjCObjectPointer:
3275
256
  case Type::Pointer:
3276
256
    // abi::__pointer_type_info.
3277
256
    VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3278
256
    break;
3279
256
3280
256
  case Type::MemberPointer:
3281
21
    // abi::__pointer_to_member_type_info.
3282
21
    VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3283
21
    break;
3284
2.32k
  }
3285
2.32k
3286
2.32k
  llvm::Constant *VTable =
3287
2.32k
    CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
3288
2.32k
  CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
3289
2.32k
3290
2.32k
  llvm::Type *PtrDiffTy =
3291
2.32k
    CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3292
2.32k
3293
2.32k
  // The vtable address point is 2.
3294
2.32k
  llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
3295
2.32k
  VTable =
3296
2.32k
      llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
3297
2.32k
  VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3298
2.32k
3299
2.32k
  Fields.push_back(VTable);
3300
2.32k
}
3301
3302
/// Return the linkage that the type info and type info name constants
3303
/// should have for the given type.
3304
static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3305
2.02k
                                                             QualType Ty) {
3306
2.02k
  // Itanium C++ ABI 2.9.5p7:
3307
2.02k
  //   In addition, it and all of the intermediate abi::__pointer_type_info
3308
2.02k
  //   structs in the chain down to the abi::__class_type_info for the
3309
2.02k
  //   incomplete class type must be prevented from resolving to the
3310
2.02k
  //   corresponding type_info structs for the complete class type, possibly
3311
2.02k
  //   by making them local static objects. Finally, a dummy class RTTI is
3312
2.02k
  //   generated for the incomplete type that will not resolve to the final
3313
2.02k
  //   complete class RTTI (because the latter need not exist), possibly by
3314
2.02k
  //   making it a local static object.
3315
2.02k
  if (ContainsIncompleteClassType(Ty))
3316
25
    return llvm::GlobalValue::InternalLinkage;
3317
1.99k
3318
1.99k
  switch (Ty->getLinkage()) {
3319
136
  case NoLinkage:
3320
136
  case InternalLinkage:
3321
136
  case UniqueExternalLinkage:
3322
136
    return llvm::GlobalValue::InternalLinkage;
3323
136
3324
1.85k
  case VisibleNoLinkage:
3325
1.85k
  case ModuleInternalLinkage:
3326
1.85k
  case ModuleLinkage:
3327
1.85k
  case ExternalLinkage:
3328
1.85k
    // RTTI is not enabled, which means that this type info struct is going
3329
1.85k
    // to be used for exception handling. Give it linkonce_odr linkage.
3330
1.85k
    if (!CGM.getLangOpts().RTTI)
3331
7
      return llvm::GlobalValue::LinkOnceODRLinkage;
3332
1.85k
3333
1.85k
    if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3334
1.68k
      const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3335
1.68k
      if (RD->hasAttr<WeakAttr>())
3336
5
        return llvm::GlobalValue::WeakODRLinkage;
3337
1.67k
      if (CGM.getTriple().isWindowsItaniumEnvironment())
3338
9
        if (RD->hasAttr<DLLImportAttr>() &&
3339
9
            
ShouldUseExternalRTTIDescriptor(CGM, Ty)1
)
3340
0
          return llvm::GlobalValue::ExternalLinkage;
3341
1.67k
      // MinGW always uses LinkOnceODRLinkage for type info.
3342
1.67k
      if (RD->isDynamicClass() &&
3343
1.67k
          !CGM.getContext()
3344
1.43k
               .getTargetInfo()
3345
1.43k
               .getTriple()
3346
1.43k
               .isWindowsGNUEnvironment())
3347
1.34k
        return CGM.getVTableLinkage(RD);
3348
502
    }
3349
502
3350
502
    return llvm::GlobalValue::LinkOnceODRLinkage;
3351
0
  }
3352
0
3353
0
  llvm_unreachable("Invalid linkage!");
3354
0
}
3355
3356
4.37k
llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
3357
4.37k
  // We want to operate on the canonical type.
3358
4.37k
  Ty = Ty.getCanonicalType();
3359
4.37k
3360
4.37k
  // Check if we've already emitted an RTTI descriptor for this type.
3361
4.37k
  SmallString<256> Name;
3362
4.37k
  llvm::raw_svector_ostream Out(Name);
3363
4.37k
  CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
3364
4.37k
3365
4.37k
  llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3366
4.37k
  if (OldGV && 
!OldGV->isDeclaration()1.61k
) {
3367
1.30k
    assert(!OldGV->hasAvailableExternallyLinkage() &&
3368
1.30k
           "available_externally typeinfos not yet implemented");
3369
1.30k
3370
1.30k
    return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3371
1.30k
  }
3372
3.07k
3373
3.07k
  // Check if there is already an external RTTI descriptor for this type.
3374
3.07k
  if (IsStandardLibraryRTTIDescriptor(Ty) ||
3375
3.07k
      
ShouldUseExternalRTTIDescriptor(CGM, Ty)2.84k
)
3376
1.05k
    return GetAddrOfExternalRTTIDescriptor(Ty);
3377
2.02k
3378
2.02k
  // Emit the standard library with external linkage.
3379
2.02k
  llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
3380
2.02k
3381
2.02k
  // Give the type_info object and name the formal visibility of the
3382
2.02k
  // type itself.
3383
2.02k
  llvm::GlobalValue::VisibilityTypes llvmVisibility;
3384
2.02k
  if (llvm::GlobalValue::isLocalLinkage(Linkage))
3385
163
    // If the linkage is local, only default visibility makes sense.
3386
163
    llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3387
1.85k
  else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
3388
1.85k
           ItaniumCXXABI::RUK_NonUniqueHidden)
3389
6
    llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3390
1.85k
  else
3391
1.85k
    llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3392
2.02k
3393
2.02k
  llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3394
2.02k
      llvm::GlobalValue::DefaultStorageClass;
3395
2.02k
  if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3396
10
    auto RD = Ty->getAsCXXRecordDecl();
3397
10
    if (RD && RD->hasAttr<DLLExportAttr>())
3398
4
      DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
3399
10
  }
3400
2.02k
3401
2.02k
  return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
3402
2.02k
}
3403
3404
llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
3405
      QualType Ty,
3406
      llvm::GlobalVariable::LinkageTypes Linkage,
3407
      llvm::GlobalValue::VisibilityTypes Visibility,
3408
2.32k
      llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
3409
2.32k
  // Add the vtable pointer.
3410
2.32k
  BuildVTablePointer(cast<Type>(Ty));
3411
2.32k
3412
2.32k
  // And the name.
3413
2.32k
  llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3414
2.32k
  llvm::Constant *TypeNameField;
3415
2.32k
3416
2.32k
  // If we're supposed to demote the visibility, be sure to set a flag
3417
2.32k
  // to use a string comparison for type_info comparisons.
3418
2.32k
  ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3419
2.32k
      CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3420
2.32k
  if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3421
8
    // The flag is the sign bit, which on ARM64 is defined to be clear
3422
8
    // for global pointers.  This is very ARM64-specific.
3423
8
    TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3424
8
    llvm::Constant *flag =
3425
8
        llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3426
8
    TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3427
8
    TypeNameField =
3428
8
        llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3429
2.31k
  } else {
3430
2.31k
    TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3431
2.31k
  }
3432
2.32k
  Fields.push_back(TypeNameField);
3433
2.32k
3434
2.32k
  switch (Ty->getTypeClass()) {
3435
0
#define TYPE(Class, Base)
3436
0
#define ABSTRACT_TYPE(Class, Base)
3437
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3438
0
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3439
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3440
0
#include "clang/AST/TypeNodes.inc"
3441
0
    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3442
0
3443
0
  // GCC treats vector types as fundamental types.
3444
127
  case Type::Builtin:
3445
127
  case Type::Vector:
3446
127
  case Type::ExtVector:
3447
127
  case Type::Complex:
3448
127
  case Type::BlockPointer:
3449
127
    // Itanium C++ ABI 2.9.5p4:
3450
127
    // abi::__fundamental_type_info adds no data members to std::type_info.
3451
127
    break;
3452
127
3453
127
  case Type::LValueReference:
3454
0
  case Type::RValueReference:
3455
0
    llvm_unreachable("References shouldn't get here");
3456
0
3457
0
  case Type::Auto:
3458
0
  case Type::DeducedTemplateSpecialization:
3459
0
    llvm_unreachable("Undeduced type shouldn't get here");
3460
0
3461
0
  case Type::Pipe:
3462
0
    llvm_unreachable("Pipe type shouldn't get here");
3463
0
3464
5
  case Type::ConstantArray:
3465
5
  case Type::IncompleteArray:
3466
5
  case Type::VariableArray:
3467
5
    // Itanium C++ ABI 2.9.5p5:
3468
5
    // abi::__array_type_info adds no data members to std::type_info.
3469
5
    break;
3470
5
3471
87
  case Type::FunctionNoProto:
3472
87
  case Type::FunctionProto:
3473
87
    // Itanium C++ ABI 2.9.5p5:
3474
87
    // abi::__function_type_info adds no data members to std::type_info.
3475
87
    break;
3476
87
3477
87
  case Type::Enum:
3478
2
    // Itanium C++ ABI 2.9.5p5:
3479
2
    // abi::__enum_type_info adds no data members to std::type_info.
3480
2
    break;
3481
87
3482
1.81k
  case Type::Record: {
3483
1.81k
    const CXXRecordDecl *RD =
3484
1.81k
      cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3485
1.81k
    if (!RD->hasDefinition() || 
!RD->getNumBases()1.81k
) {
3486
883
      // We don't need to emit any fields.
3487
883
      break;
3488
883
    }
3489
930
3490
930
    if (CanUseSingleInheritance(RD))
3491
515
      BuildSIClassTypeInfo(RD);
3492
415
    else
3493
415
      BuildVMIClassTypeInfo(RD);
3494
930
3495
930
    break;
3496
930
  }
3497
930
3498
930
  case Type::ObjCObject:
3499
9
  case Type::ObjCInterface:
3500
9
    BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3501
9
    break;
3502
9
3503
9
  case Type::ObjCObjectPointer:
3504
8
    BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3505
8
    break;
3506
9
3507
248
  case Type::Pointer:
3508
248
    BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3509
248
    break;
3510
9
3511
21
  case Type::MemberPointer:
3512
21
    BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3513
21
    break;
3514
9
3515
9
  case Type::Atomic:
3516
0
    // No fields, at least for the moment.
3517
0
    break;
3518
2.32k
  }
3519
2.32k
3520
2.32k
  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3521
2.32k
3522
2.32k
  SmallString<256> Name;
3523
2.32k
  llvm::raw_svector_ostream Out(Name);
3524
2.32k
  CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
3525
2.32k
  llvm::Module &M = CGM.getModule();
3526
2.32k
  llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
3527
2.32k
  llvm::GlobalVariable *GV =
3528
2.32k
      new llvm::GlobalVariable(M, Init->getType(),
3529
2.32k
                               /*isConstant=*/true, Linkage, Init, Name);
3530
2.32k
3531
2.32k
  // If there's already an old global variable, replace it with the new one.
3532
2.32k
  if (OldGV) {
3533
20
    GV->takeName(OldGV);
3534
20
    llvm::Constant *NewPtr =
3535
20
      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3536
20
    OldGV->replaceAllUsesWith(NewPtr);
3537
20
    OldGV->eraseFromParent();
3538
20
  }
3539
2.32k
3540
2.32k
  if (CGM.supportsCOMDAT() && 
GV->isWeakForLinker()875
)
3541
560
    GV->setComdat(M.getOrInsertComdat(GV->getName()));
3542
2.32k
3543
2.32k
  CharUnits Align =
3544
2.32k
      CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
3545
2.32k
  GV->setAlignment(Align.getAsAlign());
3546
2.32k
3547
2.32k
  // The Itanium ABI specifies that type_info objects must be globally
3548
2.32k
  // unique, with one exception: if the type is an incomplete class
3549
2.32k
  // type or a (possibly indirect) pointer to one.  That exception
3550
2.32k
  // affects the general case of comparing type_info objects produced
3551
2.32k
  // by the typeid operator, which is why the comparison operators on
3552
2.32k
  // std::type_info generally use the type_info name pointers instead
3553
2.32k
  // of the object addresses.  However, the language's built-in uses
3554
2.32k
  // of RTTI generally require class types to be complete, even when
3555
2.32k
  // manipulating pointers to those class types.  This allows the
3556
2.32k
  // implementation of dynamic_cast to rely on address equality tests,
3557
2.32k
  // which is much faster.
3558
2.32k
3559
2.32k
  // All of this is to say that it's important that both the type_info
3560
2.32k
  // object and the type_info name be uniqued when weakly emitted.
3561
2.32k
3562
2.32k
  TypeName->setVisibility(Visibility);
3563
2.32k
  CGM.setDSOLocal(TypeName);
3564
2.32k
3565
2.32k
  GV->setVisibility(Visibility);
3566
2.32k
  CGM.setDSOLocal(GV);
3567
2.32k
3568
2.32k
  TypeName->setDLLStorageClass(DLLStorageClass);
3569
2.32k
  GV->setDLLStorageClass(DLLStorageClass);
3570
2.32k
3571
2.32k
  TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3572
2.32k
  GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3573
2.32k
3574
2.32k
  return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3575
2.32k
}
3576
3577
/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3578
/// for the given Objective-C object type.
3579
9
void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3580
9
  // Drop qualifiers.
3581
9
  const Type *T = OT->getBaseType().getTypePtr();
3582
9
  assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3583
9
3584
9
  // The builtin types are abi::__class_type_infos and don't require
3585
9
  // extra fields.
3586
9
  if (isa<BuiltinType>(T)) 
return6
;
3587
3
3588
3
  ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3589
3
  ObjCInterfaceDecl *Super = Class->getSuperClass();
3590
3
3591
3
  // Root classes are also __class_type_info.
3592
3
  if (!Super) 
return2
;
3593
1
3594
1
  QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3595
1
3596
1
  // Everything else is single inheritance.
3597
1
  llvm::Constant *BaseTypeInfo =
3598
1
      ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3599
1
  Fields.push_back(BaseTypeInfo);
3600
1
}
3601
3602
/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3603
/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3604
515
void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3605
515
  // Itanium C++ ABI 2.9.5p6b:
3606
515
  // It adds to abi::__class_type_info a single member pointing to the
3607
515
  // type_info structure for the base type,
3608
515
  llvm::Constant *BaseTypeInfo =
3609
515
    ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3610
515
  Fields.push_back(BaseTypeInfo);
3611
515
}
3612
3613
namespace {
3614
  /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3615
  /// a class hierarchy.
3616
  struct SeenBases {
3617
    llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3618
    llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3619
  };
3620
}
3621
3622
/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3623
/// abi::__vmi_class_type_info.
3624
///
3625
static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3626
1.53k
                                             SeenBases &Bases) {
3627
1.53k
3628
1.53k
  unsigned Flags = 0;
3629
1.53k
3630
1.53k
  auto *BaseDecl =
3631
1.53k
      cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
3632
1.53k
3633
1.53k
  if (Base->isVirtual()) {
3634
809
    // Mark the virtual base as seen.
3635
809
    if (!Bases.VirtualBases.insert(BaseDecl).second) {
3636
408
      // If this virtual base has been seen before, then the class is diamond
3637
408
      // shaped.
3638
408
      Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3639
408
    } else {
3640
401
      if (Bases.NonVirtualBases.count(BaseDecl))
3641
19
        Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3642
401
    }
3643
809
  } else {
3644
724
    // Mark the non-virtual base as seen.
3645
724
    if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
3646
248
      // If this non-virtual base has been seen before, then the class has non-
3647
248
      // diamond shaped repeated inheritance.
3648
248
      Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3649
476
    } else {
3650
476
      if (Bases.VirtualBases.count(BaseDecl))
3651
28
        Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3652
476
    }
3653
724
  }
3654
1.53k
3655
1.53k
  // Walk all bases.
3656
1.53k
  for (const auto &I : BaseDecl->bases())
3657
880
    Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3658
1.53k
3659
1.53k
  return Flags;
3660
1.53k
}
3661
3662
415
static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3663
415
  unsigned Flags = 0;
3664
415
  SeenBases Bases;
3665
415
3666
415
  // Walk all bases.
3667
415
  for (const auto &I : RD->bases())
3668
653
    Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3669
415
3670
415
  return Flags;
3671
415
}
3672
3673
/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3674
/// classes with bases that do not satisfy the abi::__si_class_type_info
3675
/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3676
415
void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3677
415
  llvm::Type *UnsignedIntLTy =
3678
415
    CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3679
415
3680
415
  // Itanium C++ ABI 2.9.5p6c:
3681
415
  //   __flags is a word with flags describing details about the class
3682
415
  //   structure, which may be referenced by using the __flags_masks
3683
415
  //   enumeration. These flags refer to both direct and indirect bases.
3684
415
  unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3685
415
  Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3686
415
3687
415
  // Itanium C++ ABI 2.9.5p6c:
3688
415
  //   __base_count is a word with the number of direct proper base class
3689
415
  //   descriptions that follow.
3690
415
  Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3691
415
3692
415
  if (!RD->getNumBases())
3693
0
    return;
3694
415
3695
415
  // Now add the base class descriptions.
3696
415
3697
415
  // Itanium C++ ABI 2.9.5p6c:
3698
415
  //   __base_info[] is an array of base class descriptions -- one for every
3699
415
  //   direct proper base. Each description is of the type:
3700
415
  //
3701
415
  //   struct abi::__base_class_type_info {
3702
415
  //   public:
3703
415
  //     const __class_type_info *__base_type;
3704
415
  //     long __offset_flags;
3705
415
  //
3706
415
  //     enum __offset_flags_masks {
3707
415
  //       __virtual_mask = 0x1,
3708
415
  //       __public_mask = 0x2,
3709
415
  //       __offset_shift = 8
3710
415
  //     };
3711
415
  //   };
3712
415
3713
415
  // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3714
415
  // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3715
415
  // LLP64 platforms.
3716
415
  // FIXME: Consider updating libc++abi to match, and extend this logic to all
3717
415
  // LLP64 platforms.
3718
415
  QualType OffsetFlagsTy = CGM.getContext().LongTy;
3719
415
  const TargetInfo &TI = CGM.getContext().getTargetInfo();
3720
415
  if (TI.getTriple().isOSCygMing() && 
TI.getPointerWidth(0) > TI.getLongWidth()12
)
3721
6
    OffsetFlagsTy = CGM.getContext().LongLongTy;
3722
415
  llvm::Type *OffsetFlagsLTy =
3723
415
      CGM.getTypes().ConvertType(OffsetFlagsTy);
3724
415
3725
653
  for (const auto &Base : RD->bases()) {
3726
653
    // The __base_type member points to the RTTI for the base type.
3727
653
    Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3728
653
3729
653
    auto *BaseDecl =
3730
653
        cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
3731
653
3732
653
    int64_t OffsetFlags = 0;
3733
653
3734
653
    // All but the lower 8 bits of __offset_flags are a signed offset.
3735
653
    // For a non-virtual base, this is the offset in the object of the base
3736
653
    // subobject. For a virtual base, this is the offset in the virtual table of
3737
653
    // the virtual base offset for the virtual base referenced (negative).
3738
653
    CharUnits Offset;
3739
653
    if (Base.isVirtual())
3740
287
      Offset =
3741
287
        CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3742
366
    else {
3743
366
      const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3744
366
      Offset = Layout.getBaseClassOffset(BaseDecl);
3745
366
    };
3746
653
3747
653
    OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3748
653
3749
653
    // The low-order byte of __offset_flags contains flags, as given by the
3750
653
    // masks from the enumeration __offset_flags_masks.
3751
653
    if (Base.isVirtual())
3752
287
      OffsetFlags |= BCTI_Virtual;
3753
653
    if (Base.getAccessSpecifier() == AS_public)
3754
596
      OffsetFlags |= BCTI_Public;
3755
653
3756
653
    Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
3757
653
  }
3758
415
}
3759
3760
/// Compute the flags for a __pbase_type_info, and remove the corresponding
3761
/// pieces from \p Type.
3762
277
static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3763
277
  unsigned Flags = 0;
3764
277
3765
277
  if (Type.isConstQualified())
3766
104
    Flags |= ItaniumRTTIBuilder::PTI_Const;
3767
277
  if (Type.isVolatileQualified())
3768
4
    Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3769
277
  if (Type.isRestrictQualified())
3770
0
    Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3771
277
  Type = Type.getUnqualifiedType();
3772
277
3773
277
  // Itanium C++ ABI 2.9.5p7:
3774
277
  //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
3775
277
  //   incomplete class type, the incomplete target type flag is set.
3776
277
  if (ContainsIncompleteClassType(Type))
3777
19
    Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3778
277
3779
277
  if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3780
19
    if (Proto->isNothrow()) {
3781
2
      Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3782
2
      Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
3783
2
    }
3784
19
  }
3785
277
3786
277
  return Flags;
3787
277
}
3788
3789
/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3790
/// used for pointer types.
3791
256
void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3792
256
  // Itanium C++ ABI 2.9.5p7:
3793
256
  //   __flags is a flag word describing the cv-qualification and other
3794
256
  //   attributes of the type pointed to
3795
256
  unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
3796
256
3797
256
  llvm::Type *UnsignedIntLTy =
3798
256
    CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3799
256
  Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3800
256
3801
256
  // Itanium C++ ABI 2.9.5p7:
3802
256
  //  __pointee is a pointer to the std::type_info derivation for the
3803
256
  //  unqualified type being pointed to.
3804
256
  llvm::Constant *PointeeTypeInfo =
3805
256
      ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
3806
256
  Fields.push_back(PointeeTypeInfo);
3807
256
}
3808
3809
/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3810
/// struct, used for member pointer types.
3811
void
3812
21
ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3813
21
  QualType PointeeTy = Ty->getPointeeType();
3814
21
3815
21
  // Itanium C++ ABI 2.9.5p7:
3816
21
  //   __flags is a flag word describing the cv-qualification and other
3817
21
  //   attributes of the type pointed to.
3818
21
  unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
3819
21
3820
21
  const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3821
21
  if (IsIncompleteClassType(ClassType))
3822
8
    Flags |= PTI_ContainingClassIncomplete;
3823
21
3824
21
  llvm::Type *UnsignedIntLTy =
3825
21
    CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3826
21
  Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3827
21
3828
21
  // Itanium C++ ABI 2.9.5p7:
3829
21
  //   __pointee is a pointer to the std::type_info derivation for the
3830
21
  //   unqualified type being pointed to.
3831
21
  llvm::Constant *PointeeTypeInfo =
3832
21
      ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
3833
21
  Fields.push_back(PointeeTypeInfo);
3834
21
3835
21
  // Itanium C++ ABI 2.9.5p9:
3836
21
  //   __context is a pointer to an abi::__class_type_info corresponding to the
3837
21
  //   class type containing the member pointed to
3838
21
  //   (e.g., the "A" in "int A::*").
3839
21
  Fields.push_back(
3840
21
      ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3841
21
}
3842
3843
2.90k
llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
3844
2.90k
  return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3845
2.90k
}
3846
3847
4
void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
3848
4
  // Types added here must also be added to TypeInfoIsInStandardLibrary.
3849
4
  QualType FundamentalTypes[] = {
3850
4
      getContext().VoidTy,             getContext().NullPtrTy,
3851
4
      getContext().BoolTy,             getContext().WCharTy,
3852
4
      getContext().CharTy,             getContext().UnsignedCharTy,
3853
4
      getContext().SignedCharTy,       getContext().ShortTy,
3854
4
      getContext().UnsignedShortTy,    getContext().IntTy,
3855
4
      getContext().UnsignedIntTy,      getContext().LongTy,
3856
4
      getContext().UnsignedLongTy,     getContext().LongLongTy,
3857
4
      getContext().UnsignedLongLongTy, getContext().Int128Ty,
3858
4
      getContext().UnsignedInt128Ty,   getContext().HalfTy,
3859
4
      getContext().FloatTy,            getContext().DoubleTy,
3860
4
      getContext().LongDoubleTy,       getContext().Float128Ty,
3861
4
      getContext().Char8Ty,            getContext().Char16Ty,
3862
4
      getContext().Char32Ty
3863
4
  };
3864
4
  llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3865
4
      RD->hasAttr<DLLExportAttr>()
3866
4
      ? 
llvm::GlobalValue::DLLExportStorageClass2
3867
4
      : 
llvm::GlobalValue::DefaultStorageClass2
;
3868
4
  llvm::GlobalValue::VisibilityTypes Visibility =
3869
4
      CodeGenModule::GetLLVMVisibility(RD->getVisibility());
3870
100
  for (const QualType &FundamentalType : FundamentalTypes) {
3871
100
    QualType PointerType = getContext().getPointerType(FundamentalType);
3872
100
    QualType PointerTypeConst = getContext().getPointerType(
3873
100
        FundamentalType.withConst());
3874
100
    for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
3875
300
      ItaniumRTTIBuilder(*this).BuildTypeInfo(
3876
300
          Type, llvm::GlobalValue::ExternalLinkage,
3877
300
          Visibility, DLLStorageClass);
3878
100
  }
3879
4
}
3880
3881
/// What sort of uniqueness rules should we use for the RTTI for the
3882
/// given type?
3883
ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3884
4.17k
    QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3885
4.17k
  if (shouldRTTIBeUnique())
3886
4.14k
    return RUK_Unique;
3887
28
3888
28
  // It's only necessary for linkonce_odr or weak_odr linkage.
3889
28
  if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3890
28
      
Linkage != llvm::GlobalValue::WeakODRLinkage8
)
3891
4
    return RUK_Unique;
3892
24
3893
24
  // It's only necessary with default visibility.
3894
24
  if (CanTy->getVisibility() != DefaultVisibility)
3895
8
    return RUK_Unique;
3896
16
3897
16
  // If we're not required to publish this symbol, hide it.
3898
16
  if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3899
12
    return RUK_NonUniqueHidden;
3900
4
3901
4
  // If we're required to publish this symbol, as we might be under an
3902
4
  // explicit instantiation, leave it with default visibility but
3903
4
  // enable string-comparisons.
3904
4
  assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3905
4
  return RUK_NonUniqueVisible;
3906
4
}
3907
3908
// Find out how to codegen the complete destructor and constructor
3909
namespace {
3910
enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3911
}
3912
static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3913
47.2k
                                       const CXXMethodDecl *MD) {
3914
47.2k
  if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3915
46.7k
    return StructorCodegen::Emit;
3916
538
3917
538
  // The complete and base structors are not equivalent if there are any virtual
3918
538
  // bases, so emit separate functions.
3919
538
  if (MD->getParent()->getNumVBases())
3920
33
    return StructorCodegen::Emit;
3921
505
3922
505
  GlobalDecl AliasDecl;
3923
505
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3924
352
    AliasDecl = GlobalDecl(DD, Dtor_Complete);
3925
352
  } else {
3926
153
    const auto *CD = cast<CXXConstructorDecl>(MD);
3927
153
    AliasDecl = GlobalDecl(CD, Ctor_Complete);
3928
153
  }
3929
505
  llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3930
505
3931
505
  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3932
339
    return StructorCodegen::RAUW;
3933
166
3934
166
  // FIXME: Should we allow available_externally aliases?
3935
166
  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3936
0
    return StructorCodegen::RAUW;
3937
166
3938
166
  if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3939
33
    // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3940
33
    if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3941
33
        
CGM.getTarget().getTriple().isOSBinFormatWasm()11
)
3942
22
      return StructorCodegen::COMDAT;
3943
11
    return StructorCodegen::Emit;
3944
11
  }
3945
133
3946
133
  return StructorCodegen::Alias;
3947
133
}
3948
3949
static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3950
                                           GlobalDecl AliasDecl,
3951
74
                                           GlobalDecl TargetDecl) {
3952
74
  llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3953
74
3954
74
  StringRef MangledName = CGM.getMangledName(AliasDecl);
3955
74
  llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3956
74
  if (Entry && 
!Entry->isDeclaration()2
)
3957
0
    return;
3958
74
3959
74
  auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3960
74
3961
74
  // Create the alias with no name.
3962
74
  auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
3963
74
3964
74
  // Constructors and destructors are always unnamed_addr.
3965
74
  Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3966
74
3967
74
  // Switch any previous uses to the alias.
3968
74
  if (Entry) {
3969
2
    assert(Entry->getType() == Aliasee->getType() &&
3970
2
           "declaration exists with different type");
3971
2
    Alias->takeName(Entry);
3972
2
    Entry->replaceAllUsesWith(Alias);
3973
2
    Entry->eraseFromParent();
3974
72
  } else {
3975
72
    Alias->setName(MangledName);
3976
72
  }
3977
74
3978
74
  // Finally, set up the alias with its proper name and attributes.
3979
74
  CGM.SetCommonAttributes(AliasDecl, Alias);
3980
74
}
3981
3982
47.2k
void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
3983
47.2k
  auto *MD = cast<CXXMethodDecl>(GD.getDecl());
3984
47.2k
  auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3985
47.2k
  const CXXDestructorDecl *DD = CD ? 
nullptr33.9k
:
cast<CXXDestructorDecl>(MD)13.3k
;
3986
47.2k
3987
47.2k
  StructorCodegen CGType = getCodegenToUse(CGM, MD);
3988
47.2k
3989
47.2k
  if (CD ? 
GD.getCtorType() == Ctor_Complete33.9k
3990
47.2k
         : 
GD.getDtorType() == Dtor_Complete13.3k
) {
3991
20.5k
    GlobalDecl BaseDecl;
3992
20.5k
    if (CD)
3993
14.4k
      BaseDecl = GD.getWithCtorType(Ctor_Base);
3994
6.11k
    else
3995
6.11k
      BaseDecl = GD.getWithDtorType(Dtor_Base);
3996
20.5k
3997
20.5k
    if (CGType == StructorCodegen::Alias || 
CGType == StructorCodegen::COMDAT20.4k
) {
3998
74
      emitConstructorDestructorAlias(CGM, GD, BaseDecl);
3999
74
      return;
4000
74
    }
4001
20.4k
4002
20.4k
    if (CGType == StructorCodegen::RAUW) {
4003
141
      StringRef MangledName = CGM.getMangledName(GD);
4004
141
      auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
4005
141
      CGM.addReplacement(MangledName, Aliasee);
4006
141
      return;
4007
141
    }
4008
47.0k
  }
4009
47.0k
4010
47.0k
  // The base destructor is equivalent to the base destructor of its
4011
47.0k
  // base class if there is exactly one non-virtual base class with a
4012
47.0k
  // non-trivial destructor, there are no fields with a non-trivial
4013
47.0k
  // destructor, and the body of the destructor is trivial.
4014
47.0k
  if (DD && 
GD.getDtorType() == Dtor_Base13.1k
&&
4015
47.0k
      
CGType != StructorCodegen::COMDAT6.61k
&&
4016
47.0k
      
!CGM.TryEmitBaseDestructorAsAlias(DD)6.60k
)
4017
35
    return;
4018
46.9k
4019
46.9k
  // FIXME: The deleting destructor is equivalent to the selected operator
4020
46.9k
  // delete if:
4021
46.9k
  //  * either the delete is a destroying operator delete or the destructor
4022
46.9k
  //    would be trivial if it weren't virtual,
4023
46.9k
  //  * the conversion from the 'this' parameter to the first parameter of the
4024
46.9k
  //    destructor is equivalent to a bitcast,
4025
46.9k
  //  * the destructor does not have an implicit "this" return, and
4026
46.9k
  //  * the operator delete has the same calling convention and IR function type
4027
46.9k
  //    as the destructor.
4028
46.9k
  // In such cases we should try to emit the deleting dtor as an alias to the
4029
46.9k
  // selected 'operator delete'.
4030
46.9k
4031
46.9k
  llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4032
46.9k
4033
46.9k
  if (CGType == StructorCodegen::COMDAT) {
4034
12
    SmallString<256> Buffer;
4035
12
    llvm::raw_svector_ostream Out(Buffer);
4036
12
    if (DD)
4037
10
      getMangleContext().mangleCXXDtorComdat(DD, Out);
4038
2
    else
4039
2
      getMangleContext().mangleCXXCtorComdat(CD, Out);
4040
12
    llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
4041
12
    Fn->setComdat(C);
4042
46.9k
  } else {
4043
46.9k
    CGM.maybeSetTrivialComdat(*MD, *Fn);
4044
46.9k
  }
4045
46.9k
}
4046
4047
901
static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
4048
901
  // void *__cxa_begin_catch(void*);
4049
901
  llvm::FunctionType *FTy = llvm::FunctionType::get(
4050
901
      CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4051
901
4052
901
  return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
4053
901
}
4054
4055
399
static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
4056
399
  // void __cxa_end_catch();
4057
399
  llvm::FunctionType *FTy =
4058
399
      llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
4059
399
4060
399
  return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
4061
399
}
4062
4063
6
static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
4064
6
  // void *__cxa_get_exception_ptr(void*);
4065
6
  llvm::FunctionType *FTy = llvm::FunctionType::get(
4066
6
      CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4067
6
4068
6
  return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4069
6
}
4070
4071
namespace {
4072
  /// A cleanup to call __cxa_end_catch.  In many cases, the caught
4073
  /// exception type lets us state definitively that the thrown exception
4074
  /// type does not have a destructor.  In particular:
4075
  ///   - Catch-alls tell us nothing, so we have to conservatively
4076
  ///     assume that the thrown exception might have a destructor.
4077
  ///   - Catches by reference behave according to their base types.
4078
  ///   - Catches of non-record types will only trigger for exceptions
4079
  ///     of non-record types, which never have destructors.
4080
  ///   - Catches of record types can trigger for arbitrary subclasses
4081
  ///     of the caught type, so we have to assume the actual thrown
4082
  ///     exception type might have a throwing destructor, even if the
4083
  ///     caught type's destructor is trivial or nothrow.
4084
  struct CallEndCatch final : EHScopeStack::Cleanup {
4085
292
    CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4086
    bool MightThrow;
4087
4088
399
    void Emit(CodeGenFunction &CGF, Flags flags) override {
4089
399
      if (!MightThrow) {
4090
119
        CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
4091
119
        return;
4092
119
      }
4093
280
4094
280
      CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
4095
280
    }
4096
  };
4097
}
4098
4099
/// Emits a call to __cxa_begin_catch and enters a cleanup to call
4100
/// __cxa_end_catch.
4101
///
4102
/// \param EndMightThrow - true if __cxa_end_catch might throw
4103
static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4104
                                   llvm::Value *Exn,
4105
292
                                   bool EndMightThrow) {
4106
292
  llvm::CallInst *call =
4107
292
    CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
4108
292
4109
292
  CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
4110
292
4111
292
  return call;
4112
292
}
4113
4114
/// A "special initializer" callback for initializing a catch
4115
/// parameter during catch initialization.
4116
static void InitCatchParam(CodeGenFunction &CGF,
4117
                           const VarDecl &CatchParam,
4118
                           Address ParamAddr,
4119
114
                           SourceLocation Loc) {
4120
114
  // Load the exception from where the landing pad saved it.
4121
114
  llvm::Value *Exn = CGF.getExceptionFromSlot();
4122
114
4123
114
  CanQualType CatchType =
4124
114
    CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4125
114
  llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4126
114
4127
114
  // If we're catching by reference, we can just cast the object
4128
114
  // pointer to the appropriate pointer.
4129
114
  if (isa<ReferenceType>(CatchType)) {
4130
36
    QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4131
36
    bool EndCatchMightThrow = CaughtType->isRecordType();
4132
36
4133
36
    // __cxa_begin_catch returns the adjusted object pointer.
4134
36
    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4135
36
4136
36
    // We have no way to tell the personality function that we're
4137
36
    // catching by reference, so if we're catching a pointer,
4138
36
    // __cxa_begin_catch will actually return that pointer by value.
4139
36
    if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4140
9
      QualType PointeeType = PT->getPointeeType();
4141
9
4142
9
      // When catching by reference, generally we should just ignore
4143
9
      // this by-value pointer and use the exception object instead.
4144
9
      if (!PointeeType->isRecordType()) {
4145
7
4146
7
        // Exn points to the struct _Unwind_Exception header, which
4147
7
        // we have to skip past in order to reach the exception data.
4148
7
        unsigned HeaderSize =
4149
7
          CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4150
7
        AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
4151
7
4152
7
      // However, if we're catching a pointer-to-record type that won't
4153
7
      // work, because the personality function might have adjusted
4154
7
      // the pointer.  There's actually no way for us to fully satisfy
4155
7
      // the language/ABI contract here:  we can't use Exn because it
4156
7
      // might have the wrong adjustment, but we can't use the by-value
4157
7
      // pointer because it's off by a level of abstraction.
4158
7
      //
4159
7
      // The current solution is to dump the adjusted pointer into an
4160
7
      // alloca, which breaks language semantics (because changing the
4161
7
      // pointer doesn't change the exception) but at least works.
4162
7
      // The better solution would be to filter out non-exact matches
4163
7
      // and rethrow them, but this is tricky because the rethrow
4164
7
      // really needs to be catchable by other sites at this landing
4165
7
      // pad.  The best solution is to fix the personality function.
4166
7
      } else {
4167
2
        // Pull the pointer for the reference type off.
4168
2
        llvm::Type *PtrTy =
4169
2
          cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
4170
2
4171
2
        // Create the temporary and write the adjusted pointer into it.
4172
2
        Address ExnPtrTmp =
4173
2
          CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
4174
2
        llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4175
2
        CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4176
2
4177
2
        // Bind the reference to the temporary.
4178
2
        AdjustedExn = ExnPtrTmp.getPointer();
4179
2
      }
4180
9
    }
4181
36
4182
36
    llvm::Value *ExnCast =
4183
36
      CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4184
36
    CGF.Builder.CreateStore(ExnCast, ParamAddr);
4185
36
    return;
4186
36
  }
4187
78
4188
78
  // Scalars and complexes.
4189
78
  TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
4190
78
  if (TEK != TEK_Aggregate) {
4191
69
    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
4192
69
4193
69
    // If the catch type is a pointer type, __cxa_begin_catch returns
4194
69
    // the pointer by value.
4195
69
    if (CatchType->hasPointerRepresentation()) {
4196
8
      llvm::Value *CastExn =
4197
8
        CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
4198
8
4199
8
      switch (CatchType.getQualifiers().getObjCLifetime()) {
4200
1
      case Qualifiers::OCL_Strong:
4201
1
        CastExn = CGF.EmitARCRetainNonBlock(CastExn);
4202
1
        LLVM_FALLTHROUGH;
4203
1
4204
7
      case Qualifiers::OCL_None:
4205
7
      case Qualifiers::OCL_ExplicitNone:
4206
7
      case Qualifiers::OCL_Autoreleasing:
4207
7
        CGF.Builder.CreateStore(CastExn, ParamAddr);
4208
7
        return;
4209
7
4210
7
      case Qualifiers::OCL_Weak:
4211
1
        CGF.EmitARCInitWeak(ParamAddr, CastExn);
4212
1
        return;
4213
0
      }
4214
0
      llvm_unreachable("bad ownership qualifier!");
4215
0
    }
4216
61
4217
61
    // Otherwise, it returns a pointer into the exception object.
4218
61
4219
61
    llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4220
61
    llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4221
61
4222
61
    LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
4223
61
    LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
4224
61
    switch (TEK) {
4225
0
    case TEK_Complex:
4226
0
      CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
4227
0
                             /*init*/ true);
4228
0
      return;
4229
61
    case TEK_Scalar: {
4230
61
      llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
4231
61
      CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
4232
61
      return;
4233
0
    }
4234
0
    case TEK_Aggregate:
4235
0
      llvm_unreachable("evaluation kind filtered out!");
4236
0
    }
4237
0
    llvm_unreachable("bad evaluation kind");
4238
0
  }
4239
9
4240
9
  assert(isa<RecordType>(CatchType) && "unexpected catch type!");
4241
9
  auto catchRD = CatchType->getAsCXXRecordDecl();
4242
9
  CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
4243
9
4244
9
  llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4245
9
4246
9
  // Check for a copy expression.  If we don't have a copy expression,
4247
9
  // that means a trivial copy is okay.
4248
9
  const Expr *copyExpr = CatchParam.getInit();
4249
9
  if (!copyExpr) {
4250
3
    llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
4251
3
    Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4252
3
                        caughtExnAlignment);
4253
3
    LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
4254
3
    LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
4255
3
    CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
4256
3
    return;
4257
3
  }
4258
6
4259
6
  // We have to call __cxa_get_exception_ptr to get the adjusted
4260
6
  // pointer before copying.
4261
6
  llvm::CallInst *rawAdjustedExn =
4262
6
    CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
4263
6
4264
6
  // Cast that to the appropriate type.
4265
6
  Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4266
6
                      caughtExnAlignment);
4267
6
4268
6
  // The copy expression is defined in terms of an OpaqueValueExpr.
4269
6
  // Find it and map it to the adjusted expression.
4270
6
  CodeGenFunction::OpaqueValueMapping
4271
6
    opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4272
6
           CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4273
6
4274
6
  // Call the copy ctor in a terminate scope.
4275
6
  CGF.EHStack.pushTerminate();
4276
6
4277
6
  // Perform the copy construction.
4278
6
  CGF.EmitAggExpr(copyExpr,
4279
6
                  AggValueSlot::forAddr(ParamAddr, Qualifiers(),
4280
6
                                        AggValueSlot::IsNotDestructed,
4281
6
                                        AggValueSlot::DoesNotNeedGCBarriers,
4282
6
                                        AggValueSlot::IsNotAliased,
4283
6
                                        AggValueSlot::DoesNotOverlap));
4284
6
4285
6
  // Leave the terminate scope.
4286
6
  CGF.EHStack.popTerminate();
4287
6
4288
6
  // Undo the opaque value mapping.
4289
6
  opaque.pop();
4290
6
4291
6
  // Finally we can call __cxa_begin_catch.
4292
6
  CallBeginCatch(CGF, Exn, true);
4293
6
}
4294
4295
/// Begins a catch statement by initializing the catch variable and
4296
/// calling __cxa_begin_catch.
4297
void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4298
292
                                   const CXXCatchStmt *S) {
4299
292
  // We have to be very careful with the ordering of cleanups here:
4300
292
  //   C++ [except.throw]p4:
4301
292
  //     The destruction [of the exception temporary] occurs
4302
292
  //     immediately after the destruction of the object declared in
4303
292
  //     the exception-declaration in the handler.
4304
292
  //
4305
292
  // So the precise ordering is:
4306
292
  //   1.  Construct catch variable.
4307
292
  //   2.  __cxa_begin_catch
4308
292
  //   3.  Enter __cxa_end_catch cleanup
4309
292
  //   4.  Enter dtor cleanup
4310
292
  //
4311
292
  // We do this by using a slightly abnormal initialization process.
4312
292
  // Delegation sequence:
4313
292
  //   - ExitCXXTryStmt opens a RunCleanupsScope
4314
292
  //     - EmitAutoVarAlloca creates the variable and debug info
4315
292
  //       - InitCatchParam initializes the variable from the exception
4316
292
  //       - CallBeginCatch calls __cxa_begin_catch
4317
292
  //       - CallBeginCatch enters the __cxa_end_catch cleanup
4318
292
  //     - EmitAutoVarCleanups enters the variable destructor cleanup
4319
292
  //   - EmitCXXTryStmt emits the code for the catch body
4320
292
  //   - EmitCXXTryStmt close the RunCleanupsScope
4321
292
4322
292
  VarDecl *CatchParam = S->getExceptionDecl();
4323
292
  if (!CatchParam) {
4324
178
    llvm::Value *Exn = CGF.getExceptionFromSlot();
4325
178
    CallBeginCatch(CGF, Exn, true);
4326
178
    return;
4327
178
  }
4328
114
4329
114
  // Emit the local.
4330
114
  CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
4331
114
  InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
4332
114
  CGF.EmitAutoVarCleanups(var);
4333
114
}
4334
4335
/// Get or define the following function:
4336
///   void @__clang_call_terminate(i8* %exn) nounwind noreturn
4337
/// This code is used only in C++.
4338
4.09k
static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
4339
4.09k
  llvm::FunctionType *fnTy =
4340
4.09k
    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4341
4.09k
  llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
4342
4.09k
      fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
4343
4.09k
  llvm::Function *fn =
4344
4.09k
      cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
4345
4.09k
  if (fn->empty()) {
4346
609
    fn->setDoesNotThrow();
4347
609
    fn->setDoesNotReturn();
4348
609
4349
609
    // What we really want is to massively penalize inlining without
4350
609
    // forbidding it completely.  The difference between that and
4351
609
    // 'noinline' is negligible.
4352
609
    fn->addFnAttr(llvm::Attribute::NoInline);
4353
609
4354
609
    // Allow this function to be shared across translation units, but
4355
609
    // we don't want it to turn into an exported symbol.
4356
609
    fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4357
609
    fn->setVisibility(llvm::Function::HiddenVisibility);
4358
609
    if (CGM.supportsCOMDAT())
4359
116
      fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
4360
609
4361
609
    // Set up the function.
4362
609
    llvm::BasicBlock *entry =
4363
609
        llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
4364
609
    CGBuilderTy builder(CGM, entry);
4365
609
4366
609
    // Pull the exception pointer out of the parameter list.
4367
609
    llvm::Value *exn = &*fn->arg_begin();
4368
609
4369
609
    // Call __cxa_begin_catch(exn).
4370
609
    llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4371
609
    catchCall->setDoesNotThrow();
4372
609
    catchCall->setCallingConv(CGM.getRuntimeCC());
4373
609
4374
609
    // Call std::terminate().
4375
609
    llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
4376
609
    termCall->setDoesNotThrow();
4377
609
    termCall->setDoesNotReturn();
4378
609
    termCall->setCallingConv(CGM.getRuntimeCC());
4379
609
4380
609
    // std::terminate cannot return.
4381
609
    builder.CreateUnreachable();
4382
609
  }
4383
4.09k
  return fnRef;
4384
4.09k
}
4385
4386
llvm::CallInst *
4387
ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4388
4.09k
                                                   llvm::Value *Exn) {
4389
4.09k
  // In C++, we want to call __cxa_begin_catch() before terminating.
4390
4.09k
  if (Exn) {
4391
4.09k
    assert(CGF.CGM.getLangOpts().CPlusPlus);
4392
4.09k
    return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4393
4.09k
  }
4394
3
  return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4395
3
}
4396
4397
std::pair<llvm::Value *, const CXXRecordDecl *>
4398
ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4399
27
                             const CXXRecordDecl *RD) {
4400
27
  return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4401
27
}
4402
4403
void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4404
42
                                       const CXXCatchStmt *C) {
4405
42
  if (CGF.getTarget().hasFeature("exception-handling"))
4406
42
    CGF.EHStack.pushCleanup<CatchRetScope>(
4407
42
        NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
4408
42
  ItaniumCXXABI::emitBeginCatch(CGF, C);
4409
42
}