blob: ad30364986785fda8302d1c4d641d389a0835be2 [file] [log] [blame]
Devang Patelcbc7bc92010-10-04 21:15:33 +00001//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
Anders Carlsson87fc5a52008-08-22 16:00:37 +00002//
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
Mike Stump11289f42009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlsson87fc5a52008-08-22 16:00:37 +000015
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000017#include "CGCXXABI.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000018#include "CodeGenFunction.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000021#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000022#include "clang/AST/DeclObjC.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000023#include "clang/AST/Mangle.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/RecordLayout.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000027#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall7f416cc2015-09-08 08:05:57 +000031
John McCallf8ff7b92010-02-23 00:48:20 +000032/// Try to emit a base destructor as an alias to its primary
33/// base-class destructor.
34bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
35 if (!getCodeGenOpts().CXXCtorDtorAliases)
36 return true;
37
Rafael Espindolad967bad2013-11-13 23:20:45 +000038 // Producing an alias to a base class ctor/dtor can degrade debug quality
Alp Tokerf6a24ce2013-12-05 16:25:25 +000039 // as the debugger cannot tell them apart.
Rafael Espindolad967bad2013-11-13 23:20:45 +000040 if (getCodeGenOpts().OptimizationLevel == 0)
41 return true;
42
Naomi Musgrave866af2d2015-09-03 23:02:30 +000043 // 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
John McCallf8ff7b92010-02-23 00:48:20 +000049 // If the destructor doesn't have a trivial body, we have to emit it
50 // separately.
Anders Carlsson9bd7d162011-05-14 23:26:09 +000051 if (!D->hasTrivialBody())
John McCallf8ff7b92010-02-23 00:48:20 +000052 return true;
53
54 const CXXRecordDecl *Class = D->getParent();
55
Kostya Serebryany5f1b4e82014-10-31 19:01:02 +000056 // 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
John McCallf8ff7b92010-02-23 00:48:20 +000061 // 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
John McCall2b3c5532011-02-13 00:46:43 +000069 // If any field has a non-trivial destructor, we have to emit the
70 // destructor separately.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000071 for (const auto *I : Class->fields())
David Blaikie2d7c57e2012-04-30 02:36:29 +000072 if (I->getType().isDestructedType())
John McCall2b3c5532011-02-13 00:46:43 +000073 return true;
John McCallf8ff7b92010-02-23 00:48:20 +000074
75 // Try to find a unique base class with a non-trivial destructor.
Craig Topper8a13c412014-05-21 05:09:00 +000076 const CXXRecordDecl *UniqueBase = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +000077 for (const auto &I : Class->bases()) {
John McCallf8ff7b92010-02-23 00:48:20 +000078
79 // We're in the base destructor, so skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +000080 if (I.isVirtual()) continue;
John McCallf8ff7b92010-02-23 00:48:20 +000081
82 // Skip base classes with trivial destructors.
Rafael Espindola2ae250c2014-05-09 00:08:36 +000083 const auto *Base =
84 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +000085 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);
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000102 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
John McCallf8ff7b92010-02-23 00:48:20 +0000103 return true;
104
Rafael Espindola191b9512014-03-05 21:04:41 +0000105 // Give up if the calling conventions don't match. We could update the call,
106 // but it is probably not worth it.
Rafael Espindola961ba212013-11-09 01:57:21 +0000107 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
Rafael Espindola191b9512014-03-05 21:04:41 +0000108 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
109 D->getType()->getAs<FunctionType>()->getCallConv())
110 return true;
111
John McCallf8ff7b92010-02-23 00:48:20 +0000112 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000113 GlobalDecl(BaseD, Dtor_Base),
114 false);
John McCallf8ff7b92010-02-23 00:48:20 +0000115}
116
John McCalld4324142010-02-19 01:32:20 +0000117/// Try to emit a definition as a global alias for another definition.
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000118/// If \p InEveryTU is true, we know that an equivalent alias can be produced
119/// in every translation unit.
John McCalld4324142010-02-19 01:32:20 +0000120bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000121 GlobalDecl TargetDecl,
122 bool InEveryTU) {
John McCalld4324142010-02-19 01:32:20 +0000123 if (!getCodeGenOpts().CXXCtorDtorAliases)
124 return true;
125
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000126 // The alias will use the linkage of the referent. If we can't
John McCalld4324142010-02-19 01:32:20 +0000127 // support aliases with that linkage, fail.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000128 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
John McCalld4324142010-02-19 01:32:20 +0000129
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000130 // We can't use an alias if the linkage is not valid for one.
131 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola4c489c72010-03-05 01:21:10 +0000132 return true;
133
David Majnemer4b9d9642014-10-24 22:05:27 +0000134 // Don't create a weak alias for a dllexport'd symbol.
135 if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
136 llvm::GlobalValue::isWeakForLinker(Linkage))
137 return true;
138
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000139 llvm::GlobalValue::LinkageTypes TargetLinkage =
140 getFunctionLinkage(TargetDecl);
141
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000142 // Check if we have it already.
143 StringRef MangledName = getMangledName(AliasDecl);
144 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
145 if (Entry && !Entry->isDeclaration())
146 return false;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000147 if (Replacements.count(MangledName))
148 return false;
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000149
John McCallf8ff7b92010-02-23 00:48:20 +0000150 // Derive the type for the alias.
Chris Lattner2192fe52011-07-18 04:24:23 +0000151 llvm::PointerType *AliasType
John McCallf8ff7b92010-02-23 00:48:20 +0000152 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
153
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000154 // Find the referent. Some aliases might require a bitcast, in
John McCallf8ff7b92010-02-23 00:48:20 +0000155 // which case the caller is responsible for ensuring the soundness
156 // of these semantics.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000157 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
Rafael Espindola27c60b52014-06-03 02:42:01 +0000158 llvm::Constant *Aliasee = Ref;
159 if (Ref->getType() != AliasType)
160 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
John McCallf8ff7b92010-02-23 00:48:20 +0000161
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000162 // Instead of creating as alias to a linkonce_odr, replace all of the uses
Rafael Espindolab2633b92014-05-16 19:35:48 +0000163 // of the aliasee.
Joerg Sonnenberger374c2bb2013-11-22 21:34:35 +0000164 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
165 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
166 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000167 // FIXME: An extern template instantiation will create functions with
Joerg Sonnenberger374c2bb2013-11-22 21:34:35 +0000168 // linkage "AvailableExternally". In libc++, some classes also define
169 // members with attribute "AlwaysInline" and expect no reference to
170 // be generated. It is desirable to reenable this optimisation after
171 // corresponding LLVM changes.
Rafael Espindola27c60b52014-06-03 02:42:01 +0000172 Replacements[MangledName] = Aliasee;
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000173 return false;
174 }
175
Rafael Espindola961ba212013-11-09 01:57:21 +0000176 if (!InEveryTU) {
Nico Weberf867c172015-01-12 21:22:27 +0000177 // If we don't have a definition for the destructor yet, don't
178 // emit. We can't emit aliases to declarations; that's just not
179 // how aliases work.
Rafael Espindola27c60b52014-06-03 02:42:01 +0000180 if (Ref->isDeclaration())
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000181 return true;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000182 }
183
Rafael Espindola129d3132013-11-12 22:06:46 +0000184 // Don't create an alias to a linker weak symbol. This avoids producing
185 // different COMDATs in different TUs. Another option would be to
186 // output the alias both for weak_odr and linkonce_odr, but that
187 // requires explicit comdat support in the IL.
188 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
189 return true;
190
John McCalld4324142010-02-19 01:32:20 +0000191 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +0000192 auto *Alias =
193 llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000194
John McCallaea181d2010-02-24 20:32:01 +0000195 // Switch any previous uses to the alias.
John McCalld4324142010-02-19 01:32:20 +0000196 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000197 assert(Entry->getType() == AliasType &&
198 "declaration exists with different type");
John McCall7ec50432010-03-19 23:29:14 +0000199 Alias->takeName(Entry);
John McCalld4324142010-02-19 01:32:20 +0000200 Entry->replaceAllUsesWith(Alias);
201 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +0000202 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000203 Alias->setName(MangledName);
John McCalld4324142010-02-19 01:32:20 +0000204 }
John McCalld4324142010-02-19 01:32:20 +0000205
206 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolae04a17d2014-10-07 13:34:42 +0000207 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
John McCalld4324142010-02-19 01:32:20 +0000208
209 return false;
210}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000211
Rafael Espindola53686182014-09-15 19:34:18 +0000212llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
213 StructorType Type) {
214 const CGFunctionInfo &FnInfo =
215 getTypes().arrangeCXXStructorDeclaration(MD, Type);
216 auto *Fn = cast<llvm::Function>(
Andrey Bokhankocab58582015-08-31 13:20:44 +0000217 getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
218 /*DontDefer=*/true, /*IsForDefinition=*/true));
Rafael Espindola53686182014-09-15 19:34:18 +0000219
220 GlobalDecl GD;
221 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
222 GD = GlobalDecl(DD, toCXXDtorType(Type));
223 } else {
224 const auto *CD = cast<CXXConstructorDecl>(MD);
225 GD = GlobalDecl(CD, toCXXCtorType(Type));
226 }
227
228 setFunctionLinkage(GD, Fn);
Hans Wennborgbb4f9622015-05-28 17:44:56 +0000229 setFunctionDLLStorageClass(GD, Fn);
230
Rafael Espindola53686182014-09-15 19:34:18 +0000231 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
232 setFunctionDefinitionAttributes(MD, Fn);
233 SetLLVMFunctionAttributesForDefinition(MD, Fn);
234 return Fn;
235}
236
Andrey Bokhankocab58582015-08-31 13:20:44 +0000237llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000238 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
Andrey Bokhankocab58582015-08-31 13:20:44 +0000239 llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000240 GlobalDecl GD;
241 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
242 GD = GlobalDecl(CD, toCXXCtorType(Type));
243 } else {
Duncan P. N. Exon Smithd6616ac2015-05-06 22:18:39 +0000244 GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000245 }
John McCalld4324142010-02-19 01:32:20 +0000246
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000247 if (!FnType) {
248 if (!FnInfo)
249 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
250 FnType = getTypes().GetFunctionType(*FnInfo);
251 }
252
Andrey Bokhankocab58582015-08-31 13:20:44 +0000253 return GetOrCreateLLVMFunction(
254 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
255 /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition);
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000256}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000257
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000258static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
259 GlobalDecl GD,
260 llvm::Type *Ty,
261 const CXXRecordDecl *RD) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000262 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
263 "No kext in Microsoft ABI");
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000264 GD = GD.getCanonicalDecl();
265 CodeGenModule &CGM = CGF.CGM;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000266 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000267 Ty = Ty->getPointerTo()->getPointerTo();
268 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
269 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000270 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000271 uint64_t AddressPoint =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000272 CGM.getItaniumVTableContext().getVTableLayout(RD)
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000273 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
274 VTableIndex += AddressPoint;
275 llvm::Value *VFuncPtr =
276 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
John McCall7f416cc2015-09-08 08:05:57 +0000277 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
Anders Carlssone828c362009-11-13 04:45:41 +0000278}
279
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000280/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000281/// indirect call to virtual functions. It makes the call through indexing
282/// into the vtable.
283llvm::Value *
284CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
285 NestedNameSpecifier *Qual,
Chris Lattner2192fe52011-07-18 04:24:23 +0000286 llvm::Type *Ty) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000287 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
288 "BuildAppleKextVirtualCall - bad Qual kind");
289
290 const Type *QTy = Qual->getAsType();
291 QualType T = QualType(QTy, 0);
292 const RecordType *RT = T->getAs<RecordType>();
293 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000294 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
295
296 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000297 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000298
299 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000300}
301
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000302/// BuildVirtualCall - This routine makes indirect vtable call for
303/// call to virtual destructors. It returns 0 if it could not do it.
304llvm::Value *
305CodeGenFunction::BuildAppleKextVirtualDestructorCall(
306 const CXXDestructorDecl *DD,
307 CXXDtorType Type,
308 const CXXRecordDecl *RD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000309 const auto *MD = cast<CXXMethodDecl>(DD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000310 // FIXME. Dtor_Base dtor is always direct!!
311 // It need be somehow inline expanded into the caller.
312 // -O does that. But need to support -O0 as well.
313 if (MD->isVirtual() && Type != Dtor_Base) {
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000314 // Compute the function type we're calling.
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000315 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
316 DD, StructorType::Complete);
John McCalla729c622012-02-17 03:33:10 +0000317 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000318 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000319 }
Craig Topper8a13c412014-05-21 05:09:00 +0000320 return nullptr;
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000321}