blob: cb8489d20240e4170044fa22b242cb76960753ca [file] [log] [blame]
Anders Carlsson87fc5a52008-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 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
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson1235bbc2009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000024#include "clang/AST/StmtCXX.h"
John McCalld4324142010-02-19 01:32:20 +000025#include "clang/CodeGen/CodeGenOptions.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000026#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000027using namespace clang;
28using namespace CodeGen;
29
John McCallf8ff7b92010-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
96 // If the base is at a non-zero offset, give up.
97 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
98 if (ClassLayout.getBaseClassOffset(UniqueBase) != 0)
99 return true;
100
101 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(getContext());
102 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
103 GlobalDecl(BaseD, Dtor_Base));
104}
105
John McCalld4324142010-02-19 01:32:20 +0000106/// Try to emit a definition as a global alias for another definition.
107bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
108 GlobalDecl TargetDecl) {
109 if (!getCodeGenOpts().CXXCtorDtorAliases)
110 return true;
111
John McCalld4324142010-02-19 01:32:20 +0000112 // The alias will use the linkage of the referrent. If we can't
113 // support aliases with that linkage, fail.
114 llvm::GlobalValue::LinkageTypes Linkage
115 = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
116
117 switch (Linkage) {
118 // We can definitely emit aliases to definitions with external linkage.
119 case llvm::GlobalValue::ExternalLinkage:
120 case llvm::GlobalValue::ExternalWeakLinkage:
121 break;
122
123 // Same with local linkage.
124 case llvm::GlobalValue::InternalLinkage:
125 case llvm::GlobalValue::PrivateLinkage:
126 case llvm::GlobalValue::LinkerPrivateLinkage:
127 break;
128
129 // We should try to support linkonce linkages.
130 case llvm::GlobalValue::LinkOnceAnyLinkage:
131 case llvm::GlobalValue::LinkOnceODRLinkage:
132 return true;
133
134 // Other linkages will probably never be supported.
135 default:
136 return true;
137 }
138
John McCallf8ff7b92010-02-23 00:48:20 +0000139 // Derive the type for the alias.
140 const llvm::PointerType *AliasType
141 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
142
John McCallf8ff7b92010-02-23 00:48:20 +0000143 // Find the referrent. Some aliases might require a bitcast, in
144 // which case the caller is responsible for ensuring the soundness
145 // of these semantics.
146 llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
147 llvm::Constant *Aliasee = Ref;
148 if (Ref->getType() != AliasType)
149 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
150
John McCalld4324142010-02-19 01:32:20 +0000151 // Create the alias with no name.
152 llvm::GlobalAlias *Alias =
John McCallf8ff7b92010-02-23 00:48:20 +0000153 new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000154
John McCallaea181d2010-02-24 20:32:01 +0000155 // Switch any previous uses to the alias.
156 const char *MangledName = getMangledName(AliasDecl);
157 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
John McCalld4324142010-02-19 01:32:20 +0000158 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000159 assert(Entry->isDeclaration() && "definition already exists for alias");
160 assert(Entry->getType() == AliasType &&
161 "declaration exists with different type");
John McCalld4324142010-02-19 01:32:20 +0000162 Entry->replaceAllUsesWith(Alias);
163 Entry->eraseFromParent();
164 }
165 Entry = Alias;
166
167 // Finally, set up the alias with its proper name and attributes.
168 Alias->setName(MangledName);
169 SetCommonAttributes(AliasDecl.getDecl(), Alias);
170
171 return false;
172}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000173
Anders Carlssonf7475242009-04-15 15:55:24 +0000174void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
John McCalld4324142010-02-19 01:32:20 +0000175 // The constructor used for constructing this as a complete class;
176 // constucts the virtual bases, then calls the base constructor.
John McCall67cea742010-02-17 03:52:49 +0000177 EmitGlobal(GlobalDecl(D, Ctor_Complete));
John McCalld4324142010-02-19 01:32:20 +0000178
179 // The constructor used for constructing this as a base class;
180 // ignores virtual bases.
John McCall334ce7c2010-02-18 21:31:48 +0000181 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000182}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000183
Mike Stump11289f42009-09-09 15:08:12 +0000184void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000185 CXXCtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000186 // The complete constructor is equivalent to the base constructor
187 // for classes with no virtual bases. Try to emit it as an alias.
188 if (Type == Ctor_Complete &&
189 !D->getParent()->getNumVBases() &&
190 !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
191 GlobalDecl(D, Ctor_Base)))
192 return;
Mike Stump11289f42009-09-09 15:08:12 +0000193
John McCalld4324142010-02-19 01:32:20 +0000194 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
Mike Stump11289f42009-09-09 15:08:12 +0000195
Anders Carlsson73fcc952009-09-11 00:07:24 +0000196 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000198 SetFunctionDefinitionAttributes(D, Fn);
199 SetLLVMFunctionAttributesForDefinition(D, Fn);
200}
201
John McCalld4324142010-02-19 01:32:20 +0000202llvm::GlobalValue *
Mike Stump11289f42009-09-09 15:08:12 +0000203CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000204 CXXCtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000205 const char *Name = getMangledCXXCtorName(D, Type);
206 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
207 return V;
208
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000209 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000210 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000211 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000212 FPT->isVariadic());
Chris Lattnere0be0df2009-05-12 21:21:08 +0000213 return cast<llvm::Function>(
214 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000215}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000216
Mike Stump11289f42009-09-09 15:08:12 +0000217const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000218 CXXCtorType Type) {
219 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000220 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000221
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000222 Name += '\0';
223 return UniqueMangledName(Name.begin(), Name.end());
224}
225
226void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
John McCalld4324142010-02-19 01:32:20 +0000227 // The destructor in a virtual table is always a 'deleting'
228 // destructor, which calls the complete destructor and then uses the
229 // appropriate operator delete.
Eli Friedmanb572c922009-11-14 04:19:37 +0000230 if (D->isVirtual())
Eli Friedmand777ccc2009-12-15 02:06:15 +0000231 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
John McCalld4324142010-02-19 01:32:20 +0000232
233 // The destructor used for destructing this as a most-derived class;
234 // call the base destructor and then destructs any virtual bases.
John McCall334ce7c2010-02-18 21:31:48 +0000235 EmitGlobal(GlobalDecl(D, Dtor_Complete));
John McCalld4324142010-02-19 01:32:20 +0000236
237 // The destructor used for destructing this as a base class; ignores
238 // virtual bases.
John McCall334ce7c2010-02-18 21:31:48 +0000239 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000240}
241
Mike Stump11289f42009-09-09 15:08:12 +0000242void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000243 CXXDtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000244 // The complete destructor is equivalent to the base destructor for
245 // classes with no virtual bases, so try to emit it as an alias.
246 if (Type == Dtor_Complete &&
247 !D->getParent()->getNumVBases() &&
248 !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
249 GlobalDecl(D, Dtor_Base)))
250 return;
251
John McCallf8ff7b92010-02-23 00:48:20 +0000252 // The base destructor is equivalent to the base destructor of its
253 // base class if there is exactly one non-virtual base class with a
254 // non-trivial destructor, there are no fields with a non-trivial
255 // destructor, and the body of the destructor is trivial.
256 if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
257 return;
258
John McCalld4324142010-02-19 01:32:20 +0000259 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
Mike Stump11289f42009-09-09 15:08:12 +0000260
Anders Carlsson73fcc952009-09-11 00:07:24 +0000261 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000262
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000263 SetFunctionDefinitionAttributes(D, Fn);
264 SetLLVMFunctionAttributesForDefinition(D, Fn);
265}
266
John McCalld4324142010-02-19 01:32:20 +0000267llvm::GlobalValue *
Mike Stump11289f42009-09-09 15:08:12 +0000268CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000269 CXXDtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000270 const char *Name = getMangledCXXDtorName(D, Type);
271 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
272 return V;
273
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000274 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000275 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattnere0be0df2009-05-12 21:21:08 +0000277 return cast<llvm::Function>(
278 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000279}
280
Mike Stump11289f42009-09-09 15:08:12 +0000281const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000282 CXXDtorType Type) {
283 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000284 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000286 Name += '\0';
287 return UniqueMangledName(Name.begin(), Name.end());
288}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000289
Anders Carlssonc7785402009-11-26 02:32:05 +0000290llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000291CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000292 bool Extern,
293 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000294 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000295 CovariantThunkAdjustment(ThisAdjustment,
296 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000297}
298
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000299llvm::Value *
300CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
301 const ThunkAdjustment &Adjustment) {
302 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
303
Mike Stump77738202009-11-03 16:59:27 +0000304 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000305 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000306 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000307 V = Builder.CreateBitCast(V, Int8PtrTy);
308 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000309 V = Builder.CreateBitCast(V, OrigTy);
310 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000311
312 if (!Adjustment.Virtual)
313 return V;
314
315 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
316 "vtable entry unaligned");
317
318 // Do the virtual this adjustment
319 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
320 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
321
322 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
323 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
324 V = Builder.CreateLoad(V, "vtable");
325
326 llvm::Value *VTablePtr = V;
327 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
328 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
329 V = Builder.CreateLoad(V);
330 V = Builder.CreateGEP(ThisVal, V);
331
332 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000333}
334
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000335llvm::Constant *
336CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000337 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000338 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000339 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCallab26cfa2010-02-05 21:31:56 +0000340 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
341 QualType ResultType = FPT->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000342
343 FunctionArgList Args;
344 ImplicitParamDecl *ThisDecl =
345 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
346 MD->getThisType(getContext()));
347 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
348 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
349 e = MD->param_end();
350 i != e; ++i) {
351 ParmVarDecl *D = *i;
352 Args.push_back(std::make_pair(D, D->getType()));
353 }
354 IdentifierInfo *II
355 = &CGM.getContext().Idents.get("__thunk_named_foo_");
356 FunctionDecl *FD = FunctionDecl::Create(getContext(),
357 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000358 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000359 Extern
360 ? FunctionDecl::Extern
361 : FunctionDecl::Static,
362 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000363 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
364
365 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000366 const llvm::Type *Ty =
367 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
368 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000369 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000370
Mike Stump33ccd9e2009-11-02 23:22:01 +0000371 CallArgList CallArgs;
372
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000373 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000374 QualType ArgType = MD->getThisType(getContext());
375 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000376 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000377 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000378 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000379 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
380
381 if (!Adjustment.ReturnAdjustment.isEmpty()) {
382 const CovariantThunkAdjustment &ReturnAdjustment =
383 CovariantThunkAdjustment(ThunkAdjustment(),
384 Adjustment.ReturnAdjustment);
385
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000386 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000387
Mike Stump71609a22009-11-04 00:53:51 +0000388 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000389 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000390 }
391 }
392
Mike Stumpf3589722009-11-03 02:12:59 +0000393 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
394
Mike Stump33ccd9e2009-11-02 23:22:01 +0000395 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
396 e = MD->param_end();
397 i != e; ++i) {
398 ParmVarDecl *D = *i;
399 QualType ArgType = D->getType();
400
401 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000402 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
403 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000404 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
405 }
406
John McCallab26cfa2010-02-05 21:31:56 +0000407 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
408 FPT->getCallConv(),
409 FPT->getNoReturnAttr()),
Anders Carlsson61a401c2009-12-24 19:25:24 +0000410 Callee, ReturnValueSlot(), CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000411 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000412 bool CanBeZero = !(ResultType->isReferenceType()
413 // FIXME: attr nonnull can't be zero either
414 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000415 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000416 if (CanBeZero) {
417 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
418 llvm::BasicBlock *ZeroBlock = createBasicBlock();
419 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000420
Mike Stumpc5507682009-11-05 06:32:02 +0000421 const llvm::Type *Ty = RV.getScalarVal()->getType();
422 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
423 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
424 NonZeroBlock, ZeroBlock);
425 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000426 llvm::Value *NZ =
427 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000428 EmitBranch(ContBlock);
429 EmitBlock(ZeroBlock);
430 llvm::Value *Z = RV.getScalarVal();
431 EmitBlock(ContBlock);
432 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
433 RVOrZero->reserveOperandSpace(2);
434 RVOrZero->addIncoming(NZ, NonZeroBlock);
435 RVOrZero->addIncoming(Z, ZeroBlock);
436 RV = RValue::get(RVOrZero);
437 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000438 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
439 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000440 }
441
Mike Stump31e1d432009-11-02 23:47:45 +0000442 if (!ResultType->isVoidType())
443 EmitReturnOfRValue(RV, ResultType);
444
Mike Stump80f6ac52009-09-11 23:25:56 +0000445 FinishFunction();
446 return Fn;
447}
448
Anders Carlssonc7785402009-11-26 02:32:05 +0000449llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000450CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
451 const ThunkAdjustment &ThisAdjustment) {
452 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
453
454 // Compute mangled name
455 llvm::SmallString<256> OutName;
456 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
457 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
458 OutName);
459 else
460 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
461 OutName += '\0';
462 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
463
464 // Get function for mangled name
465 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
466 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
467}
468
469llvm::Constant *
470CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
471 const CovariantThunkAdjustment &Adjustment) {
472 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
473
474 // Compute mangled name
475 llvm::SmallString<256> OutName;
476 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
477 OutName += '\0';
478 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
479
480 // Get function for mangled name
481 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
482 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
483}
484
485void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000486 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
487 if (!AdjPtr)
488 return;
489 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000490 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000491 for (unsigned i = 0; i < Adj.size(); i++) {
492 GlobalDecl OGD = Adj[i].first;
493 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000494 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
495 CanQualType oret = getContext().getCanonicalType(nc_oret);
496 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
497 CanQualType ret = getContext().getCanonicalType(nc_ret);
498 ThunkAdjustment ReturnAdjustment;
499 if (oret != ret) {
500 QualType qD = nc_ret->getPointeeType();
501 QualType qB = nc_oret->getPointeeType();
502 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
503 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
504 ReturnAdjustment = ComputeThunkAdjustment(D, B);
505 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000506 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000507 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
508 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
509 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
510 llvm::Constant *FnConst;
511 if (!ReturnAdjustment.isEmpty())
512 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
513 else
514 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
515 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000516 llvm::Constant *SubExpr =
517 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
518 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
519 std::string Name = OldFn->getNameStr();
520 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
521 Name.data() + Name.size() + 1));
522 llvm::Constant *NewFnConst;
523 if (!ReturnAdjustment.isEmpty())
524 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
525 else
526 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
527 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
528 NewFn->takeName(OldFn);
529 llvm::Constant *NewPtrForOldDecl =
530 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
531 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
532 OldFn->eraseFromParent();
533 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000534 }
535 llvm::Function *Fn = cast<llvm::Function>(FnConst);
536 if (Fn->isDeclaration()) {
537 llvm::GlobalVariable::LinkageTypes linktype;
538 linktype = llvm::GlobalValue::WeakAnyLinkage;
539 if (!Extern)
540 linktype = llvm::GlobalValue::InternalLinkage;
541 Fn->setLinkage(linktype);
542 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
543 Fn->addFnAttr(llvm::Attribute::NoUnwind);
544 Fn->setAlignment(2);
545 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
546 }
547 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000548 }
549}
550
551llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000552CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000553 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000554 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000555 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000556 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
557 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
558 OutName);
559 } else
560 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000561
Mike Stump5a522352009-09-04 18:27:16 +0000562 llvm::GlobalVariable::LinkageTypes linktype;
563 linktype = llvm::GlobalValue::WeakAnyLinkage;
564 if (!Extern)
565 linktype = llvm::GlobalValue::InternalLinkage;
566 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000567 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000568 const llvm::FunctionType *FTy =
569 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
570 FPT->isVariadic());
571
Daniel Dunbare128dd12009-11-21 09:06:22 +0000572 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000573 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000574 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000575 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
576 return m;
577}
578
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000579llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000580CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000581 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000582 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000583 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000584 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000585 llvm::GlobalVariable::LinkageTypes linktype;
586 linktype = llvm::GlobalValue::WeakAnyLinkage;
587 if (!Extern)
588 linktype = llvm::GlobalValue::InternalLinkage;
589 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000590 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000591 const llvm::FunctionType *FTy =
592 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
593 FPT->isVariadic());
594
Daniel Dunbare128dd12009-11-21 09:06:22 +0000595 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000596 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000597 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000598 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
599 return m;
600}
601
Anders Carlssonf942ee02009-11-27 20:47:55 +0000602static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +0000603 llvm::Value *This, const llvm::Type *Ty) {
604 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +0000605
Anders Carlssone828c362009-11-13 04:45:41 +0000606 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
607 Vtable = CGF.Builder.CreateLoad(Vtable);
608
609 llvm::Value *VFuncPtr =
610 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
611 return CGF.Builder.CreateLoad(VFuncPtr);
612}
613
614llvm::Value *
615CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
616 const llvm::Type *Ty) {
617 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +0000618 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +0000619
620 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
621}
622
623llvm::Value *
624CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
625 llvm::Value *&This, const llvm::Type *Ty) {
626 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +0000627 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000628 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +0000629
630 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +0000631}