clang  10.0.0svn
CGCXX.cpp
Go to the documentation of this file.
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 "CodeGenModule.h"
16 #include "CGCXXABI.h"
17 #include "CodeGenFunction.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtCXX.h"
26 #include "llvm/ADT/StringExtras.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 
31 /// Try to emit a base destructor as an alias to its primary
32 /// base-class destructor.
34  if (!getCodeGenOpts().CXXCtorDtorAliases)
35  return true;
36 
37  // Producing an alias to a base class ctor/dtor can degrade debug quality
38  // as the debugger cannot tell them apart.
39  if (getCodeGenOpts().OptimizationLevel == 0)
40  return true;
41 
42  // If sanitizing memory to check for use-after-dtor, do not emit as
43  // an alias, unless this class owns no members.
44  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
45  !D->getParent()->field_empty())
46  return true;
47 
48  // If the destructor doesn't have a trivial body, we have to emit it
49  // separately.
50  if (!D->hasTrivialBody())
51  return true;
52 
53  const CXXRecordDecl *Class = D->getParent();
54 
55  // We are going to instrument this destructor, so give up even if it is
56  // currently empty.
57  if (Class->mayInsertExtraPadding())
58  return true;
59 
60  // If we need to manipulate a VTT parameter, give up.
61  if (Class->getNumVBases()) {
62  // Extra Credit: passing extra parameters is perfectly safe
63  // in many calling conventions, so only bail out if the ctor's
64  // calling convention is nonstandard.
65  return true;
66  }
67 
68  // If any field has a non-trivial destructor, we have to emit the
69  // destructor separately.
70  for (const auto *I : Class->fields())
71  if (I->getType().isDestructedType())
72  return true;
73 
74  // Try to find a unique base class with a non-trivial destructor.
75  const CXXRecordDecl *UniqueBase = nullptr;
76  for (const auto &I : Class->bases()) {
77 
78  // We're in the base destructor, so skip virtual bases.
79  if (I.isVirtual()) continue;
80 
81  // Skip base classes with trivial destructors.
82  const auto *Base =
83  cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
84  if (Base->hasTrivialDestructor()) continue;
85 
86  // If we've already found a base class with a non-trivial
87  // destructor, give up.
88  if (UniqueBase) return true;
89  UniqueBase = Base;
90  }
91 
92  // If we didn't find any bases with a non-trivial destructor, then
93  // the base destructor is actually effectively trivial, which can
94  // happen if it was needlessly user-defined or if there are virtual
95  // bases with non-trivial destructors.
96  if (!UniqueBase)
97  return true;
98 
99  // If the base is at a non-zero offset, give up.
100  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
101  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
102  return true;
103 
104  // Give up if the calling conventions don't match. We could update the call,
105  // but it is probably not worth it.
106  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
107  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
108  D->getType()->getAs<FunctionType>()->getCallConv())
109  return true;
110 
111  GlobalDecl AliasDecl(D, Dtor_Base);
112  GlobalDecl TargetDecl(BaseD, Dtor_Base);
113 
114  // The alias will use the linkage of the referent. If we can't
115  // support aliases with that linkage, fail.
116  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
117 
118  // We can't use an alias if the linkage is not valid for one.
119  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
120  return true;
121 
122  llvm::GlobalValue::LinkageTypes TargetLinkage =
123  getFunctionLinkage(TargetDecl);
124 
125  // Check if we have it already.
126  StringRef MangledName = getMangledName(AliasDecl);
127  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
128  if (Entry && !Entry->isDeclaration())
129  return false;
130  if (Replacements.count(MangledName))
131  return false;
132 
133  // Derive the type for the alias.
134  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
135  llvm::PointerType *AliasType = AliasValueType->getPointerTo();
136 
137  // Find the referent. Some aliases might require a bitcast, in
138  // which case the caller is responsible for ensuring the soundness
139  // of these semantics.
140  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
141  llvm::Constant *Aliasee = Ref;
142  if (Ref->getType() != AliasType)
143  Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
144 
145  // Instead of creating as alias to a linkonce_odr, replace all of the uses
146  // of the aliasee.
147  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
148  !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
149  TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
150  // FIXME: An extern template instantiation will create functions with
151  // linkage "AvailableExternally". In libc++, some classes also define
152  // members with attribute "AlwaysInline" and expect no reference to
153  // be generated. It is desirable to reenable this optimisation after
154  // corresponding LLVM changes.
155  addReplacement(MangledName, Aliasee);
156  return false;
157  }
158 
159  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
160  // template instantiation or a dllexported class, avoid forming it on COFF.
161  // A COFF weak external alias cannot satisfy a normal undefined symbol
162  // reference from another TU. The other TU must also mark the referenced
163  // symbol as weak, which we cannot rely on.
164  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
165  getTriple().isOSBinFormatCOFF()) {
166  return true;
167  }
168 
169  // If we don't have a definition for the destructor yet or the definition is
170  // avaialable_externally, don't emit an alias. We can't emit aliases to
171  // declarations; that's just not how aliases work.
172  if (Ref->isDeclarationForLinker())
173  return true;
174 
175  // Don't create an alias to a linker weak symbol. This avoids producing
176  // different COMDATs in different TUs. Another option would be to
177  // output the alias both for weak_odr and linkonce_odr, but that
178  // requires explicit comdat support in the IL.
179  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
180  return true;
181 
182  // Create the alias with no name.
183  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
184  Aliasee, &getModule());
185 
186  // Destructors are always unnamed_addr.
187  Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
188 
189  // Switch any previous uses to the alias.
190  if (Entry) {
191  assert(Entry->getType() == AliasType &&
192  "declaration exists with different type");
193  Alias->takeName(Entry);
194  Entry->replaceAllUsesWith(Alias);
195  Entry->eraseFromParent();
196  } else {
197  Alias->setName(MangledName);
198  }
199 
200  // Finally, set up the alias with its proper name and attributes.
201  SetCommonAttributes(AliasDecl, Alias);
202 
203  return false;
204 }
205 
208  auto *Fn = cast<llvm::Function>(
209  getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
210  /*DontDefer=*/true, ForDefinition));
211 
212  setFunctionLinkage(GD, Fn);
213 
214  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
215  setNonAliasAttributes(GD, Fn);
216  SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
217  return Fn;
218 }
219 
221  GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
222  bool DontDefer, ForDefinition_t IsForDefinition) {
223  auto *MD = cast<CXXMethodDecl>(GD.getDecl());
224 
225  if (isa<CXXDestructorDecl>(MD)) {
226  // Always alias equivalent complete destructors to base destructors in the
227  // MS ABI.
228  if (getTarget().getCXXABI().isMicrosoft() &&
229  GD.getDtorType() == Dtor_Complete &&
230  MD->getParent()->getNumVBases() == 0)
231  GD = GD.getWithDtorType(Dtor_Base);
232  }
233 
234  if (!FnType) {
235  if (!FnInfo)
236  FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
237  FnType = getTypes().GetFunctionType(*FnInfo);
238  }
239 
240  llvm::Constant *Ptr = GetOrCreateLLVMFunction(
241  getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
242  /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
243  return {FnType, Ptr};
244 }
245 
247  GlobalDecl GD,
248  llvm::Type *Ty,
249  const CXXRecordDecl *RD) {
250  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
251  "No kext in Microsoft ABI");
252  CodeGenModule &CGM = CGF.CGM;
253  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
254  Ty = Ty->getPointerTo()->getPointerTo();
255  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
256  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
257  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
258  const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
261  VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
262  AddressPoint.AddressPointIndex;
263  llvm::Value *VFuncPtr =
264  CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
265  llvm::Value *VFunc =
266  CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
267  CGCallee Callee(GD, VFunc);
268  return Callee;
269 }
270 
271 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
272 /// indirect call to virtual functions. It makes the call through indexing
273 /// into the vtable.
274 CGCallee
276  NestedNameSpecifier *Qual,
277  llvm::Type *Ty) {
278  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
279  "BuildAppleKextVirtualCall - bad Qual kind");
280 
281  const Type *QTy = Qual->getAsType();
282  QualType T = QualType(QTy, 0);
283  const RecordType *RT = T->getAs<RecordType>();
284  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
285  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
286 
287  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
288  return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
289 
290  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
291 }
292 
293 /// BuildVirtualCall - This routine makes indirect vtable call for
294 /// call to virtual destructors. It returns 0 if it could not do it.
295 CGCallee
297  const CXXDestructorDecl *DD,
299  const CXXRecordDecl *RD) {
300  assert(DD->isVirtual() && Type != Dtor_Base);
301  // Compute the function type we're calling.
302  const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
304  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
305  return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
306 }
Defines the clang::ASTContext interface.
CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty)
BuildAppleKextVirtualCall - This routine is to support gcc&#39;s kext ABI making indirect call to virtual...
Definition: CGCXX.cpp:275
A (possibly-)qualified type.
Definition: Type.h:643
base_class_range bases()
Definition: DeclCXX.h:779
static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Type *Ty, const CXXRecordDecl *RD)
Definition: CGCXX.cpp:246
const CodeGenOptions & getCodeGenOpts() const
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:84
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3393
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:232
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:794
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
bool isVirtual() const
Definition: DeclCXX.h:2112
The base class of the type hierarchy.
Definition: Type.h:1436
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
AddressPointLocation getAddressPoint(BaseSubobject Base) const
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:115
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition: CGCXX.cpp:33
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6857
bool field_empty() const
Definition: Decl.h:3857
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:23
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:4364
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1060
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen...
Definition: Decl.cpp:2799
CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, CXXDtorType Type, const CXXRecordDecl *RD)
BuildVirtualCall - This routine makes indirect vtable call for call to virtual destructors.
Definition: CGCXX.cpp:296
field_range fields() const
Definition: Decl.h:3849
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:52
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1736
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition: GlobalDecl.h:130
bool hasAttr() const
Definition: DeclBase.h:542
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:305
CXXDtorType
C++ destructor types.
Definition: ABI.h:33
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2793
Base object dtor.
Definition: ABI.h:36
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
const TargetInfo & getTarget() const
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method...
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:40
The l-value was considered opaque, so the alignment was determined from a type.
RecordDecl * getDecl() const
Definition: Type.h:4454
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:141
const Decl * getDecl() const
Definition: GlobalDecl.h:77
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2069
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
All available information about a concrete callee.
Definition: CGCall.h:66
Complete object dtor.
Definition: ABI.h:35
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
Dataflow Directional Tag Classes.
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:90
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2192
llvm::Module & getModule() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4444
StringRef getMangledName(GlobalDecl GD)
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition: CGCXX.cpp:220
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:153
llvm::Function * codegenCXXStructor(GlobalDecl GD)
Definition: CGCXX.cpp:206
QualType getType() const
Definition: Decl.h:647
size_t getVTableOffset(size_t i) const
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1541
const llvm::Triple & getTriple() const