blob: b95e8f0713bc133e223ce1ce205373d85102796c [file] [log] [blame]
Anders Carlsson11e51402010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlsson2bb27f52009-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
Anders Carlsson2bb27f52009-10-11 22:13:54 +000014#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
John McCall5513fce92010-08-05 20:39:18 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssond420a312009-11-26 19:32:45 +000021#include "llvm/ADT/DenseSet.h"
Anders Carlssond46ed892010-02-27 16:18:19 +000022#include "llvm/ADT/SetVector.h"
Chandler Carruth94eab4a2010-02-13 10:38:52 +000023#include "llvm/Support/Compiler.h"
Anders Carlsson5d40c6f2010-02-11 08:02:13 +000024#include "llvm/Support/Format.h"
Eli Friedman49a94b12011-05-06 17:27:27 +000025#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson56446142010-03-17 20:06:32 +000026#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000027#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000028
29using namespace clang;
30using namespace CodeGen;
31
Reid Kleckner96f8f932014-02-05 17:27:08 +000032CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000034
Anders Carlssoncd836f02010-03-23 17:17:29 +000035llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000036 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000037 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38
39 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000040 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000041 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000042 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000043 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000044 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000045 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000046 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
47 Out.flush();
48
Chris Lattner2192fe52011-07-18 04:24:23 +000049 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +000050 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
51 /*DontDefer*/ true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000052}
53
John McCallc8bd9c22010-08-04 23:46:35 +000054static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
55 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000056 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000057}
58
John McCall5fe00962011-03-09 07:12:35 +000059#ifndef NDEBUG
60static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61 const ABIArgInfo &infoR, CanQualType typeR) {
62 return (infoL.getKind() == infoR.getKind() &&
63 (typeL == typeR ||
64 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66}
67#endif
68
Eli Friedman49a94b12011-05-06 17:27:27 +000069static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70 QualType ResultType, RValue RV,
71 const ThunkInfo &Thunk) {
72 // Emit the return adjustment.
73 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000074
75 llvm::BasicBlock *AdjustNull = nullptr;
76 llvm::BasicBlock *AdjustNotNull = nullptr;
77 llvm::BasicBlock *AdjustEnd = nullptr;
78
Eli Friedman49a94b12011-05-06 17:27:27 +000079 llvm::Value *ReturnValue = RV.getScalarVal();
80
81 if (NullCheckValue) {
82 AdjustNull = CGF.createBasicBlock("adjust.null");
83 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84 AdjustEnd = CGF.createBasicBlock("adjust.end");
85
86 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88 CGF.EmitBlock(AdjustNotNull);
89 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +000090
91 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
92 Thunk.Return);
93
Eli Friedman49a94b12011-05-06 17:27:27 +000094 if (NullCheckValue) {
95 CGF.Builder.CreateBr(AdjustEnd);
96 CGF.EmitBlock(AdjustNull);
97 CGF.Builder.CreateBr(AdjustEnd);
98 CGF.EmitBlock(AdjustEnd);
99
100 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
101 PHI->addIncoming(ReturnValue, AdjustNotNull);
102 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
103 AdjustNull);
104 ReturnValue = PHI;
105 }
106
107 return RValue::get(ReturnValue);
108}
109
110// This function does roughly the same thing as GenerateThunk, but in a
111// very different way, so that va_start and va_end work correctly.
112// FIXME: This function assumes "this" is the first non-sret LLVM argument of
113// a function, and that there is an alloca built in the entry block
114// for all accesses to "this".
115// FIXME: This function assumes there is only one "ret" statement per function.
116// FIXME: Cloning isn't correct in the presence of indirect goto!
117// FIXME: This implementation of thunks bloats codesize by duplicating the
118// function definition. There are alternatives:
119// 1. Add some sort of stub support to LLVM for cases where we can
120// do a this adjustment, then a sibcall.
121// 2. We could transform the definition to take a va_list instead of an
122// actual variable argument list, then have the thunks (including a
123// no-op thunk for the regular definition) call va_start/va_end.
124// There's a bit of per-call overhead for this solution, but it's
125// better for codesize if the definition is long.
126void CodeGenFunction::GenerateVarArgsThunk(
127 llvm::Function *Fn,
128 const CGFunctionInfo &FnInfo,
129 GlobalDecl GD, const ThunkInfo &Thunk) {
130 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
131 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000132 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000133
134 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000135 assert(FnInfo.isVariadic());
136 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000137 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
138 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
139
140 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000141 llvm::ValueToValueMapTy VMap;
142 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
143 /*ModuleLevelChanges=*/false);
Eli Friedman49a94b12011-05-06 17:27:27 +0000144 CGM.getModule().getFunctionList().push_back(NewFn);
145 Fn->replaceAllUsesWith(NewFn);
146 NewFn->takeName(Fn);
147 Fn->eraseFromParent();
148 Fn = NewFn;
149
150 // "Initialize" CGF (minimally).
151 CurFn = Fn;
152
153 // Get the "this" value
154 llvm::Function::arg_iterator AI = Fn->arg_begin();
155 if (CGM.ReturnTypeUsesSRet(FnInfo))
156 ++AI;
157
158 // Find the first store of "this", which will be to the alloca associated
159 // with "this".
160 llvm::Value *ThisPtr = &*AI;
161 llvm::BasicBlock *EntryBB = Fn->begin();
Craig Topper8a13c412014-05-21 05:09:00 +0000162 llvm::Instruction *ThisStore = nullptr;
Eli Friedman49a94b12011-05-06 17:27:27 +0000163 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
164 I != E; I++) {
165 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
166 ThisStore = cast<llvm::StoreInst>(I);
167 break;
168 }
169 }
170 assert(ThisStore && "Store of this should be in entry block?");
171 // Adjust "this", if necessary.
172 Builder.SetInsertPoint(ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000173 llvm::Value *AdjustedThisPtr =
174 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000175 ThisStore->setOperand(0, AdjustedThisPtr);
176
177 if (!Thunk.Return.isEmpty()) {
178 // Fix up the returned value, if necessary.
179 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
180 llvm::Instruction *T = I->getTerminator();
181 if (isa<llvm::ReturnInst>(T)) {
182 RValue RV = RValue::get(T->getOperand(0));
183 T->eraseFromParent();
184 Builder.SetInsertPoint(&*I);
185 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
186 Builder.CreateRet(RV.getScalarVal());
187 break;
188 }
189 }
190 }
191}
192
Hans Wennborg88497d62013-11-15 17:24:45 +0000193void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
194 const CGFunctionInfo &FnInfo) {
195 assert(!CurGD.getDecl() && "CurGD was already set!");
196 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000197 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000198
199 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000200 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000201 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000202 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000203 QualType ResultType =
Alp Toker314cc812014-01-25 16:55:45 +0000204 CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000205 FunctionArgList FunctionArgs;
206
Anders Carlssonbad991d2010-03-24 00:39:18 +0000207 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000208 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000209
210 // Add the rest of the parameters.
211 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000212 E = MD->param_end();
213 I != E; ++I)
214 FunctionArgs.push_back(*I);
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000215
Reid Kleckner89077a12013-12-17 19:46:40 +0000216 if (isa<CXXDestructorDecl>(MD))
217 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
218
Hans Wennborg88497d62013-11-15 17:24:45 +0000219 // Start defining the function.
John McCalla738c252011-03-09 04:27:21 +0000220 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Adrian Prantl42d71b92014-04-10 23:21:53 +0000221 MD->getLocation(), SourceLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000222
Hans Wennborg88497d62013-11-15 17:24:45 +0000223 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000224 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000225 CXXThisValue = CXXABIThisValue;
Hans Wennborg88497d62013-11-15 17:24:45 +0000226}
John McCall5d865c322010-08-31 07:33:07 +0000227
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000228void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg88497d62013-11-15 17:24:45 +0000229 const ThunkInfo *Thunk) {
230 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
231 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000232 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000233
Hans Wennborg88497d62013-11-15 17:24:45 +0000234 // Adjust the 'this' pointer if necessary
235 llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
236 *this, LoadCXXThis(), Thunk->This)
237 : LoadCXXThis();
238
Reid Klecknerab2090d2014-07-26 01:34:32 +0000239 if (CurFnInfo->usesInAlloca()) {
240 // We don't handle return adjusting thunks, because they require us to call
241 // the copy constructor. For now, fall through and pretend the return
242 // adjustment was empty so we don't crash.
243 if (Thunk && !Thunk->Return.isEmpty()) {
244 CGM.ErrorUnsupported(
245 MD, "non-trivial argument copy for return-adjusting thunk");
246 }
247 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
248 return;
249 }
250
Hans Wennborg88497d62013-11-15 17:24:45 +0000251 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000252 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000253 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000254 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000255
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000256 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000257 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000258
Hans Wennborg88497d62013-11-15 17:24:45 +0000259 // Add the rest of the arguments.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000260 for (const ParmVarDecl *PD : MD->params())
261 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000262
Hans Wennborg88497d62013-11-15 17:24:45 +0000263 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000264
John McCalla738c252011-03-09 04:27:21 +0000265#ifndef NDEBUG
John McCall8dda7b22012-07-07 06:41:13 +0000266 const CGFunctionInfo &CallFnInfo =
267 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCalla729c622012-02-17 03:33:10 +0000268 RequiredArgs::forPrototypePlus(FPT, 1));
Hans Wennborg88497d62013-11-15 17:24:45 +0000269 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
270 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
271 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000272 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
273 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000274 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
275 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
276 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000277 assert(similar(CallFnInfo.arg_begin()[i].info,
278 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000279 CurFnInfo->arg_begin()[i].info,
280 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000281#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000282
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000283 // Determine whether we have a return value slot to use.
Hans Wennborg88497d62013-11-15 17:24:45 +0000284 QualType ResultType =
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000285 CGM.getCXXABI().HasThisReturn(CurGD) ? ThisType : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000286 ReturnValueSlot Slot;
287 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000288 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000289 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000290 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
291
Anders Carlssonbad991d2010-03-24 00:39:18 +0000292 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000293 llvm::Instruction *CallOrInvoke;
294 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
295
Hans Wennborg88497d62013-11-15 17:24:45 +0000296 // Consider return adjustment if we have ThunkInfo.
297 if (Thunk && !Thunk->Return.isEmpty())
298 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000299
Hans Wennborg88497d62013-11-15 17:24:45 +0000300 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000301 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000302 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000303
John McCallff755cd2012-07-31 00:33:55 +0000304 // Disable the final ARC autorelease.
305 AutoreleaseResult = false;
306
Anders Carlssonbad991d2010-03-24 00:39:18 +0000307 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000308}
309
Reid Klecknerab2090d2014-07-26 01:34:32 +0000310void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
311 llvm::Value *AdjustedThisPtr,
312 llvm::Value *Callee) {
313 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
314 // to translate AST arguments into LLVM IR arguments. For thunks, we know
315 // that the caller prototype more or less matches the callee prototype with
316 // the exception of 'this'.
317 SmallVector<llvm::Value *, 8> Args;
318 for (llvm::Argument &A : CurFn->args())
319 Args.push_back(&A);
320
321 // Set the adjusted 'this' pointer.
322 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
323 if (ThisAI.isDirect()) {
324 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
325 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
326 llvm::Type *ThisType = Args[ThisArgNo]->getType();
327 if (ThisType != AdjustedThisPtr->getType())
328 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
329 Args[ThisArgNo] = AdjustedThisPtr;
330 } else {
331 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
332 llvm::Value *ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
333 llvm::Type *ThisType =
334 cast<llvm::PointerType>(ThisAddr->getType())->getElementType();
335 if (ThisType != AdjustedThisPtr->getType())
336 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
337 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
338 }
339
340 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
341 // don't actually want to run them.
342 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
343 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
344
345 // Apply the standard set of call attributes.
346 unsigned CallingConv;
347 CodeGen::AttributeListType AttributeList;
348 CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
349 /*AttrOnCallSite=*/true);
350 llvm::AttributeSet Attrs =
351 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
352 Call->setAttributes(Attrs);
353 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
354
355 if (Call->getType()->isVoidTy())
356 Builder.CreateRetVoid();
357 else
358 Builder.CreateRet(Call);
359
360 // Finish the function to maintain CodeGenFunction invariants.
361 // FIXME: Don't emit unreachable code.
362 EmitBlock(createBasicBlock());
363 FinishFunction();
364}
365
Hans Wennborg88497d62013-11-15 17:24:45 +0000366void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
367 const CGFunctionInfo &FnInfo,
368 GlobalDecl GD, const ThunkInfo &Thunk) {
369 StartThunk(Fn, GD, FnInfo);
370
371 // Get our callee.
372 llvm::Type *Ty =
373 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
374 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
375
376 // Make the call and return the result.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000377 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000378
Anders Carlssonbad991d2010-03-24 00:39:18 +0000379 // Set the right linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000380 CGM.setFunctionLinkage(GD, Fn);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000381
382 // Set the right visibility.
Hans Wennborg88497d62013-11-15 17:24:45 +0000383 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCallc8bd9c22010-08-04 23:46:35 +0000384 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000385}
386
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000387void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
388 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000389 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000390
391 // FIXME: re-use FnInfo in this computation.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000392 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
393 llvm::GlobalValue *Entry;
394
Anders Carlsson55e89f82010-03-23 18:18:41 +0000395 // Strip off a bitcast if we got one back.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000396 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000397 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000398 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
399 } else {
400 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000401 }
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000402
Anders Carlsson55e89f82010-03-23 18:18:41 +0000403 // There's already a declaration with the same name, check if it has the same
404 // type or if we need to replace it.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000405 if (Entry->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000406 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000407 llvm::GlobalValue *OldThunkFn = Entry;
408
Anders Carlsson55e89f82010-03-23 18:18:41 +0000409 // If the types mismatch then we have to rewrite the definition.
410 assert(OldThunkFn->isDeclaration() &&
411 "Shouldn't replace non-declaration");
412
413 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000414 OldThunkFn->setName(StringRef());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000415 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson55e89f82010-03-23 18:18:41 +0000416
417 // If needed, replace the old thunk with a bitcast.
418 if (!OldThunkFn->use_empty()) {
419 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000420 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000421 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
422 }
423
424 // Remove the old thunk.
425 OldThunkFn->eraseFromParent();
426 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000427
Anders Carlssonbad991d2010-03-24 00:39:18 +0000428 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000429 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
430 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000431
432 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000433 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000434 // There is already a thunk emitted for this function, do nothing.
435 return;
436 }
437
Anders Carlssone866d442011-02-06 20:09:44 +0000438 // Change the linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000439 CGM.setFunctionLinkage(GD, ThunkFn);
Anders Carlssone866d442011-02-06 20:09:44 +0000440 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000441 }
442
Rafael Espindola86792432012-09-21 20:39:32 +0000443 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
444
Eli Friedman49a94b12011-05-06 17:27:27 +0000445 if (ThunkFn->isVarArg()) {
446 // Varargs thunks are special; we can't just generate a call because
447 // we can't copy the varargs. Our implementation is rather
448 // expensive/sucky at the moment, so don't generate the thunk unless
449 // we have to.
450 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Benjamin Kramer065c61b2013-12-07 16:12:52 +0000451 if (!UseAvailableExternallyLinkage) {
Eli Friedman49a94b12011-05-06 17:27:27 +0000452 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Hans Wennborgc94391d2014-06-06 20:04:01 +0000453 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
454 !Thunk.Return.isEmpty());
Benjamin Kramer065c61b2013-12-07 16:12:52 +0000455 }
Eli Friedman49a94b12011-05-06 17:27:27 +0000456 } else {
457 // Normal thunk body generation.
458 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
Hans Wennborgc94391d2014-06-06 20:04:01 +0000459 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
460 !Thunk.Return.isEmpty());
Eli Friedman49a94b12011-05-06 17:27:27 +0000461 }
Anders Carlsson8b021832011-02-06 18:31:40 +0000462}
463
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000464void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
465 const ThunkInfo &Thunk) {
466 // If the ABI has key functions, only the TU with the key function should emit
467 // the thunk. However, we can allow inlining of thunks if we emit them with
468 // available_externally linkage together with vtables when optimizations are
469 // enabled.
470 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
471 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000472 return;
473
474 // We can't emit thunks for member functions with incomplete types.
475 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000476 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000477 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000478 return;
479
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000480 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000481}
482
Anders Carlsson917229c2010-03-23 04:59:02 +0000483void CodeGenVTables::EmitThunks(GlobalDecl GD)
484{
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000485 const CXXMethodDecl *MD =
486 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
487
488 // We don't need to generate thunks for the base destructor.
489 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
490 return;
491
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000492 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
493 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000494
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000495 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000496 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000497
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000498 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000499 emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000500}
501
David Majnemerd905da42014-07-01 20:30:31 +0000502llvm::Constant *CodeGenVTables::CreateVTableInitializer(
503 const CXXRecordDecl *RD, const VTableComponent *Components,
504 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
505 unsigned NumVTableThunks, llvm::Constant *RTTI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlssona4147142010-03-25 15:26:28 +0000507
Chris Lattnerece04092012-02-07 00:39:47 +0000508 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlssona4147142010-03-25 15:26:28 +0000509
Chris Lattner2192fe52011-07-18 04:24:23 +0000510 llvm::Type *PtrDiffTy =
Anders Carlssona5736bd2010-03-25 16:49:53 +0000511 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
512
Anders Carlssona5736bd2010-03-25 16:49:53 +0000513 unsigned NextVTableThunkIndex = 0;
Craig Topper8a13c412014-05-21 05:09:00 +0000514
515 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000516
Anders Carlssona4147142010-03-25 15:26:28 +0000517 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000518 VTableComponent Component = Components[I];
Anders Carlssona5736bd2010-03-25 16:49:53 +0000519
Craig Topper8a13c412014-05-21 05:09:00 +0000520 llvm::Constant *Init = nullptr;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000521
522 switch (Component.getKind()) {
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000523 case VTableComponent::CK_VCallOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000524 Init = llvm::ConstantInt::get(PtrDiffTy,
525 Component.getVCallOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000526 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
527 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000528 case VTableComponent::CK_VBaseOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000529 Init = llvm::ConstantInt::get(PtrDiffTy,
530 Component.getVBaseOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000531 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
532 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000533 case VTableComponent::CK_OffsetToTop:
Ken Dyck872d74a2011-04-02 01:14:48 +0000534 Init = llvm::ConstantInt::get(PtrDiffTy,
535 Component.getOffsetToTop().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000536 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
537 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000538 case VTableComponent::CK_RTTI:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000539 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
540 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000541 case VTableComponent::CK_FunctionPointer:
542 case VTableComponent::CK_CompleteDtorPointer:
543 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlssona5736bd2010-03-25 16:49:53 +0000544 GlobalDecl GD;
545
546 // Get the right global decl.
547 switch (Component.getKind()) {
548 default:
549 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000550 case VTableComponent::CK_FunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000551 GD = Component.getFunctionDecl();
552 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000553 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000554 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
555 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000556 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000557 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
558 break;
559 }
560
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000561 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
562 // We have a pure virtual member function.
Joao Matos718a8832012-07-17 19:17:58 +0000563 if (!PureVirtualFn) {
Eli Friedman48a32912012-09-14 01:19:01 +0000564 llvm::FunctionType *Ty =
565 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
566 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
567 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
568 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matos718a8832012-07-17 19:17:58 +0000569 CGM.Int8PtrTy);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000570 }
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000571 Init = PureVirtualFn;
David Blaikieeb7d5982012-10-16 22:56:05 +0000572 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
573 if (!DeletedVirtualFn) {
574 llvm::FunctionType *Ty =
575 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
576 StringRef DeletedCallName =
577 CGM.getCXXABI().GetDeletedVirtualCallName();
578 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
579 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
580 CGM.Int8PtrTy);
581 }
582 Init = DeletedVirtualFn;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000583 } else {
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000584 // Check if we should use a thunk.
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000585 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000586 VTableThunks[NextVTableThunkIndex].first == I) {
587 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000588
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000589 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramere6b4a162012-03-20 20:18:13 +0000590 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson8b021832011-02-06 18:31:40 +0000591
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000592 NextVTableThunkIndex++;
593 } else {
Chris Lattner2192fe52011-07-18 04:24:23 +0000594 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000595
Anders Carlsson3c239482011-02-05 04:35:53 +0000596 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000597 }
598
599 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000600 }
Anders Carlssona5736bd2010-03-25 16:49:53 +0000601 break;
602 }
603
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000604 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000605 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
606 break;
607 };
Anders Carlssona4147142010-03-25 15:26:28 +0000608
609 Inits.push_back(Init);
610 }
611
612 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad83be3612011-06-22 09:24:39 +0000613 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlssona4147142010-03-25 15:26:28 +0000614}
615
Anders Carlsson0534b022010-03-25 00:35:49 +0000616llvm::GlobalVariable *
617CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlssona208b392010-03-26 03:56:54 +0000618 const BaseSubobject &Base,
619 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000620 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000621 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000622 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
623 DI->completeClassData(Base.getBase());
624
Ahmed Charlesb8984322014-03-07 20:03:18 +0000625 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000626 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000627 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000628
Anders Carlssona5736bd2010-03-25 16:49:53 +0000629 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000630 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000631
632 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000633 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000634 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000635 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
636 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
637 Base.getBase(), Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +0000638 Out.flush();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000639 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000640
Anders Carlssona4147142010-03-25 15:26:28 +0000641 llvm::ArrayType *ArrayType =
Chris Lattnerece04092012-02-07 00:39:47 +0000642 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlssona4147142010-03-25 15:26:28 +0000643
Richard Smith65fd2a42013-02-16 00:51:21 +0000644 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
645 // guarantee that they actually will be available externally. Instead, when
646 // emitting an available_externally VTT, we provide references to an internal
647 // linkage construction vtable. The ABI only requires complete-object vtables
648 // to be the same for all instances of a type, not construction vtables.
649 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
650 Linkage = llvm::GlobalVariable::InternalLinkage;
651
Anders Carlssona4147142010-03-25 15:26:28 +0000652 // Create the variable that will hold the construction vtable.
653 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000654 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
John McCall8f80a612014-02-08 00:41:16 +0000655 CGM.setGlobalVisibility(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000656
657 // V-tables are always unnamed_addr.
658 VTable->setUnnamedAddr(true);
Anders Carlssona4147142010-03-25 15:26:28 +0000659
David Majnemerd905da42014-07-01 20:30:31 +0000660 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
661 CGM.getContext().getTagDeclType(Base.getBase()));
662
Anders Carlssona4147142010-03-25 15:26:28 +0000663 // Create and set the initializer.
David Majnemerd905da42014-07-01 20:30:31 +0000664 llvm::Constant *Init = CreateVTableInitializer(
665 Base.getBase(), VTLayout->vtable_component_begin(),
666 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
667 VTLayout->getNumVTableThunks(), RTTI);
Anders Carlssona4147142010-03-25 15:26:28 +0000668 VTable->setInitializer(Init);
669
Anders Carlsson0534b022010-03-25 00:35:49 +0000670 return VTable;
671}
672
John McCall6bd2a892013-01-25 22:31:03 +0000673/// Compute the required linkage of the v-table for the given class.
674///
675/// Note that we only call this at the end of the translation unit.
676llvm::GlobalVariable::LinkageTypes
677CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000678 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000679 return llvm::GlobalVariable::InternalLinkage;
680
681 // We're at the end of the translation unit, so the current key
682 // function is fully correct.
683 if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
684 // If this class has a key function, use that to determine the
685 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000686 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000687 if (keyFunction->hasBody(def))
688 keyFunction = cast<CXXMethodDecl>(def);
689
690 switch (keyFunction->getTemplateSpecializationKind()) {
691 case TSK_Undeclared:
692 case TSK_ExplicitSpecialization:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000693 assert(def && "Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000694 if (keyFunction->isInlined())
695 return !Context.getLangOpts().AppleKext ?
696 llvm::GlobalVariable::LinkOnceODRLinkage :
697 llvm::Function::InternalLinkage;
698
699 return llvm::GlobalVariable::ExternalLinkage;
700
701 case TSK_ImplicitInstantiation:
702 return !Context.getLangOpts().AppleKext ?
703 llvm::GlobalVariable::LinkOnceODRLinkage :
704 llvm::Function::InternalLinkage;
705
706 case TSK_ExplicitInstantiationDefinition:
707 return !Context.getLangOpts().AppleKext ?
708 llvm::GlobalVariable::WeakODRLinkage :
709 llvm::Function::InternalLinkage;
710
711 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000712 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000713 }
714 }
715
716 // -fapple-kext mode does not support weak linkage, so we must use
717 // internal linkage.
718 if (Context.getLangOpts().AppleKext)
719 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000720
721 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
722 llvm::GlobalValue::LinkOnceODRLinkage;
723 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
724 llvm::GlobalValue::WeakODRLinkage;
725 if (RD->hasAttr<DLLExportAttr>()) {
726 // Cannot discard exported vtables.
727 DiscardableODRLinkage = NonDiscardableODRLinkage;
728 } else if (RD->hasAttr<DLLImportAttr>()) {
729 // Imported vtables are available externally.
730 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
731 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
732 }
733
John McCall6bd2a892013-01-25 22:31:03 +0000734 switch (RD->getTemplateSpecializationKind()) {
735 case TSK_Undeclared:
736 case TSK_ExplicitSpecialization:
737 case TSK_ImplicitInstantiation:
Hans Wennborg853ae942014-05-30 16:59:42 +0000738 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000739
740 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000741 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000742
743 case TSK_ExplicitInstantiationDefinition:
Hans Wennborg853ae942014-05-30 16:59:42 +0000744 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000745 }
746
747 llvm_unreachable("Invalid TemplateSpecializationKind!");
748}
749
750/// This is a callback from Sema to tell us that it believes that a
751/// particular v-table is required to be emitted in this translation
752/// unit.
753///
754/// The reason we don't simply trust this callback is because Sema
755/// will happily report that something is used even when it's used
756/// only in code that we don't actually have to emit.
757///
758/// \param isRequired - if true, the v-table is mandatory, e.g.
759/// because the translation unit defines the key function
760void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
761 if (!isRequired) return;
762
763 VTables.GenerateClassData(theClass);
764}
765
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000766void
John McCall6bd2a892013-01-25 22:31:03 +0000767CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000768 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
769 DI->completeClassData(RD);
770
Reid Kleckner7810af02013-06-19 15:20:38 +0000771 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000772 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000773
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000774 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000775}
John McCall6bd2a892013-01-25 22:31:03 +0000776
777/// At this point in the translation unit, does it appear that can we
778/// rely on the vtable being defined elsewhere in the program?
779///
780/// The response is really only definitive when called at the end of
781/// the translation unit.
782///
783/// The only semantic restriction here is that the object file should
784/// not contain a v-table definition when that v-table is defined
785/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
786/// v-tables when unnecessary.
787bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000788 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000789
790 // If we have an explicit instantiation declaration (and not a
791 // definition), the v-table is defined elsewhere.
792 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
793 if (TSK == TSK_ExplicitInstantiationDeclaration)
794 return true;
795
796 // Otherwise, if the class is an instantiated template, the
797 // v-table must be defined here.
798 if (TSK == TSK_ImplicitInstantiation ||
799 TSK == TSK_ExplicitInstantiationDefinition)
800 return false;
801
802 // Otherwise, if the class doesn't have a key function (possibly
803 // anymore), the v-table must be defined here.
804 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
805 if (!keyFunction)
806 return false;
807
808 // Otherwise, if we don't have a definition of the key function, the
809 // v-table must be defined somewhere else.
810 return !keyFunction->hasBody();
811}
812
813/// Given that we're currently at the end of the translation unit, and
814/// we've emitted a reference to the v-table for this class, should
815/// we define that v-table?
816static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
817 const CXXRecordDecl *RD) {
John McCall6bd2a892013-01-25 22:31:03 +0000818 return !CGM.getVTables().isVTableExternal(RD);
819}
820
821/// Given that at some point we emitted a reference to one or more
822/// v-tables, and that we are now at the end of the translation unit,
823/// decide whether we should emit them.
824void CodeGenModule::EmitDeferredVTables() {
825#ifndef NDEBUG
826 // Remember the size of DeferredVTables, because we're going to assume
827 // that this entire operation doesn't modify it.
828 size_t savedSize = DeferredVTables.size();
829#endif
830
831 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
832 for (const_iterator i = DeferredVTables.begin(),
833 e = DeferredVTables.end(); i != e; ++i) {
834 const CXXRecordDecl *RD = *i;
835 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
836 VTables.GenerateClassData(RD);
837 }
838
839 assert(savedSize == DeferredVTables.size() &&
840 "deferred extra v-tables during v-table emission?");
841 DeferredVTables.clear();
842}