blob: e467891d1078882dbe8eddbd7b4ccfe82ff9f574 [file] [log] [blame]
Devang Pateldaaf1de2010-10-04 21:15:33 +00001//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
Anders Carlssone1b29ef2008-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 Stump1eb44332009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlssone1b29ef2008-08-22 16:00:37 +000015
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Charles Davis3a811f12010-05-25 19:52:27 +000017#include "CGCXXABI.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000018#include "CodeGenFunction.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000021#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000022#include "clang/AST/DeclObjC.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000023#include "clang/AST/Mangle.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/AST/RecordLayout.h"
Anders Carlsson6815e942009-09-27 18:58:34 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000027#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000028using namespace clang;
29using namespace CodeGen;
30
John McCallc0bf4622010-02-23 00:48:20 +000031/// 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
Rafael Espindoladc8e9382013-11-13 23:20:45 +000037 // Producing an alias to a base class ctor/dtor can degrade debug quality
Stephen Hines651f13c2014-04-23 16:59:28 -070038 // as the debugger cannot tell them apart.
Rafael Espindoladc8e9382013-11-13 23:20:45 +000039 if (getCodeGenOpts().OptimizationLevel == 0)
40 return true;
41
John McCallc0bf4622010-02-23 00:48:20 +000042 // If the destructor doesn't have a trivial body, we have to emit it
43 // separately.
Anders Carlssonffb945f2011-05-14 23:26:09 +000044 if (!D->hasTrivialBody())
John McCallc0bf4622010-02-23 00:48:20 +000045 return true;
46
47 const CXXRecordDecl *Class = D->getParent();
48
Stephen Hines176edba2014-12-01 14:53:08 -080049 // We are going to instrument this destructor, so give up even if it is
50 // currently empty.
51 if (Class->mayInsertExtraPadding())
52 return true;
53
John McCallc0bf4622010-02-23 00:48:20 +000054 // If we need to manipulate a VTT parameter, give up.
55 if (Class->getNumVBases()) {
56 // Extra Credit: passing extra parameters is perfectly safe
57 // in many calling conventions, so only bail out if the ctor's
58 // calling convention is nonstandard.
59 return true;
60 }
61
John McCall0d70d712011-02-13 00:46:43 +000062 // If any field has a non-trivial destructor, we have to emit the
63 // destructor separately.
Stephen Hines651f13c2014-04-23 16:59:28 -070064 for (const auto *I : Class->fields())
David Blaikie262bc182012-04-30 02:36:29 +000065 if (I->getType().isDestructedType())
John McCall0d70d712011-02-13 00:46:43 +000066 return true;
John McCallc0bf4622010-02-23 00:48:20 +000067
68 // Try to find a unique base class with a non-trivial destructor.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070069 const CXXRecordDecl *UniqueBase = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -070070 for (const auto &I : Class->bases()) {
John McCallc0bf4622010-02-23 00:48:20 +000071
72 // We're in the base destructor, so skip virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -070073 if (I.isVirtual()) continue;
John McCallc0bf4622010-02-23 00:48:20 +000074
75 // Skip base classes with trivial destructors.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070076 const auto *Base =
77 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
John McCallc0bf4622010-02-23 00:48:20 +000078 if (Base->hasTrivialDestructor()) continue;
79
80 // If we've already found a base class with a non-trivial
81 // destructor, give up.
82 if (UniqueBase) return true;
83 UniqueBase = Base;
84 }
85
86 // If we didn't find any bases with a non-trivial destructor, then
87 // the base destructor is actually effectively trivial, which can
88 // happen if it was needlessly user-defined or if there are virtual
89 // bases with non-trivial destructors.
90 if (!UniqueBase)
91 return true;
92
93 // If the base is at a non-zero offset, give up.
94 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
Benjamin Kramerd4f51982012-07-04 18:45:14 +000095 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
John McCallc0bf4622010-02-23 00:48:20 +000096 return true;
97
Stephen Hines651f13c2014-04-23 16:59:28 -070098 // Give up if the calling conventions don't match. We could update the call,
99 // but it is probably not worth it.
Rafael Espindola6e84e922013-11-09 01:57:21 +0000100 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
Stephen Hines651f13c2014-04-23 16:59:28 -0700101 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
102 D->getType()->getAs<FunctionType>()->getCallConv())
103 return true;
104
John McCallc0bf4622010-02-23 00:48:20 +0000105 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
Rafael Espindola71fdc122013-11-04 18:38:59 +0000106 GlobalDecl(BaseD, Dtor_Base),
107 false);
John McCallc0bf4622010-02-23 00:48:20 +0000108}
109
John McCalld46f9852010-02-19 01:32:20 +0000110/// Try to emit a definition as a global alias for another definition.
Rafael Espindola71fdc122013-11-04 18:38:59 +0000111/// If \p InEveryTU is true, we know that an equivalent alias can be produced
112/// in every translation unit.
John McCalld46f9852010-02-19 01:32:20 +0000113bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
Rafael Espindola71fdc122013-11-04 18:38:59 +0000114 GlobalDecl TargetDecl,
115 bool InEveryTU) {
John McCalld46f9852010-02-19 01:32:20 +0000116 if (!getCodeGenOpts().CXXCtorDtorAliases)
117 return true;
118
Stephen Hines651f13c2014-04-23 16:59:28 -0700119 // The alias will use the linkage of the referent. If we can't
John McCalld46f9852010-02-19 01:32:20 +0000120 // support aliases with that linkage, fail.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000121 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
John McCalld46f9852010-02-19 01:32:20 +0000122
Rafael Espindola71fdc122013-11-04 18:38:59 +0000123 // We can't use an alias if the linkage is not valid for one.
124 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
Rafael Espindolabc6afd12010-03-05 01:21:10 +0000125 return true;
126
Stephen Hines176edba2014-12-01 14:53:08 -0800127 // Don't create a weak alias for a dllexport'd symbol.
128 if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
129 llvm::GlobalValue::isWeakForLinker(Linkage))
130 return true;
131
Rafael Espindola61a0a752013-11-05 21:37:29 +0000132 llvm::GlobalValue::LinkageTypes TargetLinkage =
133 getFunctionLinkage(TargetDecl);
134
Rafael Espindola71fdc122013-11-04 18:38:59 +0000135 // Check if we have it already.
136 StringRef MangledName = getMangledName(AliasDecl);
137 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
138 if (Entry && !Entry->isDeclaration())
139 return false;
Rafael Espindola61a0a752013-11-05 21:37:29 +0000140 if (Replacements.count(MangledName))
141 return false;
Rafael Espindola71fdc122013-11-04 18:38:59 +0000142
John McCallc0bf4622010-02-23 00:48:20 +0000143 // Derive the type for the alias.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000144 llvm::PointerType *AliasType
John McCallc0bf4622010-02-23 00:48:20 +0000145 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
146
Stephen Hines651f13c2014-04-23 16:59:28 -0700147 // Find the referent. Some aliases might require a bitcast, in
John McCallc0bf4622010-02-23 00:48:20 +0000148 // which case the caller is responsible for ensuring the soundness
149 // of these semantics.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700150 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700151 llvm::Constant *Aliasee = Ref;
152 if (Ref->getType() != AliasType)
153 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
John McCallc0bf4622010-02-23 00:48:20 +0000154
Rafael Espindola0171c6b2013-11-08 22:59:46 +0000155 // Instead of creating as alias to a linkonce_odr, replace all of the uses
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700156 // of the aliasee.
Bill Wendlingcc057782013-11-25 05:40:33 +0000157 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
158 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
159 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700160 // FIXME: An extern template instantiation will create functions with
Bill Wendlingcc057782013-11-25 05:40:33 +0000161 // linkage "AvailableExternally". In libc++, some classes also define
162 // members with attribute "AlwaysInline" and expect no reference to
163 // be generated. It is desirable to reenable this optimisation after
164 // corresponding LLVM changes.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700165 Replacements[MangledName] = Aliasee;
Rafael Espindola0171c6b2013-11-08 22:59:46 +0000166 return false;
167 }
168
Rafael Espindola6e84e922013-11-09 01:57:21 +0000169 if (!InEveryTU) {
170 /// If we don't have a definition for the destructor yet, don't
171 /// emit. We can't emit aliases to declarations; that's just not
172 /// how aliases work.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700173 if (Ref->isDeclaration())
Rafael Espindola61a0a752013-11-05 21:37:29 +0000174 return true;
Rafael Espindola61a0a752013-11-05 21:37:29 +0000175 }
176
Rafael Espindola610616c2013-11-12 22:06:46 +0000177 // Don't create an alias to a linker weak symbol. This avoids producing
178 // different COMDATs in different TUs. Another option would be to
179 // output the alias both for weak_odr and linkonce_odr, but that
180 // requires explicit comdat support in the IL.
181 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
182 return true;
183
John McCalld46f9852010-02-19 01:32:20 +0000184 // Create the alias with no name.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700185 auto *Alias = llvm::GlobalAlias::create(AliasType->getElementType(), 0,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700186 Linkage, "", Aliasee, &getModule());
John McCalld46f9852010-02-19 01:32:20 +0000187
John McCall1962bee2010-02-24 20:32:01 +0000188 // Switch any previous uses to the alias.
John McCalld46f9852010-02-19 01:32:20 +0000189 if (Entry) {
John McCall1962bee2010-02-24 20:32:01 +0000190 assert(Entry->getType() == AliasType &&
191 "declaration exists with different type");
John McCallf746aa62010-03-19 23:29:14 +0000192 Alias->takeName(Entry);
John McCalld46f9852010-02-19 01:32:20 +0000193 Entry->replaceAllUsesWith(Alias);
194 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +0000195 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +0000196 Alias->setName(MangledName);
John McCalld46f9852010-02-19 01:32:20 +0000197 }
John McCalld46f9852010-02-19 01:32:20 +0000198
199 // Finally, set up the alias with its proper name and attributes.
Stephen Hines176edba2014-12-01 14:53:08 -0800200 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
John McCalld46f9852010-02-19 01:32:20 +0000201
202 return false;
203}
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000204
Stephen Hines176edba2014-12-01 14:53:08 -0800205llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
206 StructorType Type) {
207 const CGFunctionInfo &FnInfo =
208 getTypes().arrangeCXXStructorDeclaration(MD, Type);
209 auto *Fn = cast<llvm::Function>(
210 getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
211
212 GlobalDecl GD;
213 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
214 GD = GlobalDecl(DD, toCXXDtorType(Type));
215 } else {
216 const auto *CD = cast<CXXConstructorDecl>(MD);
217 GD = GlobalDecl(CD, toCXXCtorType(Type));
Rafael Espindola71fdc122013-11-04 18:38:59 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Stephen Hines176edba2014-12-01 14:53:08 -0800220 setFunctionLinkage(GD, Fn);
221 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
222 setFunctionDefinitionAttributes(MD, Fn);
223 SetLLVMFunctionAttributesForDefinition(MD, Fn);
224 return Fn;
Anders Carlsson27ae5362009-04-17 01:58:57 +0000225}
226
Stephen Hines176edba2014-12-01 14:53:08 -0800227llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
228 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
229 llvm::FunctionType *FnType, bool DontDefer) {
230 GlobalDecl GD;
231 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
232 GD = GlobalDecl(CD, toCXXCtorType(Type));
233 } else {
234 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
235 GD = GlobalDecl(DD, toCXXDtorType(Type));
Rafael Espindola71fdc122013-11-04 18:38:59 +0000236 }
John McCalld46f9852010-02-19 01:32:20 +0000237
Stephen Hines176edba2014-12-01 14:53:08 -0800238 StringRef Name = getMangledName(GD);
239 if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
240 return Existing;
John McCallc0bf4622010-02-23 00:48:20 +0000241
Stephen Hines176edba2014-12-01 14:53:08 -0800242 if (!FnType) {
243 if (!FnInfo)
244 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
245 FnType = getTypes().GetFunctionType(*FnInfo);
Reid Klecknera4130ba2013-07-22 13:51:44 +0000246 }
Stephen Hines176edba2014-12-01 14:53:08 -0800247
248 return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
Stephen Hines651f13c2014-04-23 16:59:28 -0700249 /*ForVTable=*/false,
250 DontDefer));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000251}
252
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000253static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
254 GlobalDecl GD,
255 llvm::Type *Ty,
256 const CXXRecordDecl *RD) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000257 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
258 "No kext in Microsoft ABI");
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000259 GD = GD.getCanonicalDecl();
260 CodeGenModule &CGM = CGF.CGM;
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000261 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000262 Ty = Ty->getPointerTo()->getPointerTo();
263 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
264 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +0000265 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000266 uint64_t AddressPoint =
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +0000267 CGM.getItaniumVTableContext().getVTableLayout(RD)
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000268 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
269 VTableIndex += AddressPoint;
270 llvm::Value *VFuncPtr =
271 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
Anders Carlsson566abee2009-11-13 04:45:41 +0000272 return CGF.Builder.CreateLoad(VFuncPtr);
273}
274
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000275/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
Fariborz Jahanian27262672011-01-20 17:19:02 +0000276/// indirect call to virtual functions. It makes the call through indexing
277/// into the vtable.
278llvm::Value *
279CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
280 NestedNameSpecifier *Qual,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000281 llvm::Type *Ty) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000282 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
283 "BuildAppleKextVirtualCall - bad Qual kind");
284
285 const Type *QTy = Qual->getAsType();
286 QualType T = QualType(QTy, 0);
287 const RecordType *RT = T->getAs<RecordType>();
288 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700289 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
290
291 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000292 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000293
294 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
Fariborz Jahanian27262672011-01-20 17:19:02 +0000295}
296
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000297/// BuildVirtualCall - This routine makes indirect vtable call for
298/// call to virtual destructors. It returns 0 if it could not do it.
299llvm::Value *
300CodeGenFunction::BuildAppleKextVirtualDestructorCall(
301 const CXXDestructorDecl *DD,
302 CXXDtorType Type,
303 const CXXRecordDecl *RD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700304 const auto *MD = cast<CXXMethodDecl>(DD);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000305 // FIXME. Dtor_Base dtor is always direct!!
306 // It need be somehow inline expanded into the caller.
307 // -O does that. But need to support -O0 as well.
308 if (MD->isVirtual() && Type != Dtor_Base) {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000309 // Compute the function type we're calling.
Stephen Hines176edba2014-12-01 14:53:08 -0800310 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
311 DD, StructorType::Complete);
John McCallde5d3c72012-02-17 03:33:10 +0000312 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000313 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000314 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700315 return nullptr;
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000316}