clang  3.7.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 /// 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 the destructor doesn't have a trivial body, we have to emit it
43  // separately.
44  if (!D->hasTrivialBody())
45  return true;
46 
47  const CXXRecordDecl *Class = D->getParent();
48 
49  // We are going to instrument this destructor, so give up even if it is
50  // currently empty.
51  if (Class->mayInsertExtraPadding())
52  return true;
53 
54  // If we need to manipulate a VTT parameter, give up.
55  if (Class->getNumVBases()) {
56  // Extra Credit: passing extra parameters is perfectly safe
57  // in many calling conventions, so only bail out if the ctor's
58  // calling convention is nonstandard.
59  return true;
60  }
61 
62  // If any field has a non-trivial destructor, we have to emit the
63  // destructor separately.
64  for (const auto *I : Class->fields())
65  if (I->getType().isDestructedType())
66  return true;
67 
68  // Try to find a unique base class with a non-trivial destructor.
69  const CXXRecordDecl *UniqueBase = nullptr;
70  for (const auto &I : Class->bases()) {
71 
72  // We're in the base destructor, so skip virtual bases.
73  if (I.isVirtual()) continue;
74 
75  // Skip base classes with trivial destructors.
76  const auto *Base =
77  cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
78  if (Base->hasTrivialDestructor()) continue;
79 
80  // If we've already found a base class with a non-trivial
81  // destructor, give up.
82  if (UniqueBase) return true;
83  UniqueBase = Base;
84  }
85 
86  // If we didn't find any bases with a non-trivial destructor, then
87  // the base destructor is actually effectively trivial, which can
88  // happen if it was needlessly user-defined or if there are virtual
89  // bases with non-trivial destructors.
90  if (!UniqueBase)
91  return true;
92 
93  // If the base is at a non-zero offset, give up.
94  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
95  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
96  return true;
97 
98  // Give up if the calling conventions don't match. We could update the call,
99  // but it is probably not worth it.
100  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
102  D->getType()->getAs<FunctionType>()->getCallConv())
103  return true;
104 
106  GlobalDecl(BaseD, Dtor_Base),
107  false);
108 }
109 
110 /// Try to emit a definition as a global alias for another definition.
111 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
112 /// in every translation unit.
114  GlobalDecl TargetDecl,
115  bool InEveryTU) {
116  if (!getCodeGenOpts().CXXCtorDtorAliases)
117  return true;
118 
119  // The alias will use the linkage of the referent. If we can't
120  // support aliases with that linkage, fail.
121  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
122 
123  // We can't use an alias if the linkage is not valid for one.
124  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
125  return true;
126 
127  // Don't create a weak alias for a dllexport'd symbol.
128  if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
129  llvm::GlobalValue::isWeakForLinker(Linkage))
130  return true;
131 
132  llvm::GlobalValue::LinkageTypes TargetLinkage =
133  getFunctionLinkage(TargetDecl);
134 
135  // Check if we have it already.
136  StringRef MangledName = getMangledName(AliasDecl);
137  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
138  if (Entry && !Entry->isDeclaration())
139  return false;
140  if (Replacements.count(MangledName))
141  return false;
142 
143  // Derive the type for the alias.
144  llvm::PointerType *AliasType
145  = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
146 
147  // Find the referent. Some aliases might require a bitcast, in
148  // which case the caller is responsible for ensuring the soundness
149  // of these semantics.
150  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
151  llvm::Constant *Aliasee = Ref;
152  if (Ref->getType() != AliasType)
153  Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
154 
155  // Instead of creating as alias to a linkonce_odr, replace all of the uses
156  // of the aliasee.
157  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
158  (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
159  !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
160  // FIXME: An extern template instantiation will create functions with
161  // linkage "AvailableExternally". In libc++, some classes also define
162  // members with attribute "AlwaysInline" and expect no reference to
163  // be generated. It is desirable to reenable this optimisation after
164  // corresponding LLVM changes.
165  Replacements[MangledName] = Aliasee;
166  return false;
167  }
168 
169  if (!InEveryTU) {
170  // If we don't have a definition for the destructor yet, don't
171  // emit. We can't emit aliases to declarations; that's just not
172  // how aliases work.
173  if (Ref->isDeclaration())
174  return true;
175  }
176 
177  // Don't create an alias to a linker weak symbol. This avoids producing
178  // different COMDATs in different TUs. Another option would be to
179  // output the alias both for weak_odr and linkonce_odr, but that
180  // requires explicit comdat support in the IL.
181  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
182  return true;
183 
184  // Create the alias with no name.
185  auto *Alias =
186  llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
187 
188  // Switch any previous uses to the alias.
189  if (Entry) {
190  assert(Entry->getType() == AliasType &&
191  "declaration exists with different type");
192  Alias->takeName(Entry);
193  Entry->replaceAllUsesWith(Alias);
194  Entry->eraseFromParent();
195  } else {
196  Alias->setName(MangledName);
197  }
198 
199  // Finally, set up the alias with its proper name and attributes.
200  setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
201 
202  return false;
203 }
204 
206  StructorType Type) {
207  const CGFunctionInfo &FnInfo =
209  auto *Fn = cast<llvm::Function>(
210  getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
211 
212  GlobalDecl GD;
213  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
214  GD = GlobalDecl(DD, toCXXDtorType(Type));
215  } else {
216  const auto *CD = cast<CXXConstructorDecl>(MD);
217  GD = GlobalDecl(CD, toCXXCtorType(Type));
218  }
219 
220  setFunctionLinkage(GD, Fn);
222 
223  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
226  return Fn;
227 }
228 
230  const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
231  llvm::FunctionType *FnType, bool DontDefer) {
232  GlobalDecl GD;
233  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
234  GD = GlobalDecl(CD, toCXXCtorType(Type));
235  } else {
236  GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
237  }
238 
239  StringRef Name = getMangledName(GD);
240  if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
241  return Existing;
242 
243  if (!FnType) {
244  if (!FnInfo)
245  FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
246  FnType = getTypes().GetFunctionType(*FnInfo);
247  }
248 
249  return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
250  /*ForVTable=*/false,
251  DontDefer));
252 }
253 
255  GlobalDecl GD,
256  llvm::Type *Ty,
257  const CXXRecordDecl *RD) {
258  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
259  "No kext in Microsoft ABI");
260  GD = GD.getCanonicalDecl();
261  CodeGenModule &CGM = CGF.CGM;
262  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
263  Ty = Ty->getPointerTo()->getPointerTo();
264  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
265  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
266  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
267  uint64_t AddressPoint =
270  VTableIndex += AddressPoint;
271  llvm::Value *VFuncPtr =
272  CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
273  return CGF.Builder.CreateLoad(VFuncPtr);
274 }
275 
276 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
277 /// indirect call to virtual functions. It makes the call through indexing
278 /// into the vtable.
279 llvm::Value *
281  NestedNameSpecifier *Qual,
282  llvm::Type *Ty) {
283  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
284  "BuildAppleKextVirtualCall - bad Qual kind");
285 
286  const Type *QTy = Qual->getAsType();
287  QualType T = QualType(QTy, 0);
288  const RecordType *RT = T->getAs<RecordType>();
289  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
290  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
291 
292  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
294 
295  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
296 }
297 
298 /// BuildVirtualCall - This routine makes indirect vtable call for
299 /// call to virtual destructors. It returns 0 if it could not do it.
300 llvm::Value *
302  const CXXDestructorDecl *DD,
304  const CXXRecordDecl *RD) {
305  const auto *MD = cast<CXXMethodDecl>(DD);
306  // FIXME. Dtor_Base dtor is always direct!!
307  // It need be somehow inline expanded into the caller.
308  // -O does that. But need to support -O0 as well.
309  if (MD->isVirtual() && Type != Dtor_Base) {
310  // Compute the function type we're calling.
313  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
314  return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
315  }
316  return nullptr;
317 }
Defines the clang::ASTContext interface.
base_class_range bases()
Definition: DeclCXX.h:713
llvm::Module & getModule() const
void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV)
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Definition: CGCXX.cpp:33
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:193
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:52
bool hasAttr() const
Definition: DeclBase.h:487
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:205
const Decl * getDecl() const
Definition: GlobalDecl.h:60
uint64_t getAddressPoint(BaseSubobject Base) const
const CXXRecordDecl * getParent() const
Definition: DeclCXX.h:1817
field_range fields() const
Definition: Decl.h:3349
RecordDecl * getDecl() const
Definition: Type.h:3527
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
QualType getType() const
Definition: Decl.h:538
llvm::GlobalValue * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false)
Return the address of the constructor/destructor of the given type.
Definition: CGCXX.cpp:229
const TargetInfo & getTarget() const
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:133
CGCXXABI & getCXXABI() const
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2358
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:224
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.
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields. These padding are added to help Addres...
Definition: Decl.cpp:3686
static llvm::Value * BuildAppleKextVirtualCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Type *Ty, const CXXRecordDecl *RD)
Definition: CGCXX.cpp:254
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1717
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
const CodeGenOptions & getCodeGenOpts() const
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Complete object dtor.
Definition: ABI.h:36
ItaniumVTableContext & getItaniumVTableContext()
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:1302
virtual llvm::GlobalVariable * getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset)=0
CXXDtorType toCXXDtorType(StructorType T)
Definition: CodeGenTypes.h:92
bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target, bool InEveryTU)
Definition: CGCXX.cpp:113
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
const T * getAs() const
Definition: Type.h:5555
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)
Definition: CGCXX.cpp:280
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD)
CXXCtorType toCXXCtorType(StructorType T)
Definition: CodeGenTypes.h:65
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:728
bool hasTrivialBody() const
Definition: Decl.cpp:2379
llvm::Value * BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, CXXDtorType Type, const CXXRecordDecl *RD)
Definition: CGCXX.cpp:301
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1253