Coverage Report

Created: 2020-02-18 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
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 contains code dealing with C++ code generation.
10
//
11
//===----------------------------------------------------------------------===//
12
13
// We might split this into multiple files if it gets too unwieldy
14
15
#include "CGCXXABI.h"
16
#include "CodeGenFunction.h"
17
#include "CodeGenModule.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/Attr.h"
20
#include "clang/AST/Decl.h"
21
#include "clang/AST/DeclCXX.h"
22
#include "clang/AST/DeclObjC.h"
23
#include "clang/AST/Mangle.h"
24
#include "clang/AST/RecordLayout.h"
25
#include "clang/AST/StmtCXX.h"
26
#include "clang/Basic/CodeGenOptions.h"
27
#include "llvm/ADT/StringExtras.h"
28
using namespace clang;
29
using namespace CodeGen;
30
31
32
/// Try to emit a base destructor as an alias to its primary
33
/// base-class destructor.
34
6.85k
bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
35
6.85k
  if (!getCodeGenOpts().CXXCtorDtorAliases)
36
6.63k
    return true;
37
211
38
211
  // Producing an alias to a base class ctor/dtor can degrade debug quality
39
211
  // as the debugger cannot tell them apart.
40
211
  if (getCodeGenOpts().OptimizationLevel == 0)
41
65
    return true;
42
146
43
146
  // If sanitizing memory to check for use-after-dtor, do not emit as
44
146
  //  an alias, unless this class owns no members.
45
146
  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
46
146
      
!D->getParent()->field_empty()0
)
47
0
    return true;
48
146
49
146
  // If the destructor doesn't have a trivial body, we have to emit it
50
146
  // separately.
51
146
  if (!D->hasTrivialBody())
52
14
    return true;
53
132
54
132
  const CXXRecordDecl *Class = D->getParent();
55
132
56
132
  // We are going to instrument this destructor, so give up even if it is
57
132
  // currently empty.
58
132
  if (Class->mayInsertExtraPadding())
59
6
    return true;
60
126
61
126
  // If we need to manipulate a VTT parameter, give up.
62
126
  if (Class->getNumVBases()) {
63
6
    // Extra Credit:  passing extra parameters is perfectly safe
64
6
    // in many calling conventions, so only bail out if the ctor's
65
6
    // calling convention is nonstandard.
66
6
    return true;
67
6
  }
68
120
69
120
  // If any field has a non-trivial destructor, we have to emit the
70
120
  // destructor separately.
71
120
  for (const auto *I : Class->fields())
72
22
    if (I->getType().isDestructedType())
73
11
      return true;
74
120
75
120
  // Try to find a unique base class with a non-trivial destructor.
76
120
  const CXXRecordDecl *UniqueBase = nullptr;
77
109
  for (const auto &I : Class->bases()) {
78
74
79
74
    // We're in the base destructor, so skip virtual bases.
80
74
    if (I.isVirtual()) 
continue0
;
81
74
82
74
    // Skip base classes with trivial destructors.
83
74
    const auto *Base =
84
74
        cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
85
74
    if (Base->hasTrivialDestructor()) 
continue7
;
86
67
87
67
    // If we've already found a base class with a non-trivial
88
67
    // destructor, give up.
89
67
    if (UniqueBase) 
return true4
;
90
63
    UniqueBase = Base;
91
63
  }
92
109
93
109
  // If we didn't find any bases with a non-trivial destructor, then
94
109
  // the base destructor is actually effectively trivial, which can
95
109
  // happen if it was needlessly user-defined or if there are virtual
96
109
  // bases with non-trivial destructors.
97
109
  
if (105
!UniqueBase105
)
98
46
    return true;
99
59
100
59
  // If the base is at a non-zero offset, give up.
101
59
  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
102
59
  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
103
2
    return true;
104
57
105
57
  // Give up if the calling conventions don't match. We could update the call,
106
57
  // but it is probably not worth it.
