blob: 4889fc08f488912a313f848d75aff446482de13b [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
John McCall1950a112010-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 McCallf8ff7b92010-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 McCallf8ff7b92010-02-23 00:48:20 +0000108 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
109 GlobalDecl(BaseD, Dtor_Base));
110}
111
John McCalld4324142010-02-19 01:32:20 +0000112/// Try to emit a definition as a global alias for another definition.
113bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
114 GlobalDecl TargetDecl) {
115 if (!getCodeGenOpts().CXXCtorDtorAliases)
116 return true;
117
John McCalld4324142010-02-19 01:32:20 +0000118 // The alias will use the linkage of the referrent. If we can't
119 // support aliases with that linkage, fail.
120 llvm::GlobalValue::LinkageTypes Linkage
121 = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
122
123 switch (Linkage) {
124 // We can definitely emit aliases to definitions with external linkage.
125 case llvm::GlobalValue::ExternalLinkage:
126 case llvm::GlobalValue::ExternalWeakLinkage:
127 break;
128
129 // Same with local linkage.
130 case llvm::GlobalValue::InternalLinkage:
131 case llvm::GlobalValue::PrivateLinkage:
132 case llvm::GlobalValue::LinkerPrivateLinkage:
133 break;
134
135 // We should try to support linkonce linkages.
136 case llvm::GlobalValue::LinkOnceAnyLinkage:
137 case llvm::GlobalValue::LinkOnceODRLinkage:
138 return true;
139
140 // Other linkages will probably never be supported.
141 default:
142 return true;
143 }
144
John McCallf8ff7b92010-02-23 00:48:20 +0000145 // Derive the type for the alias.
146 const llvm::PointerType *AliasType
147 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
148
John McCallf8ff7b92010-02-23 00:48:20 +0000149 // Find the referrent. Some aliases might require a bitcast, in
150 // which case the caller is responsible for ensuring the soundness
151 // of these semantics.
152 llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
153 llvm::Constant *Aliasee = Ref;
154 if (Ref->getType() != AliasType)
155 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
156
John McCalld4324142010-02-19 01:32:20 +0000157 // Create the alias with no name.
158 llvm::GlobalAlias *Alias =
John McCallf8ff7b92010-02-23 00:48:20 +0000159 new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000160
John McCallaea181d2010-02-24 20:32:01 +0000161 // Switch any previous uses to the alias.
162 const char *MangledName = getMangledName(AliasDecl);
163 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
John McCalld4324142010-02-19 01:32:20 +0000164 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000165 assert(Entry->isDeclaration() && "definition already exists for alias");
166 assert(Entry->getType() == AliasType &&
167 "declaration exists with different type");
John McCalld4324142010-02-19 01:32:20 +0000168 Entry->replaceAllUsesWith(Alias);
169 Entry->eraseFromParent();
170 }
171 Entry = Alias;
172
173 // Finally, set up the alias with its proper name and attributes.
174 Alias->setName(MangledName);
175 SetCommonAttributes(AliasDecl.getDecl(), Alias);
176
177 return false;
178}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000179
Anders Carlssonf7475242009-04-15 15:55:24 +0000180void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
John McCalld4324142010-02-19 01:32:20 +0000181 // The constructor used for constructing this as a complete class;
182 // constucts the virtual bases, then calls the base constructor.
John McCall67cea742010-02-17 03:52:49 +0000183 EmitGlobal(GlobalDecl(D, Ctor_Complete));
John McCalld4324142010-02-19 01:32:20 +0000184
185 // The constructor used for constructing this as a base class;
186 // ignores virtual bases.
John McCall334ce7c2010-02-18 21:31:48 +0000187 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000188}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000189
Mike Stump11289f42009-09-09 15:08:12 +0000190void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000191 CXXCtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000192 // The complete constructor is equivalent to the base constructor
193 // for classes with no virtual bases. Try to emit it as an alias.
194 if (Type == Ctor_Complete &&
195 !D->getParent()->getNumVBases() &&
196 !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
197 GlobalDecl(D, Ctor_Base)))
198 return;
Mike Stump11289f42009-09-09 15:08:12 +0000199
John McCalld4324142010-02-19 01:32:20 +0000200 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson73fcc952009-09-11 00:07:24 +0000202 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000204 SetFunctionDefinitionAttributes(D, Fn);
205 SetLLVMFunctionAttributesForDefinition(D, Fn);
206}
207
John McCalld4324142010-02-19 01:32:20 +0000208llvm::GlobalValue *
Mike Stump11289f42009-09-09 15:08:12 +0000209CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000210 CXXCtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000211 const char *Name = getMangledCXXCtorName(D, Type);
212 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
213 return V;
214
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000215 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000216 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000217 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000218 FPT->isVariadic());
Chris Lattnere0be0df2009-05-12 21:21:08 +0000219 return cast<llvm::Function>(
220 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000221}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000222
Mike Stump11289f42009-09-09 15:08:12 +0000223const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000224 CXXCtorType Type) {
225 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000226 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000227
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000228 Name += '\0';
229 return UniqueMangledName(Name.begin(), Name.end());
230}
231
232void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
John McCalld4324142010-02-19 01:32:20 +0000233 // The destructor in a virtual table is always a 'deleting'
234 // destructor, which calls the complete destructor and then uses the
235 // appropriate operator delete.
Eli Friedmanb572c922009-11-14 04:19:37 +0000236 if (D->isVirtual())
Eli Friedmand777ccc2009-12-15 02:06:15 +0000237 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
John McCalld4324142010-02-19 01:32:20 +0000238
239 // The destructor used for destructing this as a most-derived class;
240 // call the base destructor and then destructs any virtual bases.
John McCall334ce7c2010-02-18 21:31:48 +0000241 EmitGlobal(GlobalDecl(D, Dtor_Complete));
John McCalld4324142010-02-19 01:32:20 +0000242
243 // The destructor used for destructing this as a base class; ignores
244 // virtual bases.
John McCall334ce7c2010-02-18 21:31:48 +0000245 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000246}
247
Mike Stump11289f42009-09-09 15:08:12 +0000248void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000249 CXXDtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000250 // The complete destructor is equivalent to the base destructor for
251 // classes with no virtual bases, so try to emit it as an alias.
252 if (Type == Dtor_Complete &&
253 !D->getParent()->getNumVBases() &&
254 !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
255 GlobalDecl(D, Dtor_Base)))
256 return;
257
John McCallf8ff7b92010-02-23 00:48:20 +0000258 // The base destructor is equivalent to the base destructor of its
259 // base class if there is exactly one non-virtual base class with a
260 // non-trivial destructor, there are no fields with a non-trivial
261 // destructor, and the body of the destructor is trivial.
262 if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
263 return;
264
John McCalld4324142010-02-19 01:32:20 +0000265 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
Mike Stump11289f42009-09-09 15:08:12 +0000266
Anders Carlsson73fcc952009-09-11 00:07:24 +0000267 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000268
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000269 SetFunctionDefinitionAttributes(D, Fn);
270 SetLLVMFunctionAttributesForDefinition(D, Fn);
271}
272
John McCalld4324142010-02-19 01:32:20 +0000273llvm::GlobalValue *
Mike Stump11289f42009-09-09 15:08:12 +0000274CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000275 CXXDtorType Type) {
John McCalld4324142010-02-19 01:32:20 +0000276 const char *Name = getMangledCXXDtorName(D, Type);
277 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
278 return V;
279
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000280 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000281 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattnere0be0df2009-05-12 21:21:08 +0000283 return cast<llvm::Function>(
284 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000285}
286
Mike Stump11289f42009-09-09 15:08:12 +0000287const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000288 CXXDtorType Type) {
289 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000290 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000292 Name += '\0';
293 return UniqueMangledName(Name.begin(), Name.end());
294}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000295
Anders Carlssonc7785402009-11-26 02:32:05 +0000296llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000297CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000298 bool Extern,
299 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000300 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000301 CovariantThunkAdjustment(ThisAdjustment,
302 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000303}
304
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000305llvm::Value *
306CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
307 const ThunkAdjustment &Adjustment) {
308 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
309
Mike Stump77738202009-11-03 16:59:27 +0000310 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000311 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000312 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000313 V = Builder.CreateBitCast(V, Int8PtrTy);
314 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000315 V = Builder.CreateBitCast(V, OrigTy);
316 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000317
318 if (!Adjustment.Virtual)
319 return V;
320
321 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
322 "vtable entry unaligned");
323
324 // Do the virtual this adjustment
325 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
326 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
327
328 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
329 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
330 V = Builder.CreateLoad(V, "vtable");
331
332 llvm::Value *VTablePtr = V;
333 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
334 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
335 V = Builder.CreateLoad(V);
336 V = Builder.CreateGEP(ThisVal, V);
337
338 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000339}
340
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000341llvm::Constant *
342CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000343 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000344 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000345 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCallab26cfa2010-02-05 21:31:56 +0000346 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
347 QualType ResultType = FPT->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000348
349 FunctionArgList Args;
350 ImplicitParamDecl *ThisDecl =
351 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
352 MD->getThisType(getContext()));
353 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
354 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
355 e = MD->param_end();
356 i != e; ++i) {
357 ParmVarDecl *D = *i;
358 Args.push_back(std::make_pair(D, D->getType()));
359 }
360 IdentifierInfo *II
361 = &CGM.getContext().Idents.get("__thunk_named_foo_");
362 FunctionDecl *FD = FunctionDecl::Create(getContext(),
363 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000364 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000365 Extern
366 ? FunctionDecl::Extern
367 : FunctionDecl::Static,
368 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000369 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
370
371 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000372 const llvm::Type *Ty =
373 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
374 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000375 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000376
Mike Stump33ccd9e2009-11-02 23:22:01 +0000377 CallArgList CallArgs;
378
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000379 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000380 QualType ArgType = MD->getThisType(getContext());
381 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000382 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000383 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000384 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000385 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
386
387 if (!Adjustment.ReturnAdjustment.isEmpty()) {
388 const CovariantThunkAdjustment &ReturnAdjustment =
389 CovariantThunkAdjustment(ThunkAdjustment(),
390 Adjustment.ReturnAdjustment);
391
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000392 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000393
Mike Stump71609a22009-11-04 00:53:51 +0000394 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000395 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000396 }
397 }
398
Mike Stumpf3589722009-11-03 02:12:59 +0000399 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
400
Mike Stump33ccd9e2009-11-02 23:22:01 +0000401 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
402 e = MD->param_end();
403 i != e; ++i) {
404 ParmVarDecl *D = *i;
405 QualType ArgType = D->getType();
406
407 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000408 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
409 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000410 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
411 }
412
John McCallab26cfa2010-02-05 21:31:56 +0000413 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
414 FPT->getCallConv(),
415 FPT->getNoReturnAttr()),
Anders Carlsson61a401c2009-12-24 19:25:24 +0000416 Callee, ReturnValueSlot(), CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000417 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000418 bool CanBeZero = !(ResultType->isReferenceType()
419 // FIXME: attr nonnull can't be zero either
420 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000421 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000422 if (CanBeZero) {
423 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
424 llvm::BasicBlock *ZeroBlock = createBasicBlock();
425 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000426
Mike Stumpc5507682009-11-05 06:32:02 +0000427 const llvm::Type *Ty = RV.getScalarVal()->getType();
428 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
429 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
430 NonZeroBlock, ZeroBlock);
431 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000432 llvm::Value *NZ =
433 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000434 EmitBranch(ContBlock);
435 EmitBlock(ZeroBlock);
436 llvm::Value *Z = RV.getScalarVal();
437 EmitBlock(ContBlock);
438 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
439 RVOrZero->reserveOperandSpace(2);
440 RVOrZero->addIncoming(NZ, NonZeroBlock);
441 RVOrZero->addIncoming(Z, ZeroBlock);
442 RV = RValue::get(RVOrZero);
443 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000444 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
445 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000446 }
447
Mike Stump31e1d432009-11-02 23:47:45 +0000448 if (!ResultType->isVoidType())
449 EmitReturnOfRValue(RV, ResultType);
450
Mike Stump80f6ac52009-09-11 23:25:56 +0000451 FinishFunction();
452 return Fn;
453}
454
Anders Carlssonc7785402009-11-26 02:32:05 +0000455llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000456CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
457 const ThunkAdjustment &ThisAdjustment) {
458 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
459
460 // Compute mangled name
461 llvm::SmallString<256> OutName;
462 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
463 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
464 OutName);
465 else
466 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
467 OutName += '\0';
468 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
469
470 // Get function for mangled name
471 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
472 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
473}
474
475llvm::Constant *
476CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
477 const CovariantThunkAdjustment &Adjustment) {
478 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
479
480 // Compute mangled name
481 llvm::SmallString<256> OutName;
482 getMangleContext().mangleCovariantThunk(MD, Adjustment, 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
491void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000492 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
493 if (!AdjPtr)
494 return;
495 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000496 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000497 for (unsigned i = 0; i < Adj.size(); i++) {
498 GlobalDecl OGD = Adj[i].first;
499 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000500 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
501 CanQualType oret = getContext().getCanonicalType(nc_oret);
502 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
503 CanQualType ret = getContext().getCanonicalType(nc_ret);
504 ThunkAdjustment ReturnAdjustment;
505 if (oret != ret) {
506 QualType qD = nc_ret->getPointeeType();
507 QualType qB = nc_oret->getPointeeType();
508 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
509 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
510 ReturnAdjustment = ComputeThunkAdjustment(D, B);
511 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000512 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000513 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
514 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
515 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
516 llvm::Constant *FnConst;
517 if (!ReturnAdjustment.isEmpty())
518 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
519 else
520 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
521 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000522 llvm::Constant *SubExpr =
523 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
524 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
525 std::string Name = OldFn->getNameStr();
526 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
527 Name.data() + Name.size() + 1));
528 llvm::Constant *NewFnConst;
529 if (!ReturnAdjustment.isEmpty())
530 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
531 else
532 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
533 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
534 NewFn->takeName(OldFn);
535 llvm::Constant *NewPtrForOldDecl =
536 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
537 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
538 OldFn->eraseFromParent();
539 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000540 }
541 llvm::Function *Fn = cast<llvm::Function>(FnConst);
542 if (Fn->isDeclaration()) {
543 llvm::GlobalVariable::LinkageTypes linktype;
544 linktype = llvm::GlobalValue::WeakAnyLinkage;
545 if (!Extern)
546 linktype = llvm::GlobalValue::InternalLinkage;
547 Fn->setLinkage(linktype);
548 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
549 Fn->addFnAttr(llvm::Attribute::NoUnwind);
550 Fn->setAlignment(2);
551 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
552 }
553 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000554 }
555}
556
557llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000558CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000559 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000560 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000561 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000562 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
563 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
564 OutName);
565 } else
566 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000567
Mike Stump5a522352009-09-04 18:27:16 +0000568 llvm::GlobalVariable::LinkageTypes linktype;
569 linktype = llvm::GlobalValue::WeakAnyLinkage;
570 if (!Extern)
571 linktype = llvm::GlobalValue::InternalLinkage;
572 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000573 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000574 const llvm::FunctionType *FTy =
575 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
576 FPT->isVariadic());
577
Daniel Dunbare128dd12009-11-21 09:06:22 +0000578 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000579 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000580 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000581 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
582 return m;
583}
584
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000585llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000586CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000587 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000588 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000589 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000590 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000591 llvm::GlobalVariable::LinkageTypes linktype;
592 linktype = llvm::GlobalValue::WeakAnyLinkage;
593 if (!Extern)
594 linktype = llvm::GlobalValue::InternalLinkage;
595 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000596 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000597 const llvm::FunctionType *FTy =
598 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
599 FPT->isVariadic());
600
Daniel Dunbare128dd12009-11-21 09:06:22 +0000601 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000602 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000603 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000604 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
605 return m;
606}
607
Anders Carlssonf942ee02009-11-27 20:47:55 +0000608static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +0000609 llvm::Value *This, const llvm::Type *Ty) {
610 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +0000611
Anders Carlssone828c362009-11-13 04:45:41 +0000612 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
613 Vtable = CGF.Builder.CreateLoad(Vtable);
614
615 llvm::Value *VFuncPtr =
616 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
617 return CGF.Builder.CreateLoad(VFuncPtr);
618}
619
620llvm::Value *
621CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
622 const llvm::Type *Ty) {
623 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +0000624 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +0000625
626 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
627}
628
629llvm::Value *
630CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
631 llvm::Value *&This, const llvm::Type *Ty) {
632 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +0000633 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000634 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +0000635
636 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +0000637}