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