blob: a306c857e5aa2c595c4cf0b34b652a9c489b5e90 [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.
66 llvm::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 Lattner2acc6e32011-07-18 04:24:23 +000086 llvm::Type *Int8PtrTy =
Anders Carlsson519c3282010-03-24 00:39:18 +000087 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
88
89 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
90
91 if (NonVirtualAdjustment) {
92 // Do the non-virtual adjustment.
93 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
94 }
95
96 if (VirtualAdjustment) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000097 llvm::Type *PtrDiffTy =
Anders Carlsson519c3282010-03-24 00:39:18 +000098 CGF.ConvertType(CGF.getContext().getPointerDiffType());
99
100 // Do the virtual adjustment.
101 llvm::Value *VTablePtrPtr =
102 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
103
104 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
105
106 llvm::Value *OffsetPtr =
107 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
108
109 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
110
111 // Load the adjustment offset from the vtable.
112 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
113
114 // Adjust our pointer.
115 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
116 }
117
118 // Cast back to the original type.
119 return CGF.Builder.CreateBitCast(V, Ptr->getType());
120}
121
John McCall65005532010-08-04 23:46:35 +0000122static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
123 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000124 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +0000125
John McCall279b5eb2010-08-12 23:36:15 +0000126 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
127 return;
128
John McCall65005532010-08-04 23:46:35 +0000129 // If the thunk has weak/linkonce linkage, but the function must be
130 // emitted in every translation unit that references it, then we can
131 // emit its thunks with hidden visibility, since its thunks must be
132 // emitted when the function is.
133
John McCall7a536902010-08-05 20:39:18 +0000134 // This follows CodeGenModule::setTypeVisibility; see the comments
135 // there for explanation.
John McCall65005532010-08-04 23:46:35 +0000136
137 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
138 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
139 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
140 return;
141
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000142 if (MD->getExplicitVisibility())
John McCall65005532010-08-04 23:46:35 +0000143 return;
144
145 switch (MD->getTemplateSpecializationKind()) {
John McCall65005532010-08-04 23:46:35 +0000146 case TSK_ExplicitInstantiationDefinition:
147 case TSK_ExplicitInstantiationDeclaration:
148 return;
149
John McCall65005532010-08-04 23:46:35 +0000150 case TSK_Undeclared:
151 break;
152
John McCall7a536902010-08-05 20:39:18 +0000153 case TSK_ExplicitSpecialization:
John McCall65005532010-08-04 23:46:35 +0000154 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000155 if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000156 return;
John McCall65005532010-08-04 23:46:35 +0000157 break;
158 }
159
160 // If there's an explicit definition, and that definition is
161 // out-of-line, then we can't assume that all users will have a
162 // definition to emit.
163 const FunctionDecl *Def = 0;
164 if (MD->hasBody(Def) && Def->isOutOfLine())
165 return;
166
167 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
168}
169
John McCall311b4422011-03-09 07:12:35 +0000170#ifndef NDEBUG
171static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
172 const ABIArgInfo &infoR, CanQualType typeR) {
173 return (infoL.getKind() == infoR.getKind() &&
174 (typeL == typeR ||
175 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
176 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
177}
178#endif
179
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000180static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
181 QualType ResultType, RValue RV,
182 const ThunkInfo &Thunk) {
183 // Emit the return adjustment.
184 bool NullCheckValue = !ResultType->isReferenceType();
185
186 llvm::BasicBlock *AdjustNull = 0;
187 llvm::BasicBlock *AdjustNotNull = 0;
188 llvm::BasicBlock *AdjustEnd = 0;
189
190 llvm::Value *ReturnValue = RV.getScalarVal();
191
192 if (NullCheckValue) {
193 AdjustNull = CGF.createBasicBlock("adjust.null");
194 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
195 AdjustEnd = CGF.createBasicBlock("adjust.end");
196
197 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
198 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
199 CGF.EmitBlock(AdjustNotNull);
200 }
201
202 ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
203 Thunk.Return.NonVirtual,
204 Thunk.Return.VBaseOffsetOffset);
205
206 if (NullCheckValue) {
207 CGF.Builder.CreateBr(AdjustEnd);
208 CGF.EmitBlock(AdjustNull);
209 CGF.Builder.CreateBr(AdjustEnd);
210 CGF.EmitBlock(AdjustEnd);
211
212 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
213 PHI->addIncoming(ReturnValue, AdjustNotNull);
214 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
215 AdjustNull);
216 ReturnValue = PHI;
217 }
218
219 return RValue::get(ReturnValue);
220}
221
222// This function does roughly the same thing as GenerateThunk, but in a
223// very different way, so that va_start and va_end work correctly.
224// FIXME: This function assumes "this" is the first non-sret LLVM argument of
225// a function, and that there is an alloca built in the entry block
226// for all accesses to "this".
227// FIXME: This function assumes there is only one "ret" statement per function.
228// FIXME: Cloning isn't correct in the presence of indirect goto!
229// FIXME: This implementation of thunks bloats codesize by duplicating the
230// function definition. There are alternatives:
231// 1. Add some sort of stub support to LLVM for cases where we can
232// do a this adjustment, then a sibcall.
233// 2. We could transform the definition to take a va_list instead of an
234// actual variable argument list, then have the thunks (including a
235// no-op thunk for the regular definition) call va_start/va_end.
236// There's a bit of per-call overhead for this solution, but it's
237// better for codesize if the definition is long.
238void CodeGenFunction::GenerateVarArgsThunk(
239 llvm::Function *Fn,
240 const CGFunctionInfo &FnInfo,
241 GlobalDecl GD, const ThunkInfo &Thunk) {
242 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
243 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
244 QualType ResultType = FPT->getResultType();
245
246 // Get the original function
Chris Lattner2acc6e32011-07-18 04:24:23 +0000247 llvm::Type *Ty =
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000248 CGM.getTypes().GetFunctionType(FnInfo, /*IsVariadic*/true);
249 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
250 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
251
252 // Clone to thunk.
253 llvm::Function *NewFn = llvm::CloneFunction(BaseFn);
254 CGM.getModule().getFunctionList().push_back(NewFn);
255 Fn->replaceAllUsesWith(NewFn);
256 NewFn->takeName(Fn);
257 Fn->eraseFromParent();
258 Fn = NewFn;
259
260 // "Initialize" CGF (minimally).
261 CurFn = Fn;
262
263 // Get the "this" value
264 llvm::Function::arg_iterator AI = Fn->arg_begin();
265 if (CGM.ReturnTypeUsesSRet(FnInfo))
266 ++AI;
267
268 // Find the first store of "this", which will be to the alloca associated
269 // with "this".
270 llvm::Value *ThisPtr = &*AI;
271 llvm::BasicBlock *EntryBB = Fn->begin();
272 llvm::Instruction *ThisStore = 0;
273 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
274 I != E; I++) {
275 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
276 ThisStore = cast<llvm::StoreInst>(I);
277 break;
278 }
279 }
280 assert(ThisStore && "Store of this should be in entry block?");
281 // Adjust "this", if necessary.
282 Builder.SetInsertPoint(ThisStore);
283 llvm::Value *AdjustedThisPtr =
284 PerformTypeAdjustment(*this, ThisPtr,
285 Thunk.This.NonVirtual,
286 Thunk.This.VCallOffsetOffset);
287 ThisStore->setOperand(0, AdjustedThisPtr);
288
289 if (!Thunk.Return.isEmpty()) {
290 // Fix up the returned value, if necessary.
291 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
292 llvm::Instruction *T = I->getTerminator();
293 if (isa<llvm::ReturnInst>(T)) {
294 RValue RV = RValue::get(T->getOperand(0));
295 T->eraseFromParent();
296 Builder.SetInsertPoint(&*I);
297 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
298 Builder.CreateRet(RV.getScalarVal());
299 break;
300 }
301 }
302 }
303}
304
John McCalld26bc762011-03-09 04:27:21 +0000305void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
306 const CGFunctionInfo &FnInfo,
307 GlobalDecl GD, const ThunkInfo &Thunk) {
Anders Carlsson519c3282010-03-24 00:39:18 +0000308 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
309 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
310 QualType ResultType = FPT->getResultType();
311 QualType ThisType = MD->getThisType(getContext());
312
313 FunctionArgList FunctionArgs;
314
315 // FIXME: It would be nice if more of this code could be shared with
316 // CodeGenFunction::GenerateCode.
317
318 // Create the implicit 'this' parameter declaration.
John McCall4c40d982010-08-31 07:33:07 +0000319 CurGD = GD;
320 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000321
322 // Add the rest of the parameters.
323 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
324 E = MD->param_end(); I != E; ++I) {
325 ParmVarDecl *Param = *I;
326
John McCalld26bc762011-03-09 04:27:21 +0000327 FunctionArgs.push_back(Param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000328 }
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000329
John McCalld26bc762011-03-09 04:27:21 +0000330 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
331 SourceLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000332
John McCall4c40d982010-08-31 07:33:07 +0000333 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
334
Anders Carlsson519c3282010-03-24 00:39:18 +0000335 // Adjust the 'this' pointer if necessary.
336 llvm::Value *AdjustedThisPtr =
337 PerformTypeAdjustment(*this, LoadCXXThis(),
338 Thunk.This.NonVirtual,
339 Thunk.This.VCallOffsetOffset);
340
341 CallArgList CallArgs;
342
343 // Add our adjusted 'this' pointer.
Eli Friedman04c9a492011-05-02 17:57:46 +0000344 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000345
346 // Add the rest of the parameters.
347 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
348 E = MD->param_end(); I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +0000349 ParmVarDecl *param = *I;
350 EmitDelegateCallArg(CallArgs, param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000351 }
352
353 // Get our callee.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000354 llvm::Type *Ty =
John McCall4c40d982010-08-31 07:33:07 +0000355 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
Anders Carlsson519c3282010-03-24 00:39:18 +0000356 FPT->isVariadic());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000357 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson519c3282010-03-24 00:39:18 +0000358
John McCalld26bc762011-03-09 04:27:21 +0000359#ifndef NDEBUG
360 const CGFunctionInfo &CallFnInfo =
Eli Friedman03f48612011-08-09 18:16:09 +0000361 CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo());
John McCall311b4422011-03-09 07:12:35 +0000362 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
363 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
364 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
365 assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
366 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
367 assert(CallFnInfo.arg_size() == FnInfo.arg_size());
368 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
369 assert(similar(CallFnInfo.arg_begin()[i].info,
370 CallFnInfo.arg_begin()[i].type,
371 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000372#endif
Anders Carlsson519c3282010-03-24 00:39:18 +0000373
Douglas Gregorcb359df2010-05-20 05:54:35 +0000374 // Determine whether we have a return value slot to use.
375 ReturnValueSlot Slot;
376 if (!ResultType->isVoidType() &&
377 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
378 hasAggregateLLVMType(CurFnInfo->getReturnType()))
379 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
380
Anders Carlsson519c3282010-03-24 00:39:18 +0000381 // Now emit our call.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000382 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
Anders Carlsson519c3282010-03-24 00:39:18 +0000383
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000384 if (!Thunk.Return.isEmpty())
385 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000386
Douglas Gregorcb359df2010-05-20 05:54:35 +0000387 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000388 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000389
390 FinishFunction();
391
Anders Carlsson519c3282010-03-24 00:39:18 +0000392 // Set the right linkage.
John McCall8b242332010-05-25 04:30:21 +0000393 CGM.setFunctionLinkage(MD, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000394
395 // Set the right visibility.
John McCall65005532010-08-04 23:46:35 +0000396 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000397}
398
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000399void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
400 bool UseAvailableExternallyLinkage)
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000401{
John McCalld26bc762011-03-09 04:27:21 +0000402 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD);
403
404 // FIXME: re-use FnInfo in this computation.
Anders Carlsson84c49e42011-02-06 17:15:43 +0000405 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson19879c92010-03-23 17:17:29 +0000406
Anders Carlsson7986ad52010-03-23 18:18:41 +0000407 // Strip off a bitcast if we got one back.
Anders Carlsson13d68982010-03-24 00:35:44 +0000408 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000409 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Anders Carlsson13d68982010-03-24 00:35:44 +0000410 Entry = CE->getOperand(0);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000411 }
412
Anders Carlsson7986ad52010-03-23 18:18:41 +0000413 // There's already a declaration with the same name, check if it has the same
414 // type or if we need to replace it.
Anders Carlsson13d68982010-03-24 00:35:44 +0000415 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000416 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Anders Carlsson13d68982010-03-24 00:35:44 +0000417 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000418
419 // If the types mismatch then we have to rewrite the definition.
420 assert(OldThunkFn->isDeclaration() &&
421 "Shouldn't replace non-declaration");
422
423 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000424 OldThunkFn->setName(StringRef());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000425 Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000426
427 // If needed, replace the old thunk with a bitcast.
428 if (!OldThunkFn->use_empty()) {
429 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000430 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000431 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
432 }
433
434 // Remove the old thunk.
435 OldThunkFn->eraseFromParent();
436 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000437
Anders Carlsson519c3282010-03-24 00:39:18 +0000438 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000439
440 if (!ThunkFn->isDeclaration()) {
441 if (UseAvailableExternallyLinkage) {
442 // There is already a thunk emitted for this function, do nothing.
443 return;
444 }
445
Anders Carlsson22df7b12011-02-06 20:09:44 +0000446 // If a function has a body, it should have available_externally linkage.
447 assert(ThunkFn->hasAvailableExternallyLinkage() &&
448 "Function should have available_externally linkage!");
449
450 // Change the linkage.
451 CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
452 return;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000453 }
454
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000455 if (ThunkFn->isVarArg()) {
456 // Varargs thunks are special; we can't just generate a call because
457 // we can't copy the varargs. Our implementation is rather
458 // expensive/sucky at the moment, so don't generate the thunk unless
459 // we have to.
460 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
461 if (!UseAvailableExternallyLinkage)
462 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
463 } else {
464 // Normal thunk body generation.
465 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
466 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000467
468 if (UseAvailableExternallyLinkage)
469 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
470}
471
472void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
473 const ThunkInfo &Thunk) {
474 // We only want to do this when building with optimizations.
475 if (!CGM.getCodeGenOpts().OptimizationLevel)
476 return;
477
478 // We can't emit thunks for member functions with incomplete types.
479 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000480 if (!CGM.getTypes().isFuncTypeConvertible(
481 cast<FunctionType>(MD->getType().getTypePtr())))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000482 return;
483
484 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000485}
486
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000487void CodeGenVTables::EmitThunks(GlobalDecl GD)
488{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000489 const CXXMethodDecl *MD =
490 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
491
492 // We don't need to generate thunks for the base destructor.
493 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
494 return;
495
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000496 const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
497 VTContext.getThunkInfo(MD);
498 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000499 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000500
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000501 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
502 EmitThunk(GD, (*ThunkInfoVector)[I],
503 /*UseAvailableExternallyLinkage=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000504}
505
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000506llvm::Constant *
507CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000508 const VTableComponent *Components,
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000509 unsigned NumComponents,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000510 const VTableLayout::VTableThunkTy *VTableThunks,
511 unsigned NumVTableThunks) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000512 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000513
Chris Lattner2acc6e32011-07-18 04:24:23 +0000514 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000515
Chris Lattner2acc6e32011-07-18 04:24:23 +0000516 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000517 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
518
519 QualType ClassType = CGM.getContext().getTagDeclType(RD);
520 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
521
522 unsigned NextVTableThunkIndex = 0;
523
Anders Carlsson67d568a2010-03-29 05:40:50 +0000524 llvm::Constant* PureVirtualFn = 0;
525
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000526 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000527 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000528
529 llvm::Constant *Init = 0;
530
531 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000532 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000533 Init = llvm::ConstantInt::get(PtrDiffTy,
534 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000535 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
536 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000537 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000538 Init = llvm::ConstantInt::get(PtrDiffTy,
539 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000540 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
541 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000542 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000543 Init = llvm::ConstantInt::get(PtrDiffTy,
544 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000545 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
546 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000547 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000548 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
549 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000550 case VTableComponent::CK_FunctionPointer:
551 case VTableComponent::CK_CompleteDtorPointer:
552 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000553 GlobalDecl GD;
554
555 // Get the right global decl.
556 switch (Component.getKind()) {
557 default:
558 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000559 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000560 GD = Component.getFunctionDecl();
561 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000562 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000563 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
564 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000565 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000566 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
567 break;
568 }
569
Anders Carlsson67d568a2010-03-29 05:40:50 +0000570 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
571 // We have a pure virtual member function.
572 if (!PureVirtualFn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000573 llvm::FunctionType *Ty =
Anders Carlsson67d568a2010-03-29 05:40:50 +0000574 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
575 /*isVarArg=*/false);
576 PureVirtualFn =
577 CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
578 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
579 Int8PtrTy);
580 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000581
Anders Carlsson67d568a2010-03-29 05:40:50 +0000582 Init = PureVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000583 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000584 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000585 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000586 VTableThunks[NextVTableThunkIndex].first == I) {
587 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000588
Anders Carlsson84c49e42011-02-06 17:15:43 +0000589 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000590 MaybeEmitThunkAvailableExternally(GD, Thunk);
591
Anders Carlsson67d568a2010-03-29 05:40:50 +0000592 NextVTableThunkIndex++;
593 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000594 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000595
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000596 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000597 }
598
599 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000600 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000601 break;
602 }
603
Anders Carlsson94464812010-04-10 19:13:06 +0000604 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000605 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
606 break;
607 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000608
609 Inits.push_back(Init);
610 }
611
612 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000613 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000614}
615
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000616llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000617 llvm::GlobalVariable *&VTable = VTables[RD];
618 if (VTable)
619 return VTable;
620
621 // We may need to generate a definition for this vtable.
622 if (ShouldEmitVTableInThisTU(RD))
623 CGM.DeferredVTables.push_back(RD);
624
Anders Carlsson5c6c1d92010-03-24 03:57:14 +0000625 llvm::SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000626 llvm::raw_svector_ostream Out(OutName);
627 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
628 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000629 StringRef Name = OutName.str();
Mike Stump85615df2009-11-19 04:04:36 +0000630
Chris Lattner2acc6e32011-07-18 04:24:23 +0000631 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlssonccd83d72010-03-24 16:42:11 +0000632 llvm::ArrayType *ArrayType =
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000633 llvm::ArrayType::get(Int8PtrTy,
634 VTContext.getVTableLayout(RD).getNumVTableComponents());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000635
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000636 VTable =
Anders Carlsson96eaf292011-01-29 18:25:07 +0000637 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
638 llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000639 VTable->setUnnamedAddr(true);
640 return VTable;
Mike Stump380dd752009-11-10 07:44:33 +0000641}
Mike Stump8cfcb522009-11-11 20:26:26 +0000642
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000643void
644CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
645 llvm::GlobalVariable::LinkageTypes Linkage,
646 const CXXRecordDecl *RD) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000647 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
648
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000649 // Create and set the initializer.
650 llvm::Constant *Init =
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000651 CreateVTableInitializer(RD,
652 VTLayout.vtable_component_begin(),
653 VTLayout.getNumVTableComponents(),
654 VTLayout.vtable_thunk_begin(),
655 VTLayout.getNumVTableThunks());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000656 VTable->setInitializer(Init);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000657
658 // Set the correct linkage.
659 VTable->setLinkage(Linkage);
Douglas Gregorc66bcfd2010-06-14 23:41:45 +0000660
661 // Set the right visibility.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000662 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000663}
664
Anders Carlssonff143f82010-03-25 00:35:49 +0000665llvm::GlobalVariable *
666CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000667 const BaseSubobject &Base,
668 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000669 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000670 VTableAddressPointsMapTy& AddressPoints) {
Peter Collingbourneab172b52011-09-26 01:57:04 +0000671 llvm::OwningPtr<VTableLayout> VTLayout(
672 VTContext.createConstructionVTableLayout(Base.getBase(),
673 Base.getBaseOffset(),
674 BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000675
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000676 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000677 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000678
679 // Get the mangled construction vtable name.
680 llvm::SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000681 llvm::raw_svector_ostream Out(OutName);
John McCall4c40d982010-08-31 07:33:07 +0000682 CGM.getCXXABI().getMangleContext().
Ken Dyck4230d522011-03-24 01:21:01 +0000683 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
684 Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000685 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000686 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000687
Chris Lattner2acc6e32011-07-18 04:24:23 +0000688 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000689 llvm::ArrayType *ArrayType =
Peter Collingbourneab172b52011-09-26 01:57:04 +0000690 llvm::ArrayType::get(Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000691
692 // Create the variable that will hold the construction vtable.
693 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000694 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
695 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
696
697 // V-tables are always unnamed_addr.
698 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000699
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000700 // Create and set the initializer.
701 llvm::Constant *Init =
702 CreateVTableInitializer(Base.getBase(),
Peter Collingbourneab172b52011-09-26 01:57:04 +0000703 VTLayout->vtable_component_begin(),
704 VTLayout->getNumVTableComponents(),
705 VTLayout->vtable_thunk_begin(),
706 VTLayout->getNumVTableThunks());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000707 VTable->setInitializer(Init);
708
Anders Carlssonff143f82010-03-25 00:35:49 +0000709 return VTable;
710}
711
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000712void
713CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
714 const CXXRecordDecl *RD) {
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000715 llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
716 if (VTable->hasInitializer())
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000717 return;
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000718
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000719 EmitVTableDefinition(VTable, Linkage, RD);
720
Anders Carlsson1cbce122011-01-29 19:16:51 +0000721 if (RD->getNumVBases()) {
722 llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
723 EmitVTTDefinition(VTT, Linkage, RD);
724 }
Douglas Gregor1e201b42010-04-08 15:52:03 +0000725
726 // If this is the magic class __cxxabiv1::__fundamental_type_info,
727 // we will emit the typeinfo for the fundamental types. This is the
728 // same behaviour as GCC.
729 const DeclContext *DC = RD->getDeclContext();
730 if (RD->getIdentifier() &&
731 RD->getIdentifier()->isStr("__fundamental_type_info") &&
732 isa<NamespaceDecl>(DC) &&
733 cast<NamespaceDecl>(DC)->getIdentifier() &&
734 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
735 DC->getParent()->isTranslationUnit())
736 CGM.EmitFundamentalRTTIDescriptors();
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000737}