blob: cd5d64697d156cbb293f1f41d0eb3042687e6718 [file] [log] [blame]
Anders Carlssone1b29ef2008-08-22 16:00:37 +00001//===--- CGDecl.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
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
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson283a0622009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson6815e942009-09-27 18:58:34 +000024#include "clang/AST/StmtCXX.h"
John McCalld46f9852010-02-19 01:32:20 +000025#include "clang/CodeGen/CodeGenOptions.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000026#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000027using namespace clang;
28using namespace CodeGen;
29
John McCallc0bf4622010-02-23 00:48:20 +000030/// Determines whether the given function has a trivial body that does
31/// not require any specific codegen.
32static bool HasTrivialBody(const FunctionDecl *FD) {
33 Stmt *S = FD->getBody();
34 if (!S)
35 return true;
36 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
37 return true;
38 return false;
39}
40
41/// Try to emit a base destructor as an alias to its primary
42/// base-class destructor.
43bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
44 if (!getCodeGenOpts().CXXCtorDtorAliases)
45 return true;
46
47 // If the destructor doesn't have a trivial body, we have to emit it
48 // separately.
49 if (!HasTrivialBody(D))
50 return true;
51
52 const CXXRecordDecl *Class = D->getParent();
53
54 // 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
62 // If any fields have a non-trivial destructor, we have to emit it
63 // separately.
64 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
65 E = Class->field_end(); I != E; ++I)
66 if (const RecordType *RT = (*I)->getType()->getAs<RecordType>())
67 if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
68 return true;
69
70 // Try to find a unique base class with a non-trivial destructor.
71 const CXXRecordDecl *UniqueBase = 0;
72 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
73 E = Class->bases_end(); I != E; ++I) {
74
75 // We're in the base destructor, so skip virtual bases.
76 if (I->isVirtual()) continue;
77
78 // Skip base classes with trivial destructors.
79 const CXXRecordDecl *Base
80 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
81 if (Base->hasTrivialDestructor()) continue;
82
83 // If we've already found a base class with a non-trivial
84 // destructor, give up.
85 if (UniqueBase) return true;
86 UniqueBase = Base;
87 }
88
89 // If we didn't find any bases with a non-trivial destructor, then
90 // the base destructor is actually effectively trivial, which can
91 // happen if it was needlessly user-defined or if there are virtual
92 // bases with non-trivial destructors.
93 if (!UniqueBase)
94 return true;
95
John McCall9a708462010-03-03 03:40:11 +000096 /// If we don't have a definition for the destructor yet, don't
97 /// emit. We can't emit aliases to declarations; that's just not
98 /// how aliases work.
99 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(getContext());
100 if (!BaseD->isImplicit() && !BaseD->getBody())
101 return true;
102
John McCallc0bf4622010-02-23 00:48:20 +0000103 // If the base is at a non-zero offset, give up.
104 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
105 if (ClassLayout.getBaseClassOffset(UniqueBase) != 0)
106 return true;
107
John McCallc0bf4622010-02-23 00:48:20 +0000108 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
109 GlobalDecl(BaseD, Dtor_Base));
110}
111
Rafael Espindolabc6afd12010-03-05 01:21:10 +0000112static bool isWeakForLinker(llvm::GlobalValue::LinkageTypes Linkage) {
113 return (Linkage == llvm::GlobalValue::AvailableExternallyLinkage ||
114 Linkage == llvm::GlobalValue::WeakAnyLinkage ||
115 Linkage == llvm::GlobalValue::WeakODRLinkage ||
116 Linkage == llvm::GlobalValue::LinkOnceAnyLinkage ||
117 Linkage == llvm::GlobalValue::LinkOnceODRLinkage ||
118 Linkage == llvm::GlobalValue::CommonLinkage ||
119 Linkage == llvm::GlobalValue::ExternalWeakLinkage);
120}
121
John McCalld46f9852010-02-19 01:32:20 +0000122/// Try to emit a definition as a global alias for another definition.
123bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
124 GlobalDecl TargetDecl) {
125 if (!getCodeGenOpts().CXXCtorDtorAliases)
126 return true;
127
John McCalld46f9852010-02-19 01:32:20 +0000128 // The alias will use the linkage of the referrent. If we can't
129 // support aliases with that linkage, fail.
130 llvm::GlobalValue::LinkageTypes Linkage
131 = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
132
133 switch (Linkage) {
134 // We can definitely emit aliases to definitions with external linkage.
135 case llvm::GlobalValue::ExternalLinkage:
136 case llvm::GlobalValue::ExternalWeakLinkage:
137 break;
138
139 // Same with local linkage.
140 case llvm::GlobalValue::InternalLinkage:
141 case llvm::GlobalValue::PrivateLinkage:
142 case llvm::GlobalValue::LinkerPrivateLinkage:
143 break;
144
145 // We should try to support linkonce linkages.
146 case llvm::GlobalValue::LinkOnceAnyLinkage:
147 case llvm::GlobalValue::LinkOnceODRLinkage:
148 return true;
149
150 // Other linkages will probably never be supported.
151 default:
152 return true;
153 }
154
Rafael Espindolabc6afd12010-03-05 01:21:10 +0000155 llvm::GlobalValue::LinkageTypes TargetLinkage
156 = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl()));
157
158 if (isWeakForLinker(TargetLinkage))
159 return true;
160
John McCallc0bf4622010-02-23 00:48:20 +0000161 // Derive the type for the alias.
162 const llvm::PointerType *AliasType
163 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
164
John McCallc0bf4622010-02-23 00:48:20 +0000165 // Find the referrent. Some aliases might require a bitcast, in
166 // which case the caller is responsible for ensuring the soundness
167 // of these semantics.
168 llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
169 llvm::Constant *Aliasee = Ref;
170 if (Ref->getType() != AliasType)
171 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
172
John McCalld46f9852010-02-19 01:32:20 +0000173 // Create the alias with no name.
174 llvm::GlobalAlias *Alias =
John McCallc0bf4622010-02-23 00:48:20 +0000175 new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
John McCalld46f9852010-02-19 01:32:20 +0000176
John McCall1962bee2010-02-24 20:32:01 +0000177 // Switch any previous uses to the alias.
178 const char *MangledName = getMangledName(AliasDecl);
179 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
John McCalld46f9852010-02-19 01:32:20 +0000180 if (Entry) {
John McCall1962bee2010-02-24 20:32:01 +0000181 assert(Entry->isDeclaration() && "definition already exists for alias");
182 assert(Entry->getType() == AliasType &&
183 "declaration exists with different type");
John McCalld46f9852010-02-19 01:32:20 +0000184 Entry->replaceAllUsesWith(Alias);
185 Entry->eraseFromParent();
186 }
187 Entry = Alias;
188
189 // Finally, set up the alias with its proper name and attributes.
190 Alias->setName(MangledName);
191 SetCommonAttributes(AliasDecl.getDecl(), Alias);
192
193 return false;
194}
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000195
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000196void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
John McCalld46f9852010-02-19 01:32:20 +0000197 // The constructor used for constructing this as a complete class;
198 // constucts the virtual bases, then calls the base constructor.
John McCall92ac9ff2010-02-17 03:52:49 +0000199 EmitGlobal(GlobalDecl(D, Ctor_Complete));
John McCalld46f9852010-02-19 01:32:20 +0000200
201 // The constructor used for constructing this as a base class;
202 // ignores virtual bases.
John McCall8e51a1f2010-02-18 21:31:48 +0000203 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000204}
Anders Carlsson363c1842009-04-16 23:57:24 +0000205
Mike Stump1eb44332009-09-09 15:08:12 +0000206void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000207 CXXCtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000208 // The complete constructor is equivalent to the base constructor
209 // for classes with no virtual bases. Try to emit it as an alias.
210 if (Type == Ctor_Complete &&
211 !D->getParent()->getNumVBases() &&
212 !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
213 GlobalDecl(D, Ctor_Base)))
214 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000215
John McCalld46f9852010-02-19 01:32:20 +0000216 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000218 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Anders Carlsson27ae5362009-04-17 01:58:57 +0000220 SetFunctionDefinitionAttributes(D, Fn);
221 SetLLVMFunctionAttributesForDefinition(D, Fn);
222}
223
John McCalld46f9852010-02-19 01:32:20 +0000224llvm::GlobalValue *
Mike Stump1eb44332009-09-09 15:08:12 +0000225CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlsson363c1842009-04-16 23:57:24 +0000226 CXXCtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000227 const char *Name = getMangledCXXCtorName(D, Type);
228 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
229 return V;
230
Fariborz Jahanian30509a32009-11-06 18:47:57 +0000231 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlsson363c1842009-04-16 23:57:24 +0000232 const llvm::FunctionType *FTy =
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000233 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanian30509a32009-11-06 18:47:57 +0000234 FPT->isVariadic());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000235 return cast<llvm::Function>(
236 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000237}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000238
Mike Stump1eb44332009-09-09 15:08:12 +0000239const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000240 CXXCtorType Type) {
241 llvm::SmallString<256> Name;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000242 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Anders Carlsson27ae5362009-04-17 01:58:57 +0000244 Name += '\0';
245 return UniqueMangledName(Name.begin(), Name.end());
246}
247
248void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
John McCalld46f9852010-02-19 01:32:20 +0000249 // The destructor in a virtual table is always a 'deleting'
250 // destructor, which calls the complete destructor and then uses the
251 // appropriate operator delete.
Eli Friedmanea9a2082009-11-14 04:19:37 +0000252 if (D->isVirtual())
Eli Friedman624c7d72009-12-15 02:06:15 +0000253 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
John McCalld46f9852010-02-19 01:32:20 +0000254
255 // The destructor used for destructing this as a most-derived class;
256 // call the base destructor and then destructs any virtual bases.
John McCall8e51a1f2010-02-18 21:31:48 +0000257 EmitGlobal(GlobalDecl(D, Dtor_Complete));
John McCalld46f9852010-02-19 01:32:20 +0000258
259 // The destructor used for destructing this as a base class; ignores
260 // virtual bases.
John McCall8e51a1f2010-02-18 21:31:48 +0000261 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000262}
263
Mike Stump1eb44332009-09-09 15:08:12 +0000264void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000265 CXXDtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000266 // The complete destructor is equivalent to the base destructor for
267 // classes with no virtual bases, so try to emit it as an alias.
268 if (Type == Dtor_Complete &&
269 !D->getParent()->getNumVBases() &&
270 !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
271 GlobalDecl(D, Dtor_Base)))
272 return;
273
John McCallc0bf4622010-02-23 00:48:20 +0000274 // The base destructor is equivalent to the base destructor of its
275 // base class if there is exactly one non-virtual base class with a
276 // non-trivial destructor, there are no fields with a non-trivial
277 // destructor, and the body of the destructor is trivial.
278 if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
279 return;
280
John McCalld46f9852010-02-19 01:32:20 +0000281 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000283 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Anders Carlsson27ae5362009-04-17 01:58:57 +0000285 SetFunctionDefinitionAttributes(D, Fn);
286 SetLLVMFunctionAttributesForDefinition(D, Fn);
287}
288
John McCalld46f9852010-02-19 01:32:20 +0000289llvm::GlobalValue *
Mike Stump1eb44332009-09-09 15:08:12 +0000290CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000291 CXXDtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000292 const char *Name = getMangledCXXDtorName(D, Type);
293 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
294 return V;
295
Anders Carlsson27ae5362009-04-17 01:58:57 +0000296 const llvm::FunctionType *FTy =
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000297 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000299 return cast<llvm::Function>(
300 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000301}
302
Mike Stump1eb44332009-09-09 15:08:12 +0000303const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000304 CXXDtorType Type) {
305 llvm::SmallString<256> Name;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000306 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Anders Carlsson27ae5362009-04-17 01:58:57 +0000308 Name += '\0';
309 return UniqueMangledName(Name.begin(), Name.end());
310}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000311
Anders Carlssona94822e2009-11-26 02:32:05 +0000312llvm::Constant *
Eli Friedman35c98cc2009-12-03 04:27:05 +0000313CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssona94822e2009-11-26 02:32:05 +0000314 bool Extern,
315 const ThunkAdjustment &ThisAdjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000316 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson7622cd32009-11-26 03:09:37 +0000317 CovariantThunkAdjustment(ThisAdjustment,
318 ThunkAdjustment()));
Mike Stumped032eb2009-09-04 18:27:16 +0000319}
320
Anders Carlsson7622cd32009-11-26 03:09:37 +0000321llvm::Value *
322CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
323 const ThunkAdjustment &Adjustment) {
324 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
325
Mike Stumpc902d222009-11-03 16:59:27 +0000326 const llvm::Type *OrigTy = V->getType();
Anders Carlsson7622cd32009-11-26 03:09:37 +0000327 if (Adjustment.NonVirtual) {
Mike Stumpc902d222009-11-03 16:59:27 +0000328 // Do the non-virtual adjustment
Anders Carlsson7622cd32009-11-26 03:09:37 +0000329 V = Builder.CreateBitCast(V, Int8PtrTy);
330 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stumpc902d222009-11-03 16:59:27 +0000331 V = Builder.CreateBitCast(V, OrigTy);
332 }
Anders Carlsson7622cd32009-11-26 03:09:37 +0000333
334 if (!Adjustment.Virtual)
335 return V;
336
337 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
338 "vtable entry unaligned");
339
340 // Do the virtual this adjustment
341 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
342 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
343
344 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
345 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
346 V = Builder.CreateLoad(V, "vtable");
347
348 llvm::Value *VTablePtr = V;
349 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
350 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
351 V = Builder.CreateLoad(V);
352 V = Builder.CreateGEP(ThisVal, V);
353
354 return Builder.CreateBitCast(V, OrigTy);
Mike Stumpc902d222009-11-03 16:59:27 +0000355}
356
Anders Carlsson7622cd32009-11-26 03:09:37 +0000357llvm::Constant *
358CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman35c98cc2009-12-03 04:27:05 +0000359 GlobalDecl GD, bool Extern,
Anders Carlsson7622cd32009-11-26 03:09:37 +0000360 const CovariantThunkAdjustment &Adjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000361 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCall04a67a62010-02-05 21:31:56 +0000362 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
363 QualType ResultType = FPT->getResultType();
Mike Stump6e319f62009-09-11 23:25:56 +0000364
365 FunctionArgList Args;
366 ImplicitParamDecl *ThisDecl =
367 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
368 MD->getThisType(getContext()));
369 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
370 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
371 e = MD->param_end();
372 i != e; ++i) {
373 ParmVarDecl *D = *i;
374 Args.push_back(std::make_pair(D, D->getType()));
375 }
376 IdentifierInfo *II
377 = &CGM.getContext().Idents.get("__thunk_named_foo_");
378 FunctionDecl *FD = FunctionDecl::Create(getContext(),
379 getContext().getTranslationUnitDecl(),
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000380 SourceLocation(), II, ResultType, 0,
Mike Stump6e319f62009-09-11 23:25:56 +0000381 Extern
382 ? FunctionDecl::Extern
383 : FunctionDecl::Static,
384 false, true);
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000385 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
386
387 // generate body
Mike Stump736529e2009-11-03 02:12:59 +0000388 const llvm::Type *Ty =
389 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
390 FPT->isVariadic());
Eli Friedman35c98cc2009-12-03 04:27:05 +0000391 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stump919d5e52009-12-03 03:47:56 +0000392
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000393 CallArgList CallArgs;
394
Anders Carlsson7622cd32009-11-26 03:09:37 +0000395 bool ShouldAdjustReturnPointer = true;
Mike Stump736529e2009-11-03 02:12:59 +0000396 QualType ArgType = MD->getThisType(getContext());
397 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson7622cd32009-11-26 03:09:37 +0000398 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stumpc902d222009-11-03 16:59:27 +0000399 // Do the this adjustment.
Mike Stumpd0fe5362009-11-04 00:53:51 +0000400 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson7622cd32009-11-26 03:09:37 +0000401 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
402
403 if (!Adjustment.ReturnAdjustment.isEmpty()) {
404 const CovariantThunkAdjustment &ReturnAdjustment =
405 CovariantThunkAdjustment(ThunkAdjustment(),
406 Adjustment.ReturnAdjustment);
407
Mike Stump919d5e52009-12-03 03:47:56 +0000408 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000409
Mike Stumpd0fe5362009-11-04 00:53:51 +0000410 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000411 ShouldAdjustReturnPointer = false;
Mike Stumpd0fe5362009-11-04 00:53:51 +0000412 }
413 }
414
Mike Stump736529e2009-11-03 02:12:59 +0000415 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
416
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000417 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
418 e = MD->param_end();
419 i != e; ++i) {
420 ParmVarDecl *D = *i;
421 QualType ArgType = D->getType();
422
423 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman6804fa22009-12-03 04:49:52 +0000424 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
425 SourceLocation());
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000426 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
427 }
428
John McCall04a67a62010-02-05 21:31:56 +0000429 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
430 FPT->getCallConv(),
431 FPT->getNoReturnAttr()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000432 Callee, ReturnValueSlot(), CallArgs, MD);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000433 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stump03e777e2009-11-05 06:32:02 +0000434 bool CanBeZero = !(ResultType->isReferenceType()
435 // FIXME: attr nonnull can't be zero either
436 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stumpc902d222009-11-03 16:59:27 +0000437 // Do the return result adjustment.
Mike Stump03e777e2009-11-05 06:32:02 +0000438 if (CanBeZero) {
439 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
440 llvm::BasicBlock *ZeroBlock = createBasicBlock();
441 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stump7c276b82009-11-05 06:12:26 +0000442
Mike Stump03e777e2009-11-05 06:32:02 +0000443 const llvm::Type *Ty = RV.getScalarVal()->getType();
444 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
445 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
446 NonZeroBlock, ZeroBlock);
447 EmitBlock(NonZeroBlock);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000448 llvm::Value *NZ =
449 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stump03e777e2009-11-05 06:32:02 +0000450 EmitBranch(ContBlock);
451 EmitBlock(ZeroBlock);
452 llvm::Value *Z = RV.getScalarVal();
453 EmitBlock(ContBlock);
454 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
455 RVOrZero->reserveOperandSpace(2);
456 RVOrZero->addIncoming(NZ, NonZeroBlock);
457 RVOrZero->addIncoming(Z, ZeroBlock);
458 RV = RValue::get(RVOrZero);
459 } else
Anders Carlsson7622cd32009-11-26 03:09:37 +0000460 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
461 Adjustment.ReturnAdjustment));
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000462 }
463
Mike Stumpf49ed942009-11-02 23:47:45 +0000464 if (!ResultType->isVoidType())
465 EmitReturnOfRValue(RV, ResultType);
466
Mike Stump6e319f62009-09-11 23:25:56 +0000467 FinishFunction();
468 return Fn;
469}
470
Anders Carlssona94822e2009-11-26 02:32:05 +0000471llvm::Constant *
Eli Friedman72649ed2009-12-06 22:01:30 +0000472CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
473 const ThunkAdjustment &ThisAdjustment) {
474 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
475
476 // Compute mangled name
477 llvm::SmallString<256> OutName;
478 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
479 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
480 OutName);
481 else
482 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
483 OutName += '\0';
484 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
485
486 // Get function for mangled name
487 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
488 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
489}
490
491llvm::Constant *
492CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
493 const CovariantThunkAdjustment &Adjustment) {
494 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
495
496 // Compute mangled name
497 llvm::SmallString<256> OutName;
498 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
499 OutName += '\0';
500 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
501
502 // Get function for mangled name
503 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
504 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
505}
506
507void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000508 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
509 if (!AdjPtr)
510 return;
511 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman72649ed2009-12-06 22:01:30 +0000512 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000513 for (unsigned i = 0; i < Adj.size(); i++) {
514 GlobalDecl OGD = Adj[i].first;
515 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman72649ed2009-12-06 22:01:30 +0000516 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
517 CanQualType oret = getContext().getCanonicalType(nc_oret);
518 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
519 CanQualType ret = getContext().getCanonicalType(nc_ret);
520 ThunkAdjustment ReturnAdjustment;
521 if (oret != ret) {
522 QualType qD = nc_ret->getPointeeType();
523 QualType qB = nc_oret->getPointeeType();
524 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
525 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
526 ReturnAdjustment = ComputeThunkAdjustment(D, B);
527 }
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000528 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman72649ed2009-12-06 22:01:30 +0000529 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
530 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
531 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
532 llvm::Constant *FnConst;
533 if (!ReturnAdjustment.isEmpty())
534 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
535 else
536 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
537 if (!isa<llvm::Function>(FnConst)) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000538 llvm::Constant *SubExpr =
539 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
540 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
541 std::string Name = OldFn->getNameStr();
542 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
543 Name.data() + Name.size() + 1));
544 llvm::Constant *NewFnConst;
545 if (!ReturnAdjustment.isEmpty())
546 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
547 else
548 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
549 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
550 NewFn->takeName(OldFn);
551 llvm::Constant *NewPtrForOldDecl =
552 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
553 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
554 OldFn->eraseFromParent();
555 FnConst = NewFn;
Eli Friedman72649ed2009-12-06 22:01:30 +0000556 }
557 llvm::Function *Fn = cast<llvm::Function>(FnConst);
558 if (Fn->isDeclaration()) {
559 llvm::GlobalVariable::LinkageTypes linktype;
560 linktype = llvm::GlobalValue::WeakAnyLinkage;
561 if (!Extern)
562 linktype = llvm::GlobalValue::InternalLinkage;
563 Fn->setLinkage(linktype);
564 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
565 Fn->addFnAttr(llvm::Attribute::NoUnwind);
566 Fn->setAlignment(2);
567 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
568 }
569 }
Eli Friedman72649ed2009-12-06 22:01:30 +0000570 }
571}
572
573llvm::Constant *
Eli Friedman35c98cc2009-12-03 04:27:05 +0000574CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssona94822e2009-11-26 02:32:05 +0000575 const ThunkAdjustment &ThisAdjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000576 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stumped032eb2009-09-04 18:27:16 +0000577 llvm::SmallString<256> OutName;
Mike Stump919d5e52009-12-03 03:47:56 +0000578 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
579 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
580 OutName);
581 } else
582 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssona94822e2009-11-26 02:32:05 +0000583
Mike Stumped032eb2009-09-04 18:27:16 +0000584 llvm::GlobalVariable::LinkageTypes linktype;
585 linktype = llvm::GlobalValue::WeakAnyLinkage;
586 if (!Extern)
587 linktype = llvm::GlobalValue::InternalLinkage;
588 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall183700f2009-09-21 23:43:11 +0000589 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stumped032eb2009-09-04 18:27:16 +0000590 const llvm::FunctionType *FTy =
591 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
592 FPT->isVariadic());
593
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000594 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stumped032eb2009-09-04 18:27:16 +0000595 &getModule());
Mike Stump919d5e52009-12-03 03:47:56 +0000596 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stumped032eb2009-09-04 18:27:16 +0000597 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
598 return m;
599}
600
Anders Carlsson7622cd32009-11-26 03:09:37 +0000601llvm::Constant *
Mike Stump919d5e52009-12-03 03:47:56 +0000602CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson7622cd32009-11-26 03:09:37 +0000603 const CovariantThunkAdjustment &Adjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000604 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump6e319f62009-09-11 23:25:56 +0000605 llvm::SmallString<256> OutName;
Anders Carlsson7622cd32009-11-26 03:09:37 +0000606 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump6e319f62009-09-11 23:25:56 +0000607 llvm::GlobalVariable::LinkageTypes linktype;
608 linktype = llvm::GlobalValue::WeakAnyLinkage;
609 if (!Extern)
610 linktype = llvm::GlobalValue::InternalLinkage;
611 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall183700f2009-09-21 23:43:11 +0000612 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump6e319f62009-09-11 23:25:56 +0000613 const llvm::FunctionType *FTy =
614 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
615 FPT->isVariadic());
616
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000617 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump6e319f62009-09-11 23:25:56 +0000618 &getModule());
Anders Carlsson7622cd32009-11-26 03:09:37 +0000619 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump6e319f62009-09-11 23:25:56 +0000620 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
621 return m;
622}
623
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000624static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlsson566abee2009-11-13 04:45:41 +0000625 llvm::Value *This, const llvm::Type *Ty) {
626 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson2b358352009-10-03 14:56:57 +0000627
Anders Carlsson566abee2009-11-13 04:45:41 +0000628 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
629 Vtable = CGF.Builder.CreateLoad(Vtable);
630
631 llvm::Value *VFuncPtr =
632 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
633 return CGF.Builder.CreateLoad(VFuncPtr);
634}
635
636llvm::Value *
637CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
638 const llvm::Type *Ty) {
639 MD = MD->getCanonicalDecl();
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000640 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlsson566abee2009-11-13 04:45:41 +0000641
642 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
643}
644
645llvm::Value *
646CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
647 llvm::Value *&This, const llvm::Type *Ty) {
648 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000649 uint64_t VtableIndex =
Anders Carlssona0fdd912009-11-13 17:08:56 +0000650 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlsson566abee2009-11-13 04:45:41 +0000651
652 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpf0070db2009-08-26 20:46:33 +0000653}