CGCXX.cpp revision aedd9d5ad3cc776fd61457050bcd54cac4c5ea66
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 "CGCXXABI.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Mangle.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/Frontend/CodeGenOptions.h"
27#include "llvm/ADT/StringExtras.h"
28using namespace clang;
29using namespace CodeGen;
30
31/// Determines whether the given function has a trivial body that does
32/// not require any specific codegen.
33static bool HasTrivialBody(const FunctionDecl *FD) {
34  Stmt *S = FD->getBody();
35  if (!S)
36    return true;
37  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
38    return true;
39  return false;
40}
41
42/// Try to emit a base destructor as an alias to its primary
43/// base-class destructor.
44bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
45  if (!getCodeGenOpts().CXXCtorDtorAliases)
46    return true;
47
48  // If the destructor doesn't have a trivial body, we have to emit it
49  // separately.
50  if (!HasTrivialBody(D))
51    return true;
52
53  const CXXRecordDecl *Class = D->getParent();
54
55  // If we need to manipulate a VTT parameter, give up.
56  if (Class->getNumVBases()) {
57    // Extra Credit:  passing extra parameters is perfectly safe
58    // in many calling conventions, so only bail out if the ctor's
59    // calling convention is nonstandard.
60    return true;
61  }
62
63  // If any fields have a non-trivial destructor, we have to emit it
64  // separately.
65  for (CXXRecordDecl::field_iterator I = Class->field_begin(),
66         E = Class->field_end(); I != E; ++I)
67    if (const RecordType *RT = (*I)->getType()->getAs<RecordType>())
68      if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
69        return true;
70
71  // Try to find a unique base class with a non-trivial destructor.
72  const CXXRecordDecl *UniqueBase = 0;
73  for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
74         E = Class->bases_end(); I != E; ++I) {
75
76    // We're in the base destructor, so skip virtual bases.
77    if (I->isVirtual()) continue;
78
79    // Skip base classes with trivial destructors.
80    const CXXRecordDecl *Base
81      = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
82    if (Base->hasTrivialDestructor()) continue;
83
84    // If we've already found a base class with a non-trivial
85    // destructor, give up.
86    if (UniqueBase) return true;
87    UniqueBase = Base;
88  }
89
90  // If we didn't find any bases with a non-trivial destructor, then
91  // the base destructor is actually effectively trivial, which can
92  // happen if it was needlessly user-defined or if there are virtual
93  // bases with non-trivial destructors.
94  if (!UniqueBase)
95    return true;
96
97  /// If we don't have a definition for the destructor yet, don't
98  /// emit.  We can't emit aliases to declarations; that's just not
99  /// how aliases work.
100  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101  if (!BaseD->isImplicit() && !BaseD->hasBody())
102    return true;
103
104  // If the base is at a non-zero offset, give up.
105  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
106  if (ClassLayout.getBaseClassOffsetInBits(UniqueBase) != 0)
107    return true;
108
109  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
110                                  GlobalDecl(BaseD, Dtor_Base));
111}
112
113/// Try to emit a definition as a global alias for another definition.
114bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
115                                             GlobalDecl TargetDecl) {
116  if (!getCodeGenOpts().CXXCtorDtorAliases)
117    return true;
118
119  // The alias will use the linkage of the referrent.  If we can't
120  // support aliases with that linkage, fail.
121  llvm::GlobalValue::LinkageTypes Linkage
122    = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
123
124  switch (Linkage) {
125  // We can definitely emit aliases to definitions with external linkage.
126  case llvm::GlobalValue::ExternalLinkage:
127  case llvm::GlobalValue::ExternalWeakLinkage:
128    break;
129
130  // Same with local linkage.
131  case llvm::GlobalValue::InternalLinkage:
132  case llvm::GlobalValue::PrivateLinkage:
133  case llvm::GlobalValue::LinkerPrivateLinkage:
134    break;
135
136  // We should try to support linkonce linkages.
137  case llvm::GlobalValue::LinkOnceAnyLinkage:
138  case llvm::GlobalValue::LinkOnceODRLinkage:
139    return true;
140
141  // Other linkages will probably never be supported.
142  default:
143    return true;
144  }
145
146  llvm::GlobalValue::LinkageTypes TargetLinkage
147    = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl()));
148
149  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
150    return true;
151
152  // Derive the type for the alias.
153  const llvm::PointerType *AliasType
154    = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
155
156  // Find the referrent.  Some aliases might require a bitcast, in
157  // which case the caller is responsible for ensuring the soundness
158  // of these semantics.
159  llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
160  llvm::Constant *Aliasee = Ref;
161  if (Ref->getType() != AliasType)
162    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
163
164  // Create the alias with no name.
165  llvm::GlobalAlias *Alias =
166    new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
167
168  // Switch any previous uses to the alias.
169  llvm::StringRef MangledName = getMangledName(AliasDecl);
170  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
171  if (Entry) {
172    assert(Entry->isDeclaration() && "definition already exists for alias");
173    assert(Entry->getType() == AliasType &&
174           "declaration exists with different type");
175    Alias->takeName(Entry);
176    Entry->replaceAllUsesWith(Alias);
177    Entry->eraseFromParent();
178  } else {
179    Alias->setName(MangledName);
180  }
181
182  // Finally, set up the alias with its proper name and attributes.
183  SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
184
185  return false;
186}
187
188void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
189  // The constructor used for constructing this as a complete class;
190  // constucts the virtual bases, then calls the base constructor.
191  EmitGlobal(GlobalDecl(D, Ctor_Complete));
192
193  // The constructor used for constructing this as a base class;
194  // ignores virtual bases.
195  EmitGlobal(GlobalDecl(D, Ctor_Base));
196}
197
198void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
199                                       CXXCtorType Type) {
200  // The complete constructor is equivalent to the base constructor
201  // for classes with no virtual bases.  Try to emit it as an alias.
202  if (Type == Ctor_Complete &&
203      !D->getParent()->getNumVBases() &&
204      !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
205                                GlobalDecl(D, Ctor_Base)))
206    return;
207
208  llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
209  setFunctionLinkage(D, Fn);
210
211  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
212
213  SetFunctionDefinitionAttributes(D, Fn);
214  SetLLVMFunctionAttributesForDefinition(D, Fn);
215}
216
217llvm::GlobalValue *
218CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
219                                       CXXCtorType Type) {
220  GlobalDecl GD(D, Type);
221
222  llvm::StringRef Name = getMangledName(GD);
223  if (llvm::GlobalValue *V = GetGlobalValue(Name))
224    return V;
225
226  const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
227  const llvm::FunctionType *FTy =
228    getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
229                               FPT->isVariadic());
230  return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD,
231                                                      /*ForVTable=*/false));
232}
233
234void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
235  // The destructor in a virtual table is always a 'deleting'
236  // destructor, which calls the complete destructor and then uses the
237  // appropriate operator delete.
238  if (D->isVirtual())
239    EmitGlobal(GlobalDecl(D, Dtor_Deleting));
240
241  // The destructor used for destructing this as a most-derived class;
242  // call the base destructor and then destructs any virtual bases.
243  EmitGlobal(GlobalDecl(D, Dtor_Complete));
244
245  // The destructor used for destructing this as a base class; ignores
246  // virtual bases.
247  EmitGlobal(GlobalDecl(D, Dtor_Base));
248}
249
250void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
251                                      CXXDtorType Type) {
252  // The complete destructor is equivalent to the base destructor for
253  // classes with no virtual bases, so try to emit it as an alias.
254  if (Type == Dtor_Complete &&
255      !D->getParent()->getNumVBases() &&
256      !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
257                                GlobalDecl(D, Dtor_Base)))
258    return;
259
260  // The base destructor is equivalent to the base destructor of its
261  // base class if there is exactly one non-virtual base class with a
262  // non-trivial destructor, there are no fields with a non-trivial
263  // destructor, and the body of the destructor is trivial.
264  if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
265    return;
266
267  llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
268  setFunctionLinkage(D, Fn);
269
270  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
271
272  SetFunctionDefinitionAttributes(D, Fn);
273  SetLLVMFunctionAttributesForDefinition(D, Fn);
274}
275
276llvm::GlobalValue *
277CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
278                                      CXXDtorType Type) {
279  GlobalDecl GD(D, Type);
280
281  llvm::StringRef Name = getMangledName(GD);
282  if (llvm::GlobalValue *V = GetGlobalValue(Name))
283    return V;
284
285  const llvm::FunctionType *FTy =
286    getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
287
288  return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD,
289                                                      /*ForVTable=*/false));
290}
291
292static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
293                                     llvm::Value *This, const llvm::Type *Ty) {
294  Ty = Ty->getPointerTo()->getPointerTo();
295
296  llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
297  llvm::Value *VFuncPtr =
298    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
299  return CGF.Builder.CreateLoad(VFuncPtr);
300}
301
302llvm::Value *
303CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
304                                  const llvm::Type *Ty) {
305  MD = MD->getCanonicalDecl();
306  uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
307
308  return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
309}
310
311/// BuildVirtualCall - This routine is to support gcc's kext ABI making
312/// indirect call to virtual functions. It makes the call through indexing
313/// into the vtable.
314llvm::Value *
315CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
316                                  NestedNameSpecifier *Qual,
317                                  llvm::Value *This,
318                                  const llvm::Type *Ty) {
319  llvm::Value *VTable = 0;
320  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
321         "BuildAppleKextVirtualCall - bad Qual kind");
322
323  const Type *QTy = Qual->getAsType();
324  QualType T = QualType(QTy, 0);
325  const RecordType *RT = T->getAs<RecordType>();
326  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
327  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
328
329  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
330    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
331
332  VTable = CGM.getVTables().GetAddrOfVTable(RD);
333  Ty = Ty->getPointerTo()->getPointerTo();
334  VTable = Builder.CreateBitCast(VTable, Ty);
335  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
336  MD = MD->getCanonicalDecl();
337  uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
338  uint64_t AddressPoint =
339    CGM.getVTables().getAddressPoint(BaseSubobject(RD, 0), RD);
340  VTableIndex += AddressPoint;
341  llvm::Value *VFuncPtr =
342    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
343  return CGF.Builder.CreateLoad(VFuncPtr);
344}
345
346/// BuildVirtualCall - This routine makes indirect vtable call for
347/// call to virtual destructors. It returns 0 if it could not do it.
348llvm::Value *
349CodeGenFunction::BuildAppleKextVirtualDestructorCall(
350                                            const CXXDestructorDecl *DD,
351                                            CXXDtorType Type,
352                                            const CXXRecordDecl *RD) {
353  llvm::Value * Callee = 0;
354  const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
355  // FIXME. Dtor_Base dtor is always direct!!
356  // It need be somehow inline expanded into the caller.
357  // -O does that. But need to support -O0 as well.
358  if (MD->isVirtual() && Type != Dtor_Base) {
359    DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
360    // Compute the function type we're calling.
361    const CGFunctionInfo *FInfo =
362    &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
363                                    Dtor_Complete);
364    const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
365    const llvm::Type *Ty
366      = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
367    if (!RD)
368      RD = DD->getParent();
369    llvm::Value *VTable = CGM.getVTables().GetAddrOfVTable(RD);
370    Ty = Ty->getPointerTo()->getPointerTo();
371    VTable = Builder.CreateBitCast(VTable, Ty);
372    uint64_t VTableIndex =
373    CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
374    uint64_t AddressPoint =
375    CGM.getVTables().getAddressPoint(BaseSubobject(RD, 0), RD);
376    VTableIndex += AddressPoint;
377    llvm::Value *VFuncPtr =
378    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
379    Callee = CGF.Builder.CreateLoad(VFuncPtr);
380  }
381  return Callee;
382}
383
384llvm::Value *
385CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
386                                  llvm::Value *This, const llvm::Type *Ty) {
387  DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
388  uint64_t VTableIndex =
389    CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
390
391  return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
392}
393
394