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  // 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  // For exported destructors, we need a full definition.
48  if (D->hasAttr<DLLExportAttr>())
49    return true;
50
51  const CXXRecordDecl *Class = D->getParent();
52
53  // If we need to manipulate a VTT parameter, give up.
54  if (Class->getNumVBases()) {
55    // Extra Credit:  passing extra parameters is perfectly safe
56    // in many calling conventions, so only bail out if the ctor's
57    // calling convention is nonstandard.
58    return true;
59  }
60
61  // If any field has a non-trivial destructor, we have to emit the
62  // destructor separately.
63  for (const auto *I : Class->fields())
64    if (I->getType().isDestructedType())
65      return true;
66
67  // Try to find a unique base class with a non-trivial destructor.
68  const CXXRecordDecl *UniqueBase = nullptr;
69  for (const auto &I : Class->bases()) {
70
71    // We're in the base destructor, so skip virtual bases.
72    if (I.isVirtual()) continue;
73
74    // Skip base classes with trivial destructors.
75    const auto *Base =
76        cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
77    if (Base->hasTrivialDestructor()) continue;
78
79    // If we've already found a base class with a non-trivial
80    // destructor, give up.
81    if (UniqueBase) return true;
82    UniqueBase = Base;
83  }
84
85  // If we didn't find any bases with a non-trivial destructor, then
86  // the base destructor is actually effectively trivial, which can
87  // happen if it was needlessly user-defined or if there are virtual
88  // bases with non-trivial destructors.
89  if (!UniqueBase)
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  // Give up if the calling conventions don't match. We could update the call,
98  // but it is probably not worth it.
99  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
100  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
101      D->getType()->getAs<FunctionType>()->getCallConv())
102    return true;
103
104  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
105                                  GlobalDecl(BaseD, Dtor_Base),
106                                  false);
107}
108
109/// Try to emit a definition as a global alias for another definition.
110/// If \p InEveryTU is true, we know that an equivalent alias can be produced
111/// in every translation unit.
112bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
113                                             GlobalDecl TargetDecl,
114                                             bool InEveryTU) {
115  if (!getCodeGenOpts().CXXCtorDtorAliases)
116    return true;
117
118  // The alias will use the linkage of the referent.  If we can't
119  // support aliases with that linkage, fail.
120  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
121
122  // We can't use an alias if the linkage is not valid for one.
123  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
124    return true;
125
126  llvm::GlobalValue::LinkageTypes TargetLinkage =
127      getFunctionLinkage(TargetDecl);
128
129  // Check if we have it already.
130  StringRef MangledName = getMangledName(AliasDecl);
131  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
132  if (Entry && !Entry->isDeclaration())
133    return false;
134  if (Replacements.count(MangledName))
135    return false;
136
137  // Derive the type for the alias.
138  llvm::PointerType *AliasType
139    = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
140
141  // Find the referent.  Some aliases might require a bitcast, in
142  // which case the caller is responsible for ensuring the soundness
143  // of these semantics.
144  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
145  llvm::Constant *Aliasee = Ref;
146  if (Ref->getType() != AliasType)
147    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
148
149  // Instead of creating as alias to a linkonce_odr, replace all of the uses
150  // of the aliasee.
151  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
152     (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
153      !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
154    // FIXME: An extern template instantiation will create functions with
155    // linkage "AvailableExternally". In libc++, some classes also define
156    // members with attribute "AlwaysInline" and expect no reference to
157    // be generated. It is desirable to reenable this optimisation after
158    // corresponding LLVM changes.
159    Replacements[MangledName] = Aliasee;
160    return false;
161  }
162
163  if (!InEveryTU) {
164    /// If we don't have a definition for the destructor yet, don't
165    /// emit.  We can't emit aliases to declarations; that's just not
166    /// how aliases work.
167    if (Ref->isDeclaration())
168      return true;
169  }
170
171  // Don't create an alias to a linker weak symbol. This avoids producing
172  // different COMDATs in different TUs. Another option would be to
173  // output the alias both for weak_odr and linkonce_odr, but that
174  // requires explicit comdat support in the IL.
175  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
176    return true;
177
178  // Create the alias with no name.
179  auto *Alias = llvm::GlobalAlias::create(AliasType->getElementType(), 0,
180                                          Linkage, "", Aliasee, &getModule());
181
182  // Switch any previous uses to the alias.
183  if (Entry) {
184    assert(Entry->getType() == AliasType &&
185           "declaration exists with different type");
186    Alias->takeName(Entry);
187    Entry->replaceAllUsesWith(Alias);
188    Entry->eraseFromParent();
189  } else {
190    Alias->setName(MangledName);
191  }
192
193  // Finally, set up the alias with its proper name and attributes.
194  SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
195
196  return false;
197}
198
199void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
200                                       CXXCtorType ctorType) {
201  if (!getTarget().getCXXABI().hasConstructorVariants()) {
202    // If there are no constructor variants, always emit the complete destructor.
203    ctorType = Ctor_Complete;
204  } else if (!ctor->getParent()->getNumVBases() &&
205             (ctorType == Ctor_Complete || ctorType == Ctor_Base)) {
206    // The complete constructor is equivalent to the base constructor
207    // for classes with no virtual bases.  Try to emit it as an alias.
208    bool ProducedAlias =
209        !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
210                                  GlobalDecl(ctor, Ctor_Base), true);
211    if (ctorType == Ctor_Complete && ProducedAlias)
212      return;
213  }
214
215  const CGFunctionInfo &fnInfo =
216    getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
217
218  auto *fn = cast<llvm::Function>(
219      GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo, true));
220  setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
221
222  CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
223
224  setFunctionDefinitionAttributes(ctor, fn);
225  SetLLVMFunctionAttributesForDefinition(ctor, fn);
226}
227
228llvm::GlobalValue *
229CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
230                                       CXXCtorType ctorType,
231                                       const CGFunctionInfo *fnInfo,
232                                       bool DontDefer) {
233  GlobalDecl GD(ctor, ctorType);
234
235  StringRef name = getMangledName(GD);
236  if (llvm::GlobalValue *existing = GetGlobalValue(name))
237    return existing;
238
239  if (!fnInfo)
240    fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
241
242  llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
243  return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
244                                                      /*ForVTable=*/false,
245                                                      DontDefer));
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 (!dtor->getParent()->getNumVBases() &&
253      (dtorType == Dtor_Complete || dtorType == Dtor_Base)) {
254    bool ProducedAlias =
255        !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
256                                  GlobalDecl(dtor, Dtor_Base), true);
257    if (ProducedAlias) {
258      if (dtorType == Dtor_Complete)
259        return;
260      if (dtor->isVirtual())
261        getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
262    }
263  }
264
265  // The base destructor is equivalent to the base destructor of its
266  // base class if there is exactly one non-virtual base class with a
267  // non-trivial destructor, there are no fields with a non-trivial
268  // destructor, and the body of the destructor is trivial.
269  if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
270    return;
271
272  const CGFunctionInfo &fnInfo =
273    getTypes().arrangeCXXDestructor(dtor, dtorType);
274
275  auto *fn = cast<llvm::Function>(
276      GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo, nullptr, true));
277  setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
278
279  CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
280
281  setFunctionDefinitionAttributes(dtor, fn);
282  SetLLVMFunctionAttributesForDefinition(dtor, fn);
283}
284
285llvm::GlobalValue *
286CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
287                                      CXXDtorType dtorType,
288                                      const CGFunctionInfo *fnInfo,
289                                      llvm::FunctionType *fnType,
290                                      bool DontDefer) {
291  GlobalDecl GD(dtor, dtorType);
292
293  StringRef name = getMangledName(GD);
294  if (llvm::GlobalValue *existing = GetGlobalValue(name))
295    return existing;
296
297  if (!fnType) {
298    if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
299    fnType = getTypes().GetFunctionType(*fnInfo);
300  }
301  return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
302                                                      /*ForVTable=*/false,
303                                                      DontDefer));
304}
305
306static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
307                                              GlobalDecl GD,
308                                              llvm::Type *Ty,
309                                              const CXXRecordDecl *RD) {
310  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
311         "No kext in Microsoft ABI");
312  GD = GD.getCanonicalDecl();
313  CodeGenModule &CGM = CGF.CGM;
314  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
315  Ty = Ty->getPointerTo()->getPointerTo();
316  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
317  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
318  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
319  uint64_t AddressPoint =
320    CGM.getItaniumVTableContext().getVTableLayout(RD)
321       .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
322  VTableIndex += AddressPoint;
323  llvm::Value *VFuncPtr =
324    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
325  return CGF.Builder.CreateLoad(VFuncPtr);
326}
327
328/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
329/// indirect call to virtual functions. It makes the call through indexing
330/// into the vtable.
331llvm::Value *
332CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
333                                  NestedNameSpecifier *Qual,
334                                  llvm::Type *Ty) {
335  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
336         "BuildAppleKextVirtualCall - bad Qual kind");
337
338  const Type *QTy = Qual->getAsType();
339  QualType T = QualType(QTy, 0);
340  const RecordType *RT = T->getAs<RecordType>();
341  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
342  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
343
344  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
345    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
346
347  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
348}
349
350/// BuildVirtualCall - This routine makes indirect vtable call for
351/// call to virtual destructors. It returns 0 if it could not do it.
352llvm::Value *
353CodeGenFunction::BuildAppleKextVirtualDestructorCall(
354                                            const CXXDestructorDecl *DD,
355                                            CXXDtorType Type,
356                                            const CXXRecordDecl *RD) {
357  const auto *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(DD, Dtor_Complete);
365    llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
366    return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
367  }
368  return nullptr;
369}
370