blob: 01648ae074796df8c192b7dea94cc440de772186 [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
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 McCalld46f9852010-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 McCalld46f9852010-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 McCallc0bf4622010-02-23 00:48:20 +0000139 // Derive the type for the alias.
140 const llvm::PointerType *AliasType
141 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
142
143 // Look for an existing entry.
144 const char *MangledName = getMangledName(AliasDecl);
145 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
146 if (Entry) {
147 assert(Entry->isDeclaration() && "definition already exists for alias");
148 assert(Entry->getType() == AliasType &&
149 "declaration exists with different type");
150 }
151
152 // Find the referrent. Some aliases might require a bitcast, in
153 // which case the caller is responsible for ensuring the soundness
154 // of these semantics.
155 llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
156 llvm::Constant *Aliasee = Ref;
157 if (Ref->getType() != AliasType)
158 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
159
John McCalld46f9852010-02-19 01:32:20 +0000160 // Create the alias with no name.
161 llvm::GlobalAlias *Alias =
John McCallc0bf4622010-02-23 00:48:20 +0000162 new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
John McCalld46f9852010-02-19 01:32:20 +0000163
John McCallc0bf4622010-02-23 00:48:20 +0000164 // Switch any previous uses to the alias and kill the previous decl.
John McCalld46f9852010-02-19 01:32:20 +0000165 if (Entry) {
166 Entry->replaceAllUsesWith(Alias);
167 Entry->eraseFromParent();
168 }
169 Entry = Alias;
170
171 // Finally, set up the alias with its proper name and attributes.
172 Alias->setName(MangledName);
173 SetCommonAttributes(AliasDecl.getDecl(), Alias);
174
175 return false;
176}
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000177
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000178void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
John McCalld46f9852010-02-19 01:32:20 +0000179 // The constructor used for constructing this as a complete class;
180 // constucts the virtual bases, then calls the base constructor.
John McCall92ac9ff2010-02-17 03:52:49 +0000181 EmitGlobal(GlobalDecl(D, Ctor_Complete));
John McCalld46f9852010-02-19 01:32:20 +0000182
183 // The constructor used for constructing this as a base class;
184 // ignores virtual bases.
John McCall8e51a1f2010-02-18 21:31:48 +0000185 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000186}
Anders Carlsson363c1842009-04-16 23:57:24 +0000187
Mike Stump1eb44332009-09-09 15:08:12 +0000188void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000189 CXXCtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000190 // The complete constructor is equivalent to the base constructor
191 // for classes with no virtual bases. Try to emit it as an alias.
192 if (Type == Ctor_Complete &&
193 !D->getParent()->getNumVBases() &&
194 !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
195 GlobalDecl(D, Ctor_Base)))
196 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
John McCalld46f9852010-02-19 01:32:20 +0000198 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000200 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlsson27ae5362009-04-17 01:58:57 +0000202 SetFunctionDefinitionAttributes(D, Fn);
203 SetLLVMFunctionAttributesForDefinition(D, Fn);
204}
205
John McCalld46f9852010-02-19 01:32:20 +0000206llvm::GlobalValue *
Mike Stump1eb44332009-09-09 15:08:12 +0000207CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlsson363c1842009-04-16 23:57:24 +0000208 CXXCtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000209 const char *Name = getMangledCXXCtorName(D, Type);
210 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
211 return V;
212
Fariborz Jahanian30509a32009-11-06 18:47:57 +0000213 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlsson363c1842009-04-16 23:57:24 +0000214 const llvm::FunctionType *FTy =
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000215 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanian30509a32009-11-06 18:47:57 +0000216 FPT->isVariadic());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000217 return cast<llvm::Function>(
218 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000219}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000220
Mike Stump1eb44332009-09-09 15:08:12 +0000221const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000222 CXXCtorType Type) {
223 llvm::SmallString<256> Name;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000224 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Anders Carlsson27ae5362009-04-17 01:58:57 +0000226 Name += '\0';
227 return UniqueMangledName(Name.begin(), Name.end());
228}
229
230void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
John McCalld46f9852010-02-19 01:32:20 +0000231 // The destructor in a virtual table is always a 'deleting'
232 // destructor, which calls the complete destructor and then uses the
233 // appropriate operator delete.
Eli Friedmanea9a2082009-11-14 04:19:37 +0000234 if (D->isVirtual())
Eli Friedman624c7d72009-12-15 02:06:15 +0000235 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
John McCalld46f9852010-02-19 01:32:20 +0000236
237 // The destructor used for destructing this as a most-derived class;
238 // call the base destructor and then destructs any virtual bases.
John McCall8e51a1f2010-02-18 21:31:48 +0000239 EmitGlobal(GlobalDecl(D, Dtor_Complete));
John McCalld46f9852010-02-19 01:32:20 +0000240
241 // The destructor used for destructing this as a base class; ignores
242 // virtual bases.
John McCall8e51a1f2010-02-18 21:31:48 +0000243 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000244}
245
Mike Stump1eb44332009-09-09 15:08:12 +0000246void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000247 CXXDtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000248 // The complete destructor is equivalent to the base destructor for
249 // classes with no virtual bases, so try to emit it as an alias.
250 if (Type == Dtor_Complete &&
251 !D->getParent()->getNumVBases() &&
252 !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
253 GlobalDecl(D, Dtor_Base)))
254 return;
255
John McCallc0bf4622010-02-23 00:48:20 +0000256 // The base destructor is equivalent to the base destructor of its
257 // base class if there is exactly one non-virtual base class with a
258 // non-trivial destructor, there are no fields with a non-trivial
259 // destructor, and the body of the destructor is trivial.
260 if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
261 return;
262
John McCalld46f9852010-02-19 01:32:20 +0000263 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000265 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Anders Carlsson27ae5362009-04-17 01:58:57 +0000267 SetFunctionDefinitionAttributes(D, Fn);
268 SetLLVMFunctionAttributesForDefinition(D, Fn);
269}
270
John McCalld46f9852010-02-19 01:32:20 +0000271llvm::GlobalValue *
Mike Stump1eb44332009-09-09 15:08:12 +0000272CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000273 CXXDtorType Type) {
John McCalld46f9852010-02-19 01:32:20 +0000274 const char *Name = getMangledCXXDtorName(D, Type);
275 if (llvm::GlobalValue *V = GlobalDeclMap[Name])
276 return V;
277
Anders Carlsson27ae5362009-04-17 01:58:57 +0000278 const llvm::FunctionType *FTy =
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000279 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000281 return cast<llvm::Function>(
282 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000283}
284
Mike Stump1eb44332009-09-09 15:08:12 +0000285const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlsson27ae5362009-04-17 01:58:57 +0000286 CXXDtorType Type) {
287 llvm::SmallString<256> Name;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000288 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Anders Carlsson27ae5362009-04-17 01:58:57 +0000290 Name += '\0';
291 return UniqueMangledName(Name.begin(), Name.end());
292}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000293
Anders Carlssona94822e2009-11-26 02:32:05 +0000294llvm::Constant *
Eli Friedman35c98cc2009-12-03 04:27:05 +0000295CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssona94822e2009-11-26 02:32:05 +0000296 bool Extern,
297 const ThunkAdjustment &ThisAdjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000298 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson7622cd32009-11-26 03:09:37 +0000299 CovariantThunkAdjustment(ThisAdjustment,
300 ThunkAdjustment()));
Mike Stumped032eb2009-09-04 18:27:16 +0000301}
302
Anders Carlsson7622cd32009-11-26 03:09:37 +0000303llvm::Value *
304CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
305 const ThunkAdjustment &Adjustment) {
306 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
307
Mike Stumpc902d222009-11-03 16:59:27 +0000308 const llvm::Type *OrigTy = V->getType();
Anders Carlsson7622cd32009-11-26 03:09:37 +0000309 if (Adjustment.NonVirtual) {
Mike Stumpc902d222009-11-03 16:59:27 +0000310 // Do the non-virtual adjustment
Anders Carlsson7622cd32009-11-26 03:09:37 +0000311 V = Builder.CreateBitCast(V, Int8PtrTy);
312 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stumpc902d222009-11-03 16:59:27 +0000313 V = Builder.CreateBitCast(V, OrigTy);
314 }
Anders Carlsson7622cd32009-11-26 03:09:37 +0000315
316 if (!Adjustment.Virtual)
317 return V;
318
319 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
320 "vtable entry unaligned");
321
322 // Do the virtual this adjustment
323 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
324 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
325
326 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
327 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
328 V = Builder.CreateLoad(V, "vtable");
329
330 llvm::Value *VTablePtr = V;
331 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
332 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
333 V = Builder.CreateLoad(V);
334 V = Builder.CreateGEP(ThisVal, V);
335
336 return Builder.CreateBitCast(V, OrigTy);
Mike Stumpc902d222009-11-03 16:59:27 +0000337}
338
Anders Carlsson7622cd32009-11-26 03:09:37 +0000339llvm::Constant *
340CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman35c98cc2009-12-03 04:27:05 +0000341 GlobalDecl GD, bool Extern,
Anders Carlsson7622cd32009-11-26 03:09:37 +0000342 const CovariantThunkAdjustment &Adjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000343 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCall04a67a62010-02-05 21:31:56 +0000344 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
345 QualType ResultType = FPT->getResultType();
Mike Stump6e319f62009-09-11 23:25:56 +0000346
347 FunctionArgList Args;
348 ImplicitParamDecl *ThisDecl =
349 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
350 MD->getThisType(getContext()));
351 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
352 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
353 e = MD->param_end();
354 i != e; ++i) {
355 ParmVarDecl *D = *i;
356 Args.push_back(std::make_pair(D, D->getType()));
357 }
358 IdentifierInfo *II
359 = &CGM.getContext().Idents.get("__thunk_named_foo_");
360 FunctionDecl *FD = FunctionDecl::Create(getContext(),
361 getContext().getTranslationUnitDecl(),
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000362 SourceLocation(), II, ResultType, 0,
Mike Stump6e319f62009-09-11 23:25:56 +0000363 Extern
364 ? FunctionDecl::Extern
365 : FunctionDecl::Static,
366 false, true);
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000367 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
368
369 // generate body
Mike Stump736529e2009-11-03 02:12:59 +0000370 const llvm::Type *Ty =
371 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
372 FPT->isVariadic());
Eli Friedman35c98cc2009-12-03 04:27:05 +0000373 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stump919d5e52009-12-03 03:47:56 +0000374
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000375 CallArgList CallArgs;
376
Anders Carlsson7622cd32009-11-26 03:09:37 +0000377 bool ShouldAdjustReturnPointer = true;
Mike Stump736529e2009-11-03 02:12:59 +0000378 QualType ArgType = MD->getThisType(getContext());
379 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson7622cd32009-11-26 03:09:37 +0000380 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stumpc902d222009-11-03 16:59:27 +0000381 // Do the this adjustment.
Mike Stumpd0fe5362009-11-04 00:53:51 +0000382 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson7622cd32009-11-26 03:09:37 +0000383 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
384
385 if (!Adjustment.ReturnAdjustment.isEmpty()) {
386 const CovariantThunkAdjustment &ReturnAdjustment =
387 CovariantThunkAdjustment(ThunkAdjustment(),
388 Adjustment.ReturnAdjustment);
389
Mike Stump919d5e52009-12-03 03:47:56 +0000390 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000391
Mike Stumpd0fe5362009-11-04 00:53:51 +0000392 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000393 ShouldAdjustReturnPointer = false;
Mike Stumpd0fe5362009-11-04 00:53:51 +0000394 }
395 }
396
Mike Stump736529e2009-11-03 02:12:59 +0000397 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
398
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000399 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
400 e = MD->param_end();
401 i != e; ++i) {
402 ParmVarDecl *D = *i;
403 QualType ArgType = D->getType();
404
405 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman6804fa22009-12-03 04:49:52 +0000406 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
407 SourceLocation());
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000408 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
409 }
410
John McCall04a67a62010-02-05 21:31:56 +0000411 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
412 FPT->getCallConv(),
413 FPT->getNoReturnAttr()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000414 Callee, ReturnValueSlot(), CallArgs, MD);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000415 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stump03e777e2009-11-05 06:32:02 +0000416 bool CanBeZero = !(ResultType->isReferenceType()
417 // FIXME: attr nonnull can't be zero either
418 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stumpc902d222009-11-03 16:59:27 +0000419 // Do the return result adjustment.
Mike Stump03e777e2009-11-05 06:32:02 +0000420 if (CanBeZero) {
421 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
422 llvm::BasicBlock *ZeroBlock = createBasicBlock();
423 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stump7c276b82009-11-05 06:12:26 +0000424
Mike Stump03e777e2009-11-05 06:32:02 +0000425 const llvm::Type *Ty = RV.getScalarVal()->getType();
426 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
427 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
428 NonZeroBlock, ZeroBlock);
429 EmitBlock(NonZeroBlock);
Anders Carlsson7622cd32009-11-26 03:09:37 +0000430 llvm::Value *NZ =
431 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stump03e777e2009-11-05 06:32:02 +0000432 EmitBranch(ContBlock);
433 EmitBlock(ZeroBlock);
434 llvm::Value *Z = RV.getScalarVal();
435 EmitBlock(ContBlock);
436 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
437 RVOrZero->reserveOperandSpace(2);
438 RVOrZero->addIncoming(NZ, NonZeroBlock);
439 RVOrZero->addIncoming(Z, ZeroBlock);
440 RV = RValue::get(RVOrZero);
441 } else
Anders Carlsson7622cd32009-11-26 03:09:37 +0000442 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
443 Adjustment.ReturnAdjustment));
Mike Stumpc5dac4e2009-11-02 23:22:01 +0000444 }
445
Mike Stumpf49ed942009-11-02 23:47:45 +0000446 if (!ResultType->isVoidType())
447 EmitReturnOfRValue(RV, ResultType);
448
Mike Stump6e319f62009-09-11 23:25:56 +0000449 FinishFunction();
450 return Fn;
451}
452
Anders Carlssona94822e2009-11-26 02:32:05 +0000453llvm::Constant *
Eli Friedman72649ed2009-12-06 22:01:30 +0000454CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
455 const ThunkAdjustment &ThisAdjustment) {
456 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
457
458 // Compute mangled name
459 llvm::SmallString<256> OutName;
460 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
461 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
462 OutName);
463 else
464 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
465 OutName += '\0';
466 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
467
468 // Get function for mangled name
469 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
470 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
471}
472
473llvm::Constant *
474CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
475 const CovariantThunkAdjustment &Adjustment) {
476 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
477
478 // Compute mangled name
479 llvm::SmallString<256> OutName;
480 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
481 OutName += '\0';
482 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
483
484 // Get function for mangled name
485 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
486 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
487}
488
489void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000490 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
491 if (!AdjPtr)
492 return;
493 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman72649ed2009-12-06 22:01:30 +0000494 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000495 for (unsigned i = 0; i < Adj.size(); i++) {
496 GlobalDecl OGD = Adj[i].first;
497 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman72649ed2009-12-06 22:01:30 +0000498 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
499 CanQualType oret = getContext().getCanonicalType(nc_oret);
500 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
501 CanQualType ret = getContext().getCanonicalType(nc_ret);
502 ThunkAdjustment ReturnAdjustment;
503 if (oret != ret) {
504 QualType qD = nc_ret->getPointeeType();
505 QualType qB = nc_oret->getPointeeType();
506 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
507 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
508 ReturnAdjustment = ComputeThunkAdjustment(D, B);
509 }
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000510 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman72649ed2009-12-06 22:01:30 +0000511 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
512 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
513 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
514 llvm::Constant *FnConst;
515 if (!ReturnAdjustment.isEmpty())
516 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
517 else
518 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
519 if (!isa<llvm::Function>(FnConst)) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000520 llvm::Constant *SubExpr =
521 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
522 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
523 std::string Name = OldFn->getNameStr();
524 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
525 Name.data() + Name.size() + 1));
526 llvm::Constant *NewFnConst;
527 if (!ReturnAdjustment.isEmpty())
528 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
529 else
530 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
531 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
532 NewFn->takeName(OldFn);
533 llvm::Constant *NewPtrForOldDecl =
534 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
535 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
536 OldFn->eraseFromParent();
537 FnConst = NewFn;
Eli Friedman72649ed2009-12-06 22:01:30 +0000538 }
539 llvm::Function *Fn = cast<llvm::Function>(FnConst);
540 if (Fn->isDeclaration()) {
541 llvm::GlobalVariable::LinkageTypes linktype;
542 linktype = llvm::GlobalValue::WeakAnyLinkage;
543 if (!Extern)
544 linktype = llvm::GlobalValue::InternalLinkage;
545 Fn->setLinkage(linktype);
546 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
547 Fn->addFnAttr(llvm::Attribute::NoUnwind);
548 Fn->setAlignment(2);
549 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
550 }
551 }
Eli Friedman72649ed2009-12-06 22:01:30 +0000552 }
553}
554
555llvm::Constant *
Eli Friedman35c98cc2009-12-03 04:27:05 +0000556CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssona94822e2009-11-26 02:32:05 +0000557 const ThunkAdjustment &ThisAdjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000558 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stumped032eb2009-09-04 18:27:16 +0000559 llvm::SmallString<256> OutName;
Mike Stump919d5e52009-12-03 03:47:56 +0000560 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
561 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
562 OutName);
563 } else
564 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssona94822e2009-11-26 02:32:05 +0000565
Mike Stumped032eb2009-09-04 18:27:16 +0000566 llvm::GlobalVariable::LinkageTypes linktype;
567 linktype = llvm::GlobalValue::WeakAnyLinkage;
568 if (!Extern)
569 linktype = llvm::GlobalValue::InternalLinkage;
570 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall183700f2009-09-21 23:43:11 +0000571 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stumped032eb2009-09-04 18:27:16 +0000572 const llvm::FunctionType *FTy =
573 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
574 FPT->isVariadic());
575
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000576 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stumped032eb2009-09-04 18:27:16 +0000577 &getModule());
Mike Stump919d5e52009-12-03 03:47:56 +0000578 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stumped032eb2009-09-04 18:27:16 +0000579 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
580 return m;
581}
582
Anders Carlsson7622cd32009-11-26 03:09:37 +0000583llvm::Constant *
Mike Stump919d5e52009-12-03 03:47:56 +0000584CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson7622cd32009-11-26 03:09:37 +0000585 const CovariantThunkAdjustment &Adjustment) {
Mike Stump919d5e52009-12-03 03:47:56 +0000586 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump6e319f62009-09-11 23:25:56 +0000587 llvm::SmallString<256> OutName;
Anders Carlsson7622cd32009-11-26 03:09:37 +0000588 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump6e319f62009-09-11 23:25:56 +0000589 llvm::GlobalVariable::LinkageTypes linktype;
590 linktype = llvm::GlobalValue::WeakAnyLinkage;
591 if (!Extern)
592 linktype = llvm::GlobalValue::InternalLinkage;
593 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall183700f2009-09-21 23:43:11 +0000594 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump6e319f62009-09-11 23:25:56 +0000595 const llvm::FunctionType *FTy =
596 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
597 FPT->isVariadic());
598
Daniel Dunbar94fd26d2009-11-21 09:06:22 +0000599 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump6e319f62009-09-11 23:25:56 +0000600 &getModule());
Anders Carlsson7622cd32009-11-26 03:09:37 +0000601 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump6e319f62009-09-11 23:25:56 +0000602 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
603 return m;
604}
605
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000606static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlsson566abee2009-11-13 04:45:41 +0000607 llvm::Value *This, const llvm::Type *Ty) {
608 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson2b358352009-10-03 14:56:57 +0000609
Anders Carlsson566abee2009-11-13 04:45:41 +0000610 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
611 Vtable = CGF.Builder.CreateLoad(Vtable);
612
613 llvm::Value *VFuncPtr =
614 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
615 return CGF.Builder.CreateLoad(VFuncPtr);
616}
617
618llvm::Value *
619CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
620 const llvm::Type *Ty) {
621 MD = MD->getCanonicalDecl();
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000622 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlsson566abee2009-11-13 04:45:41 +0000623
624 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
625}
626
627llvm::Value *
628CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
629 llvm::Value *&This, const llvm::Type *Ty) {
630 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000631 uint64_t VtableIndex =
Anders Carlssona0fdd912009-11-13 17:08:56 +0000632 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlsson566abee2009-11-13 04:45:41 +0000633
634 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpf0070db2009-08-26 20:46:33 +0000635}