blob: 40f1bc426ff74001a8c769002bf6a19ca7d4bb81 [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +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
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000134 llvm::GlobalValue::LinkageTypes TargetLinkage =
135 getFunctionLinkage(TargetDecl);
136
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000137 // Check if we have it already.
138 StringRef MangledName = getMangledName(AliasDecl);
139 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
140 if (Entry && !Entry->isDeclaration())
141 return false;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000142 if (Replacements.count(MangledName))
143 return false;
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000144
John McCallf8ff7b92010-02-23 00:48:20 +0000145 // Derive the type for the alias.
David Blaikie2a791d72015-09-14 18:38:22 +0000146 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
147 llvm::PointerType *AliasType = AliasValueType->getPointerTo();
John McCallf8ff7b92010-02-23 00:48:20 +0000148
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000149 // Find the referent. Some aliases might require a bitcast, in
John McCallf8ff7b92010-02-23 00:48:20 +0000150 // which case the caller is responsible for ensuring the soundness
151 // of these semantics.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000152 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
Rafael Espindola27c60b52014-06-03 02:42:01 +0000153 llvm::Constant *Aliasee = Ref;
154 if (Ref->getType() != AliasType)
155 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
John McCallf8ff7b92010-02-23 00:48:20 +0000156
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000157 // Instead of creating as alias to a linkonce_odr, replace all of the uses
Rafael Espindolab2633b92014-05-16 19:35:48 +0000158 // of the aliasee.
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +0000159 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
160 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
161 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
162 // FIXME: An extern template instantiation will create functions with
163 // linkage "AvailableExternally". In libc++, some classes also define
164 // members with attribute "AlwaysInline" and expect no reference to
165 // be generated. It is desirable to reenable this optimisation after
166 // corresponding LLVM changes.
Yaron Kerenf8adb382016-02-07 12:44:35 +0000167 addReplacement(MangledName, Aliasee);
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000168 return false;
169 }
170
Reid Kleckner489cfe12015-11-10 22:23:58 +0000171 // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
172 // template instantiation or a dllexported class, avoid forming it on COFF.
173 // A COFF weak external alias cannot satisfy a normal undefined symbol
174 // reference from another TU. The other TU must also mark the referenced
175 // symbol as weak, which we cannot rely on.
176 if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
177 getTriple().isOSBinFormatCOFF()) {
178 return true;
179 }
180
Rafael Espindola961ba212013-11-09 01:57:21 +0000181 if (!InEveryTU) {
Nico Weberf867c172015-01-12 21:22:27 +0000182 // If we don't have a definition for the destructor yet, don't
183 // emit. We can't emit aliases to declarations; that's just not
184 // how aliases work.
Rafael Espindola27c60b52014-06-03 02:42:01 +0000185 if (Ref->isDeclaration())
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000186 return true;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000187 }
188
Rafael Espindola129d3132013-11-12 22:06:46 +0000189 // Don't create an alias to a linker weak symbol. This avoids producing
190 // different COMDATs in different TUs. Another option would be to
191 // output the alias both for weak_odr and linkonce_odr, but that
192 // requires explicit comdat support in the IL.
193 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
194 return true;
195
John McCalld4324142010-02-19 01:32:20 +0000196 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +0000197 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
198 Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000199
John McCallaea181d2010-02-24 20:32:01 +0000200 // Switch any previous uses to the alias.
John McCalld4324142010-02-19 01:32:20 +0000201 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000202 assert(Entry->getType() == AliasType &&
203 "declaration exists with different type");
John McCall7ec50432010-03-19 23:29:14 +0000204 Alias->takeName(Entry);
John McCalld4324142010-02-19 01:32:20 +0000205 Entry->replaceAllUsesWith(Alias);
206 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +0000207 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000208 Alias->setName(MangledName);
John McCalld4324142010-02-19 01:32:20 +0000209 }
John McCalld4324142010-02-19 01:32:20 +0000210
211 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolae04a17d2014-10-07 13:34:42 +0000212 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
John McCalld4324142010-02-19 01:32:20 +0000213
214 return false;
215}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000216
Rafael Espindola53686182014-09-15 19:34:18 +0000217llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
218 StructorType Type) {
219 const CGFunctionInfo &FnInfo =
220 getTypes().arrangeCXXStructorDeclaration(MD, Type);
221 auto *Fn = cast<llvm::Function>(
Andrey Bokhankocab58582015-08-31 13:20:44 +0000222 getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
223 /*DontDefer=*/true, /*IsForDefinition=*/true));
Rafael Espindola53686182014-09-15 19:34:18 +0000224
225 GlobalDecl GD;
226 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
227 GD = GlobalDecl(DD, toCXXDtorType(Type));
228 } else {
229 const auto *CD = cast<CXXConstructorDecl>(MD);
230 GD = GlobalDecl(CD, toCXXCtorType(Type));
231 }
232
233 setFunctionLinkage(GD, Fn);
Hans Wennborgbb4f9622015-05-28 17:44:56 +0000234 setFunctionDLLStorageClass(GD, Fn);
235
Rafael Espindola53686182014-09-15 19:34:18 +0000236 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
237 setFunctionDefinitionAttributes(MD, Fn);
238 SetLLVMFunctionAttributesForDefinition(MD, Fn);
239 return Fn;
240}
241
Andrey Bokhankocab58582015-08-31 13:20:44 +0000242llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000243 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
Andrey Bokhankocab58582015-08-31 13:20:44 +0000244 llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000245 GlobalDecl GD;
246 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
247 GD = GlobalDecl(CD, toCXXCtorType(Type));
248 } else {
Duncan P. N. Exon Smithd6616ac2015-05-06 22:18:39 +0000249 GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000250 }
John McCalld4324142010-02-19 01:32:20 +0000251
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000252 if (!FnType) {
253 if (!FnInfo)
254 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
255 FnType = getTypes().GetFunctionType(*FnInfo);
256 }
257
Andrey Bokhankocab58582015-08-31 13:20:44 +0000258 return GetOrCreateLLVMFunction(
259 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
260 /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition);
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000261}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000262
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000263static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
264 GlobalDecl GD,
265 llvm::Type *Ty,
266 const CXXRecordDecl *RD) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000267 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
268 "No kext in Microsoft ABI");
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000269 GD = GD.getCanonicalDecl();
270 CodeGenModule &CGM = CGF.CGM;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000271 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000272 Ty = Ty->getPointerTo()->getPointerTo();
273 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
274 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000275 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000276 uint64_t AddressPoint =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000277 CGM.getItaniumVTableContext().getVTableLayout(RD)
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000278 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
279 VTableIndex += AddressPoint;
280 llvm::Value *VFuncPtr =
281 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
John McCall7f416cc2015-09-08 08:05:57 +0000282 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
Anders Carlssone828c362009-11-13 04:45:41 +0000283}
284
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000285/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000286/// indirect call to virtual functions. It makes the call through indexing
287/// into the vtable.
288llvm::Value *
289CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
290 NestedNameSpecifier *Qual,
Chris Lattner2192fe52011-07-18 04:24:23 +0000291 llvm::Type *Ty) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000292 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
293 "BuildAppleKextVirtualCall - bad Qual kind");
294
295 const Type *QTy = Qual->getAsType();
296 QualType T = QualType(QTy, 0);
297 const RecordType *RT = T->getAs<RecordType>();
298 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000299 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
300
301 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000302 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000303
304 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000305}
306
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000307/// BuildVirtualCall - This routine makes indirect vtable call for
308/// call to virtual destructors. It returns 0 if it could not do it.
309llvm::Value *
310CodeGenFunction::BuildAppleKextVirtualDestructorCall(
311 const CXXDestructorDecl *DD,
312 CXXDtorType Type,
313 const CXXRecordDecl *RD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000314 const auto *MD = cast<CXXMethodDecl>(DD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000315 // FIXME. Dtor_Base dtor is always direct!!
316 // It need be somehow inline expanded into the caller.
317 // -O does that. But need to support -O0 as well.
318 if (MD->isVirtual() && Type != Dtor_Base) {
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000319 // Compute the function type we're calling.
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000320 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
321 DD, StructorType::Complete);
John McCalla729c622012-02-17 03:33:10 +0000322 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000323 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000324 }
Craig Topper8a13c412014-05-21 05:09:00 +0000325 return nullptr;
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000326}