1 //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation.
12 //===----------------------------------------------------------------------===//
14 // We might split this into multiple files if it gets too unwieldy
16 #include "CodeGenModule.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"
28 using namespace clang;
29 using namespace CodeGen;
31 /// Try to emit a base destructor as an alias to its primary
32 /// base-class destructor.
33 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
34 if (!getCodeGenOpts().CXXCtorDtorAliases)
37 // Producing an alias to a base class ctor/dtor can degrade debug quality
38 // as the debugger cannot tell them appart.
39 if (getCodeGenOpts().OptimizationLevel == 0)
42 // If the destructor doesn't have a trivial body, we have to emit it
44 if (!D->hasTrivialBody())
47 const CXXRecordDecl *Class = D->getParent();
49 // If we need to manipulate a VTT parameter, give up.
50 if (Class->getNumVBases()) {
51 // Extra Credit: passing extra parameters is perfectly safe
52 // in many calling conventions, so only bail out if the ctor's
53 // calling convention is nonstandard.
57 // If any field has a non-trivial destructor, we have to emit the
58 // destructor separately.
59 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
60 E = Class->field_end(); I != E; ++I)
61 if (I->getType().isDestructedType())
64 // Try to find a unique base class with a non-trivial destructor.
65 const CXXRecordDecl *UniqueBase = 0;
66 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
67 E = Class->bases_end(); I != E; ++I) {
69 // We're in the base destructor, so skip virtual bases.
70 if (I->isVirtual()) continue;
72 // Skip base classes with trivial destructors.
73 const CXXRecordDecl *Base
74 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
75 if (Base->hasTrivialDestructor()) continue;
77 // If we've already found a base class with a non-trivial
78 // destructor, give up.
79 if (UniqueBase) return true;
83 // If we didn't find any bases with a non-trivial destructor, then
84 // the base destructor is actually effectively trivial, which can
85 // happen if it was needlessly user-defined or if there are virtual
86 // bases with non-trivial destructors.
90 // If the base is at a non-zero offset, give up.
91 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
92 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
95 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
96 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
97 GlobalDecl(BaseD, Dtor_Base),
101 /// Try to emit a definition as a global alias for another definition.
102 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
103 /// in every translation unit.
104 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
105 GlobalDecl TargetDecl,
107 if (!getCodeGenOpts().CXXCtorDtorAliases)
110 // The alias will use the linkage of the referrent. If we can't
111 // support aliases with that linkage, fail.
112 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
114 // We can't use an alias if the linkage is not valid for one.
115 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
118 llvm::GlobalValue::LinkageTypes TargetLinkage =
119 getFunctionLinkage(TargetDecl);
121 // Check if we have it already.
122 StringRef MangledName = getMangledName(AliasDecl);
123 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
124 if (Entry && !Entry->isDeclaration())
126 if (Replacements.count(MangledName))
129 // Derive the type for the alias.
130 llvm::PointerType *AliasType
131 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
133 // Find the referrent. Some aliases might require a bitcast, in
134 // which case the caller is responsible for ensuring the soundness
135 // of these semantics.
136 llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
137 llvm::Constant *Aliasee = Ref;
138 if (Ref->getType() != AliasType)
139 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
141 // Instead of creating as alias to a linkonce_odr, replace all of the uses
143 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
144 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
145 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
146 // FIXME: An extern template instanciation will create functions with
147 // linkage "AvailableExternally". In libc++, some classes also define
148 // members with attribute "AlwaysInline" and expect no reference to
149 // be generated. It is desirable to reenable this optimisation after
150 // corresponding LLVM changes.
151 Replacements[MangledName] = Aliasee;
156 /// If we don't have a definition for the destructor yet, don't
157 /// emit. We can't emit aliases to declarations; that's just not
158 /// how aliases work.
159 if (Ref->isDeclaration())
163 // Don't create an alias to a linker weak symbol. This avoids producing
164 // different COMDATs in different TUs. Another option would be to
165 // output the alias both for weak_odr and linkonce_odr, but that
166 // requires explicit comdat support in the IL.
167 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
170 // Create the alias with no name.
171 llvm::GlobalAlias *Alias =
172 new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
174 // Switch any previous uses to the alias.
176 assert(Entry->getType() == AliasType &&
177 "declaration exists with different type");
178 Alias->takeName(Entry);
179 Entry->replaceAllUsesWith(Alias);
180 Entry->eraseFromParent();
182 Alias->setName(MangledName);
185 // Finally, set up the alias with its proper name and attributes.
186 SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
191 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
192 CXXCtorType ctorType) {
193 // The complete constructor is equivalent to the base constructor
194 // for classes with no virtual bases. Try to emit it as an alias.
195 if (getTarget().getCXXABI().hasConstructorVariants() &&
196 !ctor->getParent()->getNumVBases() &&
197 (ctorType == Ctor_Complete || ctorType == Ctor_Base)) {
199 !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
200 GlobalDecl(ctor, Ctor_Base), true);
201 if (ctorType == Ctor_Complete && ProducedAlias)
205 const CGFunctionInfo &fnInfo =
206 getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
209 cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
210 setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
212 CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
214 SetFunctionDefinitionAttributes(ctor, fn);
215 SetLLVMFunctionAttributesForDefinition(ctor, fn);
219 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
220 CXXCtorType ctorType,
221 const CGFunctionInfo *fnInfo) {
222 GlobalDecl GD(ctor, ctorType);
224 StringRef name = getMangledName(GD);
225 if (llvm::GlobalValue *existing = GetGlobalValue(name))
229 fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
231 llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
232 return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
233 /*ForVTable=*/false));
236 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
237 CXXDtorType dtorType) {
238 // The complete destructor is equivalent to the base destructor for
239 // classes with no virtual bases, so try to emit it as an alias.
240 if (!dtor->getParent()->getNumVBases() &&
241 (dtorType == Dtor_Complete || dtorType == Dtor_Base)) {
243 !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
244 GlobalDecl(dtor, Dtor_Base), true);
246 if (dtorType == Dtor_Complete)
248 if (dtor->isVirtual())
249 getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
253 // The base destructor is equivalent to the base destructor of its
254 // base class if there is exactly one non-virtual base class with a
255 // non-trivial destructor, there are no fields with a non-trivial
256 // destructor, and the body of the destructor is trivial.
257 if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
260 const CGFunctionInfo &fnInfo =
261 getTypes().arrangeCXXDestructor(dtor, dtorType);
264 cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
265 setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
267 CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
269 SetFunctionDefinitionAttributes(dtor, fn);
270 SetLLVMFunctionAttributesForDefinition(dtor, fn);
274 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
275 CXXDtorType dtorType,
276 const CGFunctionInfo *fnInfo,
277 llvm::FunctionType *fnType) {
278 GlobalDecl GD(dtor, dtorType);
280 StringRef name = getMangledName(GD);
281 if (llvm::GlobalValue *existing = GetGlobalValue(name))
285 if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
286 fnType = getTypes().GetFunctionType(*fnInfo);
288 return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
289 /*ForVTable=*/false));
292 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
295 const CXXRecordDecl *RD) {
296 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
297 "No kext in Microsoft ABI");
298 GD = GD.getCanonicalDecl();
299 CodeGenModule &CGM = CGF.CGM;
300 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
301 Ty = Ty->getPointerTo()->getPointerTo();
302 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
303 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
304 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
305 uint64_t AddressPoint =
306 CGM.getItaniumVTableContext().getVTableLayout(RD)
307 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
308 VTableIndex += AddressPoint;
309 llvm::Value *VFuncPtr =
310 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
311 return CGF.Builder.CreateLoad(VFuncPtr);
314 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
315 /// indirect call to virtual functions. It makes the call through indexing
318 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
319 NestedNameSpecifier *Qual,
321 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
322 "BuildAppleKextVirtualCall - bad Qual kind");
324 const Type *QTy = Qual->getAsType();
325 QualType T = QualType(QTy, 0);
326 const RecordType *RT = T->getAs<RecordType>();
327 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
328 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
330 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
331 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
333 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
336 /// BuildVirtualCall - This routine makes indirect vtable call for
337 /// call to virtual destructors. It returns 0 if it could not do it.
339 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
340 const CXXDestructorDecl *DD,
342 const CXXRecordDecl *RD) {
343 const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
344 // FIXME. Dtor_Base dtor is always direct!!
345 // It need be somehow inline expanded into the caller.
346 // -O does that. But need to support -O0 as well.
347 if (MD->isVirtual() && Type != Dtor_Base) {
348 // Compute the function type we're calling.
349 const CGFunctionInfo &FInfo =
350 CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete);
351 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
352 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);