107
57
  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
108
57
  if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
109
57
      D->getType()->castAs<FunctionType>()->getCallConv())
110
2
    return true;
111
55
112
55
  GlobalDecl AliasDecl(D, Dtor_Base);
113
55
  GlobalDecl TargetDecl(BaseD, Dtor_Base);
114
55
115
55
  // The alias will use the linkage of the referent.  If we can't
116
55
  // support aliases with that linkage, fail.
117
55
  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
118
55
119
55
  // We can't use an alias if the linkage is not valid for one.
120
55
  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
121
2
    return true;
122
53
123
53
  llvm::GlobalValue::LinkageTypes TargetLinkage =
124
53
      getFunctionLinkage(TargetDecl);
125
53
126
53
  // Check if we have it already.
127
53
  StringRef MangledName = getMangledName(AliasDecl);
128
53
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
129
53
  if (Entry && 
!Entry->isDeclaration()22
)
130
0
    return false;
131
53
  if (Replacements.count(MangledName))
132
0
    return false;
133
53
134
53
  // Derive the type for the alias.
135
53
  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
136
53
  llvm::PointerType *AliasType = AliasValueType->getPointerTo();
137
53
138
53
  // Find the referent.  Some aliases might require a bitcast, in
139
53
  // which case the caller is responsible for ensuring the soundness
140
53
  // of these semantics.
141
53
  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
142
53
  llvm::Constant *Aliasee = Ref;
143
53
  if (Ref->getType() != AliasType)
144
53
    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
145
53
146
53
  // Instead of creating as alias to a linkonce_odr, replace all of the uses
147
53
  // of the aliasee.
148
53
  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
149
53
      
!(22
TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage22
&&
150
22
        
TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>()2
)) {
151
20
    // FIXME: An extern template instantiation will create functions with
152
20
    // linkage "AvailableExternally". In libc++, some classes also define
153
20
    // members with attribute "AlwaysInline" and expect no reference to
154
20
    // be generated. It is desirable to reenable this optimisation after
155
20
    // corresponding LLVM changes.
156
20
    addReplacement(MangledName, Aliasee);
157
20
    return false;
158
20
  }
159
33
160
33
  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
161
33
  // template instantiation or a dllexported class, avoid forming it on COFF.
162
33
  // A COFF weak external alias cannot satisfy a normal undefined symbol
163
33
  // reference from another TU. The other TU must also mark the referenced
164
33
  // symbol as weak, which we cannot rely on.
165
33
  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
166
33
      
getTriple().isOSBinFormatCOFF()8
) {
167
7
    return true;
168
7
  }
169
26
170
26
  // If we don't have a definition for the destructor yet or the definition is
171
26
  // avaialable_externally, don't emit an alias.  We can't emit aliases to
172
26
  // declarations; that's just not how aliases work.
173
26
  if (Ref->isDeclarationForLinker())
174
5
    return true;
175
21
176
21
  // Don't create an alias to a linker weak symbol. This avoids producing
177
21
  // different COMDATs in different TUs. Another option would be to
178
21
  // output the alias both for weak_odr and linkonce_odr, but that
179
21
  // requires explicit comdat support in the IL.
180
21
  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
181
2
    return true;
182
19
183
19
  // Create the alias with no name.
184
19
  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
185
19
                                          Aliasee, &getModule());
186
19
187
19
  // Destructors are always unnamed_addr.
188
19
  Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
189
19
190
19
  // Switch any previous uses to the alias.
191
19
  if (Entry) {
192
0
    assert(Entry->getType() == AliasType &&
193
0
           "declaration exists with different type");
194
0
    Alias->takeName(Entry);
195
0
    Entry->replaceAllUsesWith(Alias);
196
0
    Entry->eraseFromParent();
197
19
  } else {
198
19
    Alias->setName(MangledName);
199
19
  }
200
19
201
19
  // Finally, set up the alias with its proper name and attributes.
