clang  3.9.0
CGCXX.cpp
Go to the documentation of this file.
1 //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 // We might split this into multiple files if it gets too unwieldy
15 
16 #include "CodeGenModule.h"
17 #include "CGCXXABI.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/ASTContext.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"
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.
35  if (!getCodeGenOpts().CXXCtorDtorAliases)
36  return true;
37 
38  // Producing an alias to a base class ctor/dtor can degrade debug quality
39  // as the debugger cannot tell them apart.
40  if (getCodeGenOpts().OptimizationLevel == 0)
41  return true;
42 
43  // If sanitizing memory to check for use-after-dtor, do not emit as
44  // an alias, unless this class owns no members.
45  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
46  !D->getParent()->field_empty())
47  return true;
48 
49  // If the destructor doesn't have a trivial body, we have to emit it
50  // separately.
51  if (!D->hasTrivialBody())
52  return true;
53 
54  const CXXRecordDecl *Class = D->getParent();
55 
56  // We are going to instrument this destructor, so give up even if it is
57  // currently empty.
58  if (Class->mayInsertExtraPadding())
59  return true;
60 
61  // If we need to manipulate a VTT parameter, give up.
62  if (Class->getNumVBases()) {
63  // Extra Credit: passing extra parameters is perfectly safe
64  // in many calling conventions, so only bail out if the ctor's
65  // calling convention is nonstandard.
66  return true;
67  }
68 
69  // If any field has a non-trivial destructor, we have to emit the
70  // destructor separately.
71  for (const auto *I : Class->fields())
72  if (I->getType().isDestructedType())
73  return true;
74 
75  // Try to find a unique base class with a non-trivial destructor.
76  const CXXRecordDecl *UniqueBase = nullptr;
77  for (const auto &I : Class->bases()) {
78 
79  // We're in the base destructor, so skip virtual bases.
80  if (I.isVirtual()) continue;
81 
82  // Skip base classes with trivial destructors.
83  const auto *Base =
84  cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
85  if (Base->hasTrivialDestructor()) continue;
86 
87  // If we've already found a base class with a non-trivial
88  // destructor, give up.
89  if (UniqueBase) return true;
90  UniqueBase = Base;
91  }
92 
93  // If we didn't find any bases with a non-trivial destructor, then
94  // the base destructor is actually effectively trivial, which can
95  // happen if it was needlessly user-defined or if there are virtual
96  // bases with non-trivial destructors.
97  if (!UniqueBase)
98  return true;
99 
100  // If the base is at a non-zero offset, give up.
101  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
102  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
103  return true;
104 
105  // Give up if the calling conventions don't match. We could update the call,
106  // but it is probably not worth it.
107  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
108  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
109  D->getType()->getAs<FunctionType>()->getCallConv())
110  return true;
111 
113  GlobalDecl(BaseD, Dtor_Base),
114  false);
115 }
116 
117 /// Try to emit a definition as a global alias for another definition.
118 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
119 /// in every translation unit.
121  GlobalDecl TargetDecl,
122  bool InEveryTU) {
123  if (!getCodeGenOpts().CXXCtorDtorAliases)
124  return true;
125 
126  // The alias will use the linkage of the referent. If we can't
127  // support aliases with that linkage, fail.
128  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
129 
130  // We can't use an alias if the linkage is not valid for one.
131  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
132  return true;
133 
134  llvm::GlobalValue::LinkageTypes TargetLinkage =
135  getFunctionLinkage(TargetDecl);
136 
137  // Check if we have it already.
138  StringRef MangledName = getMangledName(AliasDecl);
139  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
140  if (Entry && !Entry->isDeclaration())
141  return false;
142  if (Replacements.count(MangledName))
143  return false;
144 
145  // Derive the type for the alias.
146  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
147  llvm::PointerType *AliasType = AliasValueType->getPointerTo();
148 
149  // Find the referent. Some aliases might require a bitcast, in
150  // which case the caller is responsible for ensuring the soundness
151  // of these semantics.
152  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
153  llvm::Constant *Aliasee = Ref;
154  if (Ref->getType() != AliasType)
155  Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
156 
157  // Instead of creating as alias to a linkonce_odr, replace all of the uses
158  // of the aliasee.
159  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
160  (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
161  !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
162  // FIXME: An extern template instantiation will create functions with
163  // linkage "AvailableExternally". In libc++, some classes also define
164  // members with attribute "AlwaysInline" and expect no reference to
165  // be generated. It is desirable to reenable this optimisation after
166  // corresponding LLVM changes.
167  addReplacement(MangledName, Aliasee);
168  return false;
169  }
170 
171  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
172  // template instantiation or a dllexported class, avoid forming it on COFF.
173  // A COFF weak external alias cannot satisfy a normal undefined symbol
174  // reference from another TU. The other TU must also mark the referenced
175  // symbol as weak, which we cannot rely on.
176  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
177  getTriple().isOSBinFormatCOFF()) {
178  return true;
179  }
180 
181  if (!InEveryTU) {
182  // If we don't have a definition for the destructor yet, don't
183  // emit. We can't emit aliases to declarations; that's just not
184  // how aliases work.
185  if (Ref->isDeclaration())
186  return true;
187  }
188 
189  // Don't create an alias to a linker weak symbol. This avoids producing
190  // different COMDATs in different TUs. Another option would be to
191  // output the alias both for weak_odr and linkonce_odr, but that
192  // requires explicit comdat support in the IL.
193  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
194  return true;
195 
196  // Create the alias with no name.
197  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
198  Aliasee, &getModule());
199 
200  // Switch any previous uses to the alias.
201  if (Entry) {
202  assert(Entry->getType() == AliasType &&
203  "declaration exists with different type");
204  Alias->takeName(Entry);
205  Entry->replaceAllUsesWith(Alias);
206  Entry->eraseFromParent();
207  } else {
208  Alias->setName(MangledName);
209  }
210 
211  // Finally, set up the alias with its proper name and attributes.
212  setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
213 
214  return false;
215 }
216 
218  StructorType Type) {
219  const CGFunctionInfo &FnInfo =
221  auto *Fn = cast<llvm::Function>(
222  getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
223  /*DontDefer=*/true, /*IsForDefinition=*/true));
224 
225  GlobalDecl GD;
226  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
227  GD = GlobalDecl(DD, toCXXDtorType(Type));
228  } else {
229  const auto *CD = cast<CXXConstructorDecl>(MD);
230  GD = GlobalDecl(CD, toCXXCtorType(Type));
231  }
232 
233  setFunctionLinkage(GD, Fn);
235 
236  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
239  return Fn;
240 }
241 
243  const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
244  llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) {
245  GlobalDecl GD;
246  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
247  GD = GlobalDecl(CD, toCXXCtorType(Type));
248  } else {
249  GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
250  }
251 
252  if (!FnType) {
253  if (!FnInfo)
254  FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
255  FnType = getTypes().GetFunctionType(*FnInfo);
256  }
257 
258  return GetOrCreateLLVMFunction(
259  getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
260  /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition);
261 }
262 
264  GlobalDecl GD,
265  llvm::Type *Ty,
266  const CXXRecordDecl *RD) {
267  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
268  "No kext in Microsoft ABI");
269  GD = GD.getCanonicalDecl();
270  CodeGenModule &CGM = CGF.CGM;
271  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
272  Ty = Ty->getPointerTo()->getPointerTo();
273  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
274  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
275  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
276  uint64_t AddressPoint =
279  VTableIndex += AddressPoint;
280  llvm::Value *VFuncPtr =
281  CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
282  return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
283 }
284 
285 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
286 /// indirect call to virtual functions. It makes the call through indexing
287 /// into the vtable.
288 llvm::Value *
290  NestedNameSpecifier *Qual,
291  llvm::Type *Ty) {
292  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
293  "BuildAppleKextVirtualCall - bad Qual kind");
294 
295  const Type *QTy = Qual->getAsType();
296  QualType T = QualType(QTy, 0);
297  const RecordType *RT = T->getAs<RecordType>();
298  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
299  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
300 
301  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
303 
304  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
305 }
306 
307 /// BuildVirtualCall - This routine makes indirect vtable call for
308 /// call to virtual destructors. It returns 0 if it could not do it.
309 llvm::Value *
311  const CXXDestructorDecl *DD,
313  const CXXRecordDecl *RD) {
314  const auto *MD = cast<CXXMethodDecl>(DD);
315  // FIXME. Dtor_Base dtor is always direct!!
316  // It need be somehow inline expanded into the caller.
317  // -O does that. But need to support -O0 as well.
318  if (MD->isVirtual() && Type != Dtor_Base) {
319  // Compute the function type we're calling.
322  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
323  return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
324  }
325  return nullptr;
326 }
Defines the clang::ASTContext interface.
A (possibly-)qualified type.
Definition: Type.h:598
base_class_range bases()
Definition: DeclCXX.h:718
llvm::Module & getModule() const
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2879
void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV)
Set attributes which must be preserved by an alias.
The base class of the type hierarchy.
Definition: Type.h:1281
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition: CGCXX.cpp:34
void setFunctionDefinitionAttributes(const FunctionDecl *D, llvm::Function *F)
Set attributes for a global definition.
void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F)
Set the DLL storage class on F.
const CGFunctionInfo & arrangeCXXStructorDeclaration(const CXXMethodDecl *MD, StructorType Type)
Definition: CGCall.cpp:258
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:25
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:54
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
llvm::Function * codegenCXXStructor(const CXXMethodDecl *MD, StructorType Type)
Definition: CGCXX.cpp:217
const Decl * getDecl() const
Definition: GlobalDecl.h:62
uint64_t getAddressPoint(BaseSubobject Base) const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1838
field_range fields() const
Definition: Decl.h:3382
RecordDecl * getDecl() const
Definition: Type.h:3716
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition=false)
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
detail::InMemoryDirectory::const_iterator I
QualType getType() const
Definition: Decl.h:599
const TargetInfo & getTarget() const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
CXXDtorType
C++ destructor types.
Definition: ABI.h:34
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:155
CGCXXABI & getCXXABI() const
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:219
Base object dtor.
Definition: ABI.h:37
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:29
The l-value was considered opaque, so the alignment was determined from a type.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:160
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:3814
static llvm::Value * BuildAppleKextVirtualCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Type *Ty, const CXXRecordDecl *RD)
Definition: CGCXX.cpp:263
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1736
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
const CodeGenOptions & getCodeGenOpts() const
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
Complete object dtor.
Definition: ABI.h:36
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, bool IsForDefinition=false)
Return the address of the constructor/destructor of the given type.
Definition: CGCXX.cpp:242
ItaniumVTableContext & getItaniumVTableContext()
void addReplacement(StringRef Name, llvm::Constant *C)
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)
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1375
virtual llvm::GlobalVariable * getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset)=0
Get the address of the vtable for the given record decl which should be used for the vptr at the give...
CXXDtorType toCXXDtorType(StructorType T)
Definition: CodeGenTypes.h:92
bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target, bool InEveryTU)
Try to emit a definition as a global alias for another definition.
Definition: CGCXX.cpp:120
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:91
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
const llvm::Triple & getTriple() const
bool field_empty() const
Definition: Decl.h:3391
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3707
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
StringRef getMangledName(GlobalDecl GD)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
const VTableLayout & getVTableLayout(const CXXRecordDecl *RD)
llvm::Value * BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty)
BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making indirect call to virtual...
Definition: CGCXX.cpp:289
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
CXXCtorType toCXXCtorType(StructorType T)
Definition: CodeGenTypes.h:65
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:733
bool hasTrivialBody() const
hasTrivialBody - Returns whether the function has a trivial body that does not require any specific c...
Definition: Decl.cpp:2465
llvm::Value * BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, CXXDtorType Type, const CXXRecordDecl *RD)
BuildVirtualCall - This routine makes indirect vtable call for call to virtual destructors.
Definition: CGCXX.cpp:310
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1466