blob: f13cae11a6e209c971f47c20e902a2baf0d2eb4a [file] [log] [blame]
Anders Carlsson046c2942010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlssondbd920c2009-10-11 22:13:54 +00002//
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 of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
John McCall7a536902010-08-05 20:39:18 +000019#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000020#include "llvm/ADT/DenseSet.h"
Anders Carlssonb9021e92010-02-27 16:18:19 +000021#include "llvm/ADT/SetVector.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000022#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000023#include "llvm/Support/Format.h"
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000024#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson5e454aa2010-03-17 20:06:32 +000025#include <algorithm>
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000026#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000027
28using namespace clang;
29using namespace CodeGen;
30
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000031CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32 : CGM(CGM), VTContext(CGM.getContext()) { }
33
Argyrios Kyrtzidisd2c47bd2010-10-11 03:25:57 +000034bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
35 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
36
37 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
38 if (TSK == TSK_ExplicitInstantiationDeclaration)
39 return false;
40
41 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
42 if (!KeyFunction)
43 return true;
44
45 // Itanium C++ ABI, 5.2.6 Instantiated Templates:
46 // An instantiation of a class template requires:
47 // - In the object where instantiated, the virtual table...
48 if (TSK == TSK_ImplicitInstantiation ||
49 TSK == TSK_ExplicitInstantiationDefinition)
50 return true;
51
Anders Carlsson6d7f8472011-01-30 20:45:54 +000052 // If we're building with optimization, we always emit VTables since that
53 // allows for virtual function calls to be devirtualized.
54 // (We don't want to do this in -fapple-kext mode however).
55 if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext)
56 return true;
57
Argyrios Kyrtzidisd2c47bd2010-10-11 03:25:57 +000058 return KeyFunction->hasBody();
59}
60
Anders Carlsson19879c92010-03-23 17:17:29 +000061llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlsson84c49e42011-02-06 17:15:43 +000062 const ThunkInfo &Thunk) {
Anders Carlsson19879c92010-03-23 17:17:29 +000063 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
64
65 // Compute the mangled name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000066 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +000067 llvm::raw_svector_ostream Out(Name);
Anders Carlsson19879c92010-03-23 17:17:29 +000068 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall4c40d982010-08-31 07:33:07 +000069 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindolaf0be9792011-02-11 02:52:17 +000070 Thunk.This, Out);
Anders Carlsson19879c92010-03-23 17:17:29 +000071 else
Rafael Espindolaf0be9792011-02-11 02:52:17 +000072 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
73 Out.flush();
74
Chris Lattner2acc6e32011-07-18 04:24:23 +000075 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson84c49e42011-02-06 17:15:43 +000076 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
Anders Carlsson19879c92010-03-23 17:17:29 +000077}
78
Anders Carlsson519c3282010-03-24 00:39:18 +000079static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
80 llvm::Value *Ptr,
81 int64_t NonVirtualAdjustment,
82 int64_t VirtualAdjustment) {
83 if (!NonVirtualAdjustment && !VirtualAdjustment)
84 return Ptr;
85
Chris Lattner8b418682012-02-07 00:39:47 +000086 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Anders Carlsson519c3282010-03-24 00:39:18 +000087 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
88
89 if (NonVirtualAdjustment) {
90 // Do the non-virtual adjustment.
91 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
92 }
93
94 if (VirtualAdjustment) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000095 llvm::Type *PtrDiffTy =
Anders Carlsson519c3282010-03-24 00:39:18 +000096 CGF.ConvertType(CGF.getContext().getPointerDiffType());
97
98 // Do the virtual adjustment.
99 llvm::Value *VTablePtrPtr =
100 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
101
102 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
103
104 llvm::Value *OffsetPtr =
105 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
106
107 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
108
109 // Load the adjustment offset from the vtable.
110 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
111
112 // Adjust our pointer.
113 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
114 }
115
116 // Cast back to the original type.
117 return CGF.Builder.CreateBitCast(V, Ptr->getType());
118}
119
John McCall65005532010-08-04 23:46:35 +0000120static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
121 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000122 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +0000123
John McCall279b5eb2010-08-12 23:36:15 +0000124 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
125 return;
126
John McCall65005532010-08-04 23:46:35 +0000127 // If the thunk has weak/linkonce linkage, but the function must be
128 // emitted in every translation unit that references it, then we can
129 // emit its thunks with hidden visibility, since its thunks must be
130 // emitted when the function is.
131
John McCall7a536902010-08-05 20:39:18 +0000132 // This follows CodeGenModule::setTypeVisibility; see the comments
133 // there for explanation.
John McCall65005532010-08-04 23:46:35 +0000134
135 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
136 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
137 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
138 return;
139
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000140 if (MD->getExplicitVisibility())
John McCall65005532010-08-04 23:46:35 +0000141 return;
142
143 switch (MD->getTemplateSpecializationKind()) {
John McCall65005532010-08-04 23:46:35 +0000144 case TSK_ExplicitInstantiationDefinition:
145 case TSK_ExplicitInstantiationDeclaration:
146 return;
147
John McCall65005532010-08-04 23:46:35 +0000148 case TSK_Undeclared:
149 break;
150
John McCall7a536902010-08-05 20:39:18 +0000151 case TSK_ExplicitSpecialization:
John McCall65005532010-08-04 23:46:35 +0000152 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000153 if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000154 return;
John McCall65005532010-08-04 23:46:35 +0000155 break;
156 }
157
158 // If there's an explicit definition, and that definition is
159 // out-of-line, then we can't assume that all users will have a
160 // definition to emit.
161 const FunctionDecl *Def = 0;
162 if (MD->hasBody(Def) && Def->isOutOfLine())
163 return;
164
165 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
166}
167
John McCall311b4422011-03-09 07:12:35 +0000168#ifndef NDEBUG
169static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
170 const ABIArgInfo &infoR, CanQualType typeR) {
171 return (infoL.getKind() == infoR.getKind() &&
172 (typeL == typeR ||
173 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
174 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
175}
176#endif
177
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000178static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
179 QualType ResultType, RValue RV,
180 const ThunkInfo &Thunk) {
181 // Emit the return adjustment.
182 bool NullCheckValue = !ResultType->isReferenceType();
183
184 llvm::BasicBlock *AdjustNull = 0;
185 llvm::BasicBlock *AdjustNotNull = 0;
186 llvm::BasicBlock *AdjustEnd = 0;
187
188 llvm::Value *ReturnValue = RV.getScalarVal();
189
190 if (NullCheckValue) {
191 AdjustNull = CGF.createBasicBlock("adjust.null");
192 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
193 AdjustEnd = CGF.createBasicBlock("adjust.end");
194
195 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
196 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
197 CGF.EmitBlock(AdjustNotNull);
198 }
199
200 ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
201 Thunk.Return.NonVirtual,
202 Thunk.Return.VBaseOffsetOffset);
203
204 if (NullCheckValue) {
205 CGF.Builder.CreateBr(AdjustEnd);
206 CGF.EmitBlock(AdjustNull);
207 CGF.Builder.CreateBr(AdjustEnd);
208 CGF.EmitBlock(AdjustEnd);
209
210 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
211 PHI->addIncoming(ReturnValue, AdjustNotNull);
212 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
213 AdjustNull);
214 ReturnValue = PHI;
215 }
216
217 return RValue::get(ReturnValue);
218}
219
220// This function does roughly the same thing as GenerateThunk, but in a
221// very different way, so that va_start and va_end work correctly.
222// FIXME: This function assumes "this" is the first non-sret LLVM argument of
223// a function, and that there is an alloca built in the entry block
224// for all accesses to "this".
225// FIXME: This function assumes there is only one "ret" statement per function.
226// FIXME: Cloning isn't correct in the presence of indirect goto!
227// FIXME: This implementation of thunks bloats codesize by duplicating the
228// function definition. There are alternatives:
229// 1. Add some sort of stub support to LLVM for cases where we can
230// do a this adjustment, then a sibcall.
231// 2. We could transform the definition to take a va_list instead of an
232// actual variable argument list, then have the thunks (including a
233// no-op thunk for the regular definition) call va_start/va_end.
234// There's a bit of per-call overhead for this solution, but it's
235// better for codesize if the definition is long.
236void CodeGenFunction::GenerateVarArgsThunk(
237 llvm::Function *Fn,
238 const CGFunctionInfo &FnInfo,
239 GlobalDecl GD, const ThunkInfo &Thunk) {
240 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
241 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
242 QualType ResultType = FPT->getResultType();
243
244 // Get the original function
Chris Lattner2acc6e32011-07-18 04:24:23 +0000245 llvm::Type *Ty =
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000246 CGM.getTypes().GetFunctionType(FnInfo, /*IsVariadic*/true);
247 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
248 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
249
250 // Clone to thunk.
251 llvm::Function *NewFn = llvm::CloneFunction(BaseFn);
252 CGM.getModule().getFunctionList().push_back(NewFn);
253 Fn->replaceAllUsesWith(NewFn);
254 NewFn->takeName(Fn);
255 Fn->eraseFromParent();
256 Fn = NewFn;
257
258 // "Initialize" CGF (minimally).
259 CurFn = Fn;
260
261 // Get the "this" value
262 llvm::Function::arg_iterator AI = Fn->arg_begin();
263 if (CGM.ReturnTypeUsesSRet(FnInfo))
264 ++AI;
265
266 // Find the first store of "this", which will be to the alloca associated
267 // with "this".
268 llvm::Value *ThisPtr = &*AI;
269 llvm::BasicBlock *EntryBB = Fn->begin();
270 llvm::Instruction *ThisStore = 0;
271 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
272 I != E; I++) {
273 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
274 ThisStore = cast<llvm::StoreInst>(I);
275 break;
276 }
277 }
278 assert(ThisStore && "Store of this should be in entry block?");
279 // Adjust "this", if necessary.
280 Builder.SetInsertPoint(ThisStore);
281 llvm::Value *AdjustedThisPtr =
282 PerformTypeAdjustment(*this, ThisPtr,
283 Thunk.This.NonVirtual,
284 Thunk.This.VCallOffsetOffset);
285 ThisStore->setOperand(0, AdjustedThisPtr);
286
287 if (!Thunk.Return.isEmpty()) {
288 // Fix up the returned value, if necessary.
289 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
290 llvm::Instruction *T = I->getTerminator();
291 if (isa<llvm::ReturnInst>(T)) {
292 RValue RV = RValue::get(T->getOperand(0));
293 T->eraseFromParent();
294 Builder.SetInsertPoint(&*I);
295 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
296 Builder.CreateRet(RV.getScalarVal());
297 break;
298 }
299 }
300 }
301}
302
John McCalld26bc762011-03-09 04:27:21 +0000303void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
304 const CGFunctionInfo &FnInfo,
305 GlobalDecl GD, const ThunkInfo &Thunk) {
Anders Carlsson519c3282010-03-24 00:39:18 +0000306 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
307 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
308 QualType ResultType = FPT->getResultType();
309 QualType ThisType = MD->getThisType(getContext());
310
311 FunctionArgList FunctionArgs;
312
313 // FIXME: It would be nice if more of this code could be shared with
314 // CodeGenFunction::GenerateCode.
315
316 // Create the implicit 'this' parameter declaration.
John McCall4c40d982010-08-31 07:33:07 +0000317 CurGD = GD;
318 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000319
320 // Add the rest of the parameters.
321 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
322 E = MD->param_end(); I != E; ++I) {
323 ParmVarDecl *Param = *I;
324
John McCalld26bc762011-03-09 04:27:21 +0000325 FunctionArgs.push_back(Param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000326 }
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000327
John McCalld26bc762011-03-09 04:27:21 +0000328 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
329 SourceLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000330
John McCall4c40d982010-08-31 07:33:07 +0000331 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
332
Anders Carlsson519c3282010-03-24 00:39:18 +0000333 // Adjust the 'this' pointer if necessary.
334 llvm::Value *AdjustedThisPtr =
335 PerformTypeAdjustment(*this, LoadCXXThis(),
336 Thunk.This.NonVirtual,
337 Thunk.This.VCallOffsetOffset);
338
339 CallArgList CallArgs;
340
341 // Add our adjusted 'this' pointer.
Eli Friedman04c9a492011-05-02 17:57:46 +0000342 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000343
344 // Add the rest of the parameters.
345 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
346 E = MD->param_end(); I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +0000347 ParmVarDecl *param = *I;
348 EmitDelegateCallArg(CallArgs, param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000349 }
350
351 // Get our callee.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000352 llvm::Type *Ty =
John McCall4c40d982010-08-31 07:33:07 +0000353 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
Anders Carlsson519c3282010-03-24 00:39:18 +0000354 FPT->isVariadic());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000355 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson519c3282010-03-24 00:39:18 +0000356
John McCalld26bc762011-03-09 04:27:21 +0000357#ifndef NDEBUG
358 const CGFunctionInfo &CallFnInfo =
Eli Friedman03f48612011-08-09 18:16:09 +0000359 CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo());
John McCall311b4422011-03-09 07:12:35 +0000360 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
361 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
362 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
363 assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
364 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
365 assert(CallFnInfo.arg_size() == FnInfo.arg_size());
366 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
367 assert(similar(CallFnInfo.arg_begin()[i].info,
368 CallFnInfo.arg_begin()[i].type,
369 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000370#endif
Anders Carlsson519c3282010-03-24 00:39:18 +0000371
Douglas Gregorcb359df2010-05-20 05:54:35 +0000372 // Determine whether we have a return value slot to use.
373 ReturnValueSlot Slot;
374 if (!ResultType->isVoidType() &&
375 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
376 hasAggregateLLVMType(CurFnInfo->getReturnType()))
377 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
378
Anders Carlsson519c3282010-03-24 00:39:18 +0000379 // Now emit our call.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000380 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
Anders Carlsson519c3282010-03-24 00:39:18 +0000381
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000382 if (!Thunk.Return.isEmpty())
383 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000384
Douglas Gregorcb359df2010-05-20 05:54:35 +0000385 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000386 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000387
388 FinishFunction();
389
Anders Carlsson519c3282010-03-24 00:39:18 +0000390 // Set the right linkage.
John McCall8b242332010-05-25 04:30:21 +0000391 CGM.setFunctionLinkage(MD, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000392
393 // Set the right visibility.
John McCall65005532010-08-04 23:46:35 +0000394 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000395}
396
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000397void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
398 bool UseAvailableExternallyLinkage)
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000399{
John McCalld26bc762011-03-09 04:27:21 +0000400 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD);
401
402 // FIXME: re-use FnInfo in this computation.
Anders Carlsson84c49e42011-02-06 17:15:43 +0000403 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson19879c92010-03-23 17:17:29 +0000404
Anders Carlsson7986ad52010-03-23 18:18:41 +0000405 // Strip off a bitcast if we got one back.
Anders Carlsson13d68982010-03-24 00:35:44 +0000406 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000407 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Anders Carlsson13d68982010-03-24 00:35:44 +0000408 Entry = CE->getOperand(0);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000409 }
410
Anders Carlsson7986ad52010-03-23 18:18:41 +0000411 // There's already a declaration with the same name, check if it has the same
412 // type or if we need to replace it.
Anders Carlsson13d68982010-03-24 00:35:44 +0000413 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000414 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Anders Carlsson13d68982010-03-24 00:35:44 +0000415 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000416
417 // If the types mismatch then we have to rewrite the definition.
418 assert(OldThunkFn->isDeclaration() &&
419 "Shouldn't replace non-declaration");
420
421 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000422 OldThunkFn->setName(StringRef());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000423 Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000424
425 // If needed, replace the old thunk with a bitcast.
426 if (!OldThunkFn->use_empty()) {
427 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000428 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000429 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
430 }
431
432 // Remove the old thunk.
433 OldThunkFn->eraseFromParent();
434 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000435
Anders Carlsson519c3282010-03-24 00:39:18 +0000436 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000437
438 if (!ThunkFn->isDeclaration()) {
439 if (UseAvailableExternallyLinkage) {
440 // There is already a thunk emitted for this function, do nothing.
441 return;
442 }
443
Anders Carlsson22df7b12011-02-06 20:09:44 +0000444 // If a function has a body, it should have available_externally linkage.
445 assert(ThunkFn->hasAvailableExternallyLinkage() &&
446 "Function should have available_externally linkage!");
447
448 // Change the linkage.
449 CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
450 return;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000451 }
452
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000453 if (ThunkFn->isVarArg()) {
454 // Varargs thunks are special; we can't just generate a call because
455 // we can't copy the varargs. Our implementation is rather
456 // expensive/sucky at the moment, so don't generate the thunk unless
457 // we have to.
458 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
459 if (!UseAvailableExternallyLinkage)
460 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
461 } else {
462 // Normal thunk body generation.
463 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
464 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000465
466 if (UseAvailableExternallyLinkage)
467 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
468}
469
470void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
471 const ThunkInfo &Thunk) {
472 // We only want to do this when building with optimizations.
473 if (!CGM.getCodeGenOpts().OptimizationLevel)
474 return;
475
476 // We can't emit thunks for member functions with incomplete types.
477 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000478 if (!CGM.getTypes().isFuncTypeConvertible(
479 cast<FunctionType>(MD->getType().getTypePtr())))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000480 return;
481
482 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000483}
484
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000485void CodeGenVTables::EmitThunks(GlobalDecl GD)
486{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000487 const CXXMethodDecl *MD =
488 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
489
490 // We don't need to generate thunks for the base destructor.
491 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
492 return;
493
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000494 const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
495 VTContext.getThunkInfo(MD);
496 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000497 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000498
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000499 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
500 EmitThunk(GD, (*ThunkInfoVector)[I],
501 /*UseAvailableExternallyLinkage=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000502}
503
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000504llvm::Constant *
505CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000506 const VTableComponent *Components,
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000507 unsigned NumComponents,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000508 const VTableLayout::VTableThunkTy *VTableThunks,
509 unsigned NumVTableThunks) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000510 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000511
Chris Lattner8b418682012-02-07 00:39:47 +0000512 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000513
Chris Lattner2acc6e32011-07-18 04:24:23 +0000514 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000515 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
516
517 QualType ClassType = CGM.getContext().getTagDeclType(RD);
518 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
519
520 unsigned NextVTableThunkIndex = 0;
521
Anders Carlsson67d568a2010-03-29 05:40:50 +0000522 llvm::Constant* PureVirtualFn = 0;
523
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000524 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000525 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000526
527 llvm::Constant *Init = 0;
528
529 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000530 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000531 Init = llvm::ConstantInt::get(PtrDiffTy,
532 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000533 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
534 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000535 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000536 Init = llvm::ConstantInt::get(PtrDiffTy,
537 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000538 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
539 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000540 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000541 Init = llvm::ConstantInt::get(PtrDiffTy,
542 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000543 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
544 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000545 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000546 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
547 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000548 case VTableComponent::CK_FunctionPointer:
549 case VTableComponent::CK_CompleteDtorPointer:
550 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000551 GlobalDecl GD;
552
553 // Get the right global decl.
554 switch (Component.getKind()) {
555 default:
556 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000557 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000558 GD = Component.getFunctionDecl();
559 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000560 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000561 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
562 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000563 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000564 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
565 break;
566 }
567
Anders Carlsson67d568a2010-03-29 05:40:50 +0000568 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
569 // We have a pure virtual member function.
570 if (!PureVirtualFn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000571 llvm::FunctionType *Ty =
Chris Lattner8b418682012-02-07 00:39:47 +0000572 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000573 PureVirtualFn =
574 CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
575 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
576 Int8PtrTy);
577 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000578
Anders Carlsson67d568a2010-03-29 05:40:50 +0000579 Init = PureVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000580 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000581 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000582 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000583 VTableThunks[NextVTableThunkIndex].first == I) {
584 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000585
Anders Carlsson84c49e42011-02-06 17:15:43 +0000586 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000587 MaybeEmitThunkAvailableExternally(GD, Thunk);
588
Anders Carlsson67d568a2010-03-29 05:40:50 +0000589 NextVTableThunkIndex++;
590 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000591 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000592
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000593 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000594 }
595
596 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000597 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000598 break;
599 }
600
Anders Carlsson94464812010-04-10 19:13:06 +0000601 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000602 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
603 break;
604 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000605
606 Inits.push_back(Init);
607 }
608
609 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000610 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000611}
612
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000613llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000614 llvm::GlobalVariable *&VTable = VTables[RD];
615 if (VTable)
616 return VTable;
617
618 // We may need to generate a definition for this vtable.
619 if (ShouldEmitVTableInThisTU(RD))
620 CGM.DeferredVTables.push_back(RD);
621
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000622 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000623 llvm::raw_svector_ostream Out(OutName);
624 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
625 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000626 StringRef Name = OutName.str();
Mike Stump85615df2009-11-19 04:04:36 +0000627
Anders Carlssonccd83d72010-03-24 16:42:11 +0000628 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000629 llvm::ArrayType::get(CGM.Int8PtrTy,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000630 VTContext.getVTableLayout(RD).getNumVTableComponents());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000631
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000632 VTable =
Anders Carlsson96eaf292011-01-29 18:25:07 +0000633 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
634 llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000635 VTable->setUnnamedAddr(true);
636 return VTable;
Mike Stump380dd752009-11-10 07:44:33 +0000637}
Mike Stump8cfcb522009-11-11 20:26:26 +0000638
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000639void
640CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
641 llvm::GlobalVariable::LinkageTypes Linkage,
642 const CXXRecordDecl *RD) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000643 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
644
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000645 // Create and set the initializer.
646 llvm::Constant *Init =
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000647 CreateVTableInitializer(RD,
648 VTLayout.vtable_component_begin(),
649 VTLayout.getNumVTableComponents(),
650 VTLayout.vtable_thunk_begin(),
651 VTLayout.getNumVTableThunks());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000652 VTable->setInitializer(Init);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000653
654 // Set the correct linkage.
655 VTable->setLinkage(Linkage);
Douglas Gregorc66bcfd2010-06-14 23:41:45 +0000656
657 // Set the right visibility.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000658 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000659}
660
Anders Carlssonff143f82010-03-25 00:35:49 +0000661llvm::GlobalVariable *
662CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000663 const BaseSubobject &Base,
664 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000665 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000666 VTableAddressPointsMapTy& AddressPoints) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000667 OwningPtr<VTableLayout> VTLayout(
Peter Collingbourneab172b52011-09-26 01:57:04 +0000668 VTContext.createConstructionVTableLayout(Base.getBase(),
669 Base.getBaseOffset(),
670 BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000671
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000672 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000673 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000674
675 // Get the mangled construction vtable name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000676 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000677 llvm::raw_svector_ostream Out(OutName);
John McCall4c40d982010-08-31 07:33:07 +0000678 CGM.getCXXABI().getMangleContext().
Ken Dyck4230d522011-03-24 01:21:01 +0000679 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
680 Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000681 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000682 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000683
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000684 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000685 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000686
687 // Create the variable that will hold the construction vtable.
688 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000689 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
690 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
691
692 // V-tables are always unnamed_addr.
693 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000694
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000695 // Create and set the initializer.
696 llvm::Constant *Init =
697 CreateVTableInitializer(Base.getBase(),
Peter Collingbourneab172b52011-09-26 01:57:04 +0000698 VTLayout->vtable_component_begin(),
699 VTLayout->getNumVTableComponents(),
700 VTLayout->vtable_thunk_begin(),
701 VTLayout->getNumVTableThunks());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000702 VTable->setInitializer(Init);
703
Anders Carlssonff143f82010-03-25 00:35:49 +0000704 return VTable;
705}
706
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000707void
708CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
709 const CXXRecordDecl *RD) {
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000710 llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
711 if (VTable->hasInitializer())
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000712 return;
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000713
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000714 EmitVTableDefinition(VTable, Linkage, RD);
715
Anders Carlsson1cbce122011-01-29 19:16:51 +0000716 if (RD->getNumVBases()) {
717 llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
718 EmitVTTDefinition(VTT, Linkage, RD);
719 }
Douglas Gregor1e201b42010-04-08 15:52:03 +0000720
721 // If this is the magic class __cxxabiv1::__fundamental_type_info,
722 // we will emit the typeinfo for the fundamental types. This is the
723 // same behaviour as GCC.
724 const DeclContext *DC = RD->getDeclContext();
725 if (RD->getIdentifier() &&
726 RD->getIdentifier()->isStr("__fundamental_type_info") &&
727 isa<NamespaceDecl>(DC) &&
728 cast<NamespaceDecl>(DC)->getIdentifier() &&
729 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
730 DC->getParent()->isTranslationUnit())
731 CGM.EmitFundamentalRTTIDescriptors();
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000732}