202
19
  SetCommonAttributes(AliasDecl, Alias);
203
19
204
19
  return false;
205
19
}
206
207
48.7k
llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
208
48.7k
  const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
209
48.7k
  auto *Fn = cast<llvm::Function>(
210
48.7k
      getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
211
48.7k
                           /*DontDefer=*/true, ForDefinition));
212
48.7k
213
48.7k
  setFunctionLinkage(GD, Fn);
214
48.7k
215
48.7k
  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
216
48.7k
  setNonAliasAttributes(GD, Fn);
217
48.7k
  SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
218
48.7k
  return Fn;
219
48.7k
}
220
221
llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
222
    GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
223
172k
    bool DontDefer, ForDefinition_t IsForDefinition) {
224
172k
  auto *MD = cast<CXXMethodDecl>(GD.getDecl());
225
172k
226
172k
  if (isa<CXXDestructorDecl>(MD)) {
227
56.4k
    // Always alias equivalent complete destructors to base destructors in the
228
56.4k
    // MS ABI.
229
56.4k
    if (getTarget().getCXXABI().isMicrosoft() &&
230
56.4k
        
GD.getDtorType() == Dtor_Complete2.21k
&&
231
56.4k
        
MD->getParent()->getNumVBases() == 0488
)
232
112
      GD = GD.getWithDtorType(Dtor_Base);
233
56.4k
  }
234
172k
235
172k
  if (!FnType) {
236
172k
    if (!FnInfo)
237
123k
      FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
238
172k
    FnType = getTypes().GetFunctionType(*FnInfo);
239
172k
  }
240
172k
241
172k
  llvm::Constant *Ptr = GetOrCreateLLVMFunction(
242
172k
      getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
243
172k
      /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
244
172k
  return {FnType, Ptr};
245
172k
}
246
247
static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
248
                                          GlobalDecl GD,
249
                                          llvm::Type *Ty,
250
15
                                          const CXXRecordDecl *RD) {
251
15
  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
252
15
         "No kext in Microsoft ABI");
253
15
  CodeGenModule &CGM = CGF.CGM;
254
15
  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
255
15
  Ty = Ty->getPointerTo()->getPointerTo();
256
15
  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
257
15
  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
258
15
  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
259
15
  const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
260
15
  VTableLayout::AddressPointLocation AddressPoint =
261
15
      VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
262
15
  VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
263
15
                 AddressPoint.AddressPointIndex;
264
15
  llvm::Value *VFuncPtr =
265
15
    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
266
15
  llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(
267
15
      VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));
268
15
  CGCallee Callee(GD, VFunc);
269
15
  return Callee;
270
15
}
271
272
/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
273
/// indirect call to virtual functions. It makes the call through indexing
274
/// into the vtable.
275
CGCallee
276
CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
277
                                           NestedNameSpecifier *Qual,
278
8
                                           llvm::Type *Ty) {
279
8
  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
280
8
         "BuildAppleKextVirtualCall - bad Qual kind");
281
8
282
8
  const Type *QTy = Qual->getAsType();
283
8
  QualType T = QualType(QTy, 0);
284
8
  const RecordType *RT = T->getAs<RecordType>();
285
8
  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
286
8
  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
287
8
288
8
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
289
2
    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
290
6
291
6
  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
292
6
}
293
294
/// BuildVirtualCall - This routine makes indirect vtable call for
295
/// call to virtual destructors. It returns 0 if it could not do it.
296
CGCallee
297
CodeGenFunction::BuildAppleKextVirtualDestructorCall(
298
                                            const CXXDestructorDecl *DD,
299
                                            CXXDtorType Type,
300
9
                                            const CXXRecordDecl *RD) {
301
9
  assert(DD->isVirtual() && Type != Dtor_Base);
302
9
  // Compute the function type we're calling.
303
9
  const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
304
9
      GlobalDecl(DD, Dtor_Complete));
305
9
  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
306
9
  return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
307
9
}