clang 23.0.0git
CGVTables.cpp
Go to the documentation of this file.
1//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of virtual tables.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/Attr.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/Transforms/Utils/Cloning.h"
25#include <algorithm>
26#include <cstdio>
27#include <utility>
28
29using namespace clang;
30using namespace CodeGen;
31
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
34
35llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
36 GlobalDecl GD) {
37 return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
38 /*DontDefer=*/true, /*IsThunk=*/true);
39}
40
41llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
42 llvm::GlobalVariable *VTable =
43 CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
44 return VTable;
45}
46
47static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
48 llvm::Function *ThunkFn, bool ForVTable,
49 GlobalDecl GD) {
50 CGM.setFunctionLinkage(GD, ThunkFn);
51 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
52 !Thunk.Return.isEmpty());
53
54 // Set the right visibility.
55 CGM.setGVProperties(ThunkFn, GD);
56
57 if (!CGM.getCXXABI().exportThunk()) {
58 ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
59 ThunkFn->setDSOLocal(true);
60 }
61
62 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
63 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
64}
65
66#ifndef NDEBUG
67static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
68 const ABIArgInfo &infoR, CanQualType typeR) {
69 return (infoL.getKind() == infoR.getKind() &&
70 (typeL == typeR ||
71 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
72 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
73}
74#endif
75
77 QualType ResultType, RValue RV,
78 const ThunkInfo &Thunk) {
79 // Emit the return adjustment.
80 bool NullCheckValue = !ResultType->isReferenceType();
81
82 llvm::BasicBlock *AdjustNull = nullptr;
83 llvm::BasicBlock *AdjustNotNull = nullptr;
84 llvm::BasicBlock *AdjustEnd = nullptr;
85
86 llvm::Value *ReturnValue = RV.getScalarVal();
87
88 if (NullCheckValue) {
89 AdjustNull = CGF.createBasicBlock("adjust.null");
90 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
91 AdjustEnd = CGF.createBasicBlock("adjust.end");
92
93 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
94 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
95 CGF.EmitBlock(AdjustNotNull);
96 }
97
98 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
99 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
100 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(
101 CGF,
102 Address(ReturnValue, CGF.ConvertTypeForMem(ResultType->getPointeeType()),
103 ClassAlign),
104 ClassDecl, Thunk.Return);
105
106 if (NullCheckValue) {
107 CGF.Builder.CreateBr(AdjustEnd);
108 CGF.EmitBlock(AdjustNull);
109 CGF.Builder.CreateBr(AdjustEnd);
110 CGF.EmitBlock(AdjustEnd);
111
112 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
113 PHI->addIncoming(ReturnValue, AdjustNotNull);
114 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
115 AdjustNull);
116 ReturnValue = PHI;
117 }
118
119 return RValue::get(ReturnValue);
120}
121
122/// This function clones a function's DISubprogram node and enters it into
123/// a value map with the intent that the map can be utilized by the cloner
124/// to short-circuit Metadata node mapping.
125/// Furthermore, the function resolves any DILocalVariable nodes referenced
126/// by dbg.value intrinsics so they can be properly mapped during cloning.
127static void resolveTopLevelMetadata(llvm::Function *Fn,
128 llvm::ValueToValueMapTy &VMap) {
129 // Clone the DISubprogram node and put it into the Value map.
130 auto *DIS = Fn->getSubprogram();
131 if (!DIS)
132 return;
133 auto *NewDIS = llvm::MDNode::replaceWithDistinct(DIS->clone());
134 // As DISubprogram remapping is avoided, clear retained nodes list of
135 // cloned DISubprogram from retained nodes local to original DISubprogram.
136 // FIXME: Thunk function signature is produced wrong in DWARF, as retained
137 // nodes are not remapped.
138 NewDIS->replaceRetainedNodes(llvm::MDTuple::get(Fn->getContext(), {}));
139 VMap.MD()[DIS].reset(NewDIS);
140
141 // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
142 // they are referencing.
143 //
144 // DIDerivedTypes referring to incomplete Clang types, or
145 // LLVM enumeration types representing complete enums with no definition
146 // may be still unresolved. As they can't be cloned, keep references
147 // to the types from the base subprogram.
148 // FIXME: As a result, variables of cloned subprogram may refer to local types
149 // from base subprogram. In such case, type locality information is damaged.
150 // Find a way to enable cloning of all local types.
151 auto PrepareVariableMapping = [&VMap](llvm::DILocalVariable *DILocal) {
152 if (DILocal->isResolved())
153 return;
154
155 if (llvm::DIType *Ty = DILocal->getType(); Ty && !Ty->isResolved())
156 VMap.MD()[Ty].reset(Ty);
157
158 DILocal->resolve();
159 };
160
161 for (auto &BB : *Fn) {
162 for (auto &I : BB) {
163 for (llvm::DbgVariableRecord &DVR :
164 llvm::filterDbgVars(I.getDbgRecordRange()))
165 PrepareVariableMapping(DVR.getVariable());
166
167 if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I))
168 PrepareVariableMapping(DII->getVariable());
169 }
170 }
171}
172
173// This function does roughly the same thing as GenerateThunk, but in a
174// very different way, so that va_start and va_end work correctly.
175// FIXME: This function assumes "this" is the first non-sret LLVM argument of
176// a function, and that there is an alloca built in the entry block
177// for all accesses to "this".
178// FIXME: This function assumes there is only one "ret" statement per function.
179// FIXME: Cloning isn't correct in the presence of indirect goto!
180// FIXME: This implementation of thunks bloats codesize by duplicating the
181// function definition. There are alternatives:
182// 1. Add some sort of stub support to LLVM for cases where we can
183// do a this adjustment, then a sibcall.
184// 2. We could transform the definition to take a va_list instead of an
185// actual variable argument list, then have the thunks (including a
186// no-op thunk for the regular definition) call va_start/va_end.
187// There's a bit of per-call overhead for this solution, but it's
188// better for codesize if the definition is long.
189llvm::Function *
191 const CGFunctionInfo &FnInfo,
192 GlobalDecl GD, const ThunkInfo &Thunk) {
193 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
194 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
195 QualType ResultType = FPT->getReturnType();
196
197 // Get the original function
198 assert(FnInfo.isVariadic());
199 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
200 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
201 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
202
203 // Cloning can't work if we don't have a definition. The Microsoft ABI may
204 // require thunks when a definition is not available. Emit an error in these
205 // cases.
206 if (!MD->isDefined()) {
207 CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
208 return Fn;
209 }
210 assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
211
212 // Clone to thunk.
213 llvm::ValueToValueMapTy VMap;
214
215 // We are cloning a function while some Metadata nodes are still unresolved.
216 // Ensure that the value mapper does not encounter any of them.
217 resolveTopLevelMetadata(BaseFn, VMap);
218 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
219 Fn->replaceAllUsesWith(NewFn);
220 NewFn->takeName(Fn);
221 Fn->eraseFromParent();
222 Fn = NewFn;
223
224 // "Initialize" CGF (minimally).
225 CurFn = Fn;
226
227 // Get the "this" value
228 llvm::Function::arg_iterator AI = Fn->arg_begin();
229 if (CGM.ReturnTypeUsesSRet(FnInfo))
230 ++AI;
231
232 // Find the first store of "this", which will be to the alloca associated
233 // with "this".
236 CGM.getClassPointerAlignment(MD->getParent()));
237 llvm::BasicBlock *EntryBB = &Fn->front();
238 llvm::BasicBlock::iterator ThisStore =
239 llvm::find_if(*EntryBB, [&](llvm::Instruction &I) {
240 return isa<llvm::StoreInst>(I) && I.getOperand(0) == &*AI;
241 });
242 assert(ThisStore != EntryBB->end() &&
243 "Store of this should be in entry block?");
244 // Adjust "this", if necessary.
245 Builder.SetInsertPoint(&*ThisStore);
246
247 const CXXRecordDecl *ThisValueClass = Thunk.ThisType->getPointeeCXXRecordDecl();
248 llvm::Value *AdjustedThisPtr = CGM.getCXXABI().performThisAdjustment(
249 *this, ThisPtr, ThisValueClass, Thunk);
250 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
251 ThisStore->getOperand(0)->getType());
252 ThisStore->setOperand(0, AdjustedThisPtr);
253
254 if (!Thunk.Return.isEmpty()) {
255 // Fix up the returned value, if necessary.
256 for (llvm::BasicBlock &BB : *Fn) {
257 llvm::Instruction *T = BB.getTerminator();
258 if (isa<llvm::ReturnInst>(T)) {
259 RValue RV = RValue::get(T->getOperand(0));
260 T->eraseFromParent();
261 Builder.SetInsertPoint(&BB);
262 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
263 Builder.CreateRet(RV.getScalarVal());
264 break;
265 }
266 }
267 }
268
269 return Fn;
270}
271
272void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
273 const CGFunctionInfo &FnInfo,
274 bool IsUnprototyped) {
275 assert(!CurGD.getDecl() && "CurGD was already set!");
276 CurGD = GD;
277 CurFuncIsThunk = true;
278
279 // Build FunctionArgs.
280 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
281 QualType ThisType = MD->getThisType();
282 QualType ResultType;
283 if (IsUnprototyped)
284 ResultType = CGM.getContext().VoidTy;
285 else if (CGM.getCXXABI().HasThisReturn(GD))
286 ResultType = ThisType;
287 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
288 ResultType = CGM.getContext().VoidPtrTy;
289 else
290 ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
291 FunctionArgList FunctionArgs;
292
293 // Create the implicit 'this' parameter declaration.
294 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
295
296 // Add the rest of the parameters, if we have a prototype to work with.
297 if (!IsUnprototyped) {
298 FunctionArgs.append(MD->param_begin(), MD->param_end());
299
301 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
302 FunctionArgs);
303 }
304
305 // Start defining the function.
306 auto NL = ApplyDebugLocation::CreateEmpty(*this);
307 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
308 MD->getLocation());
309 // Create a scope with an artificial location for the body of this function.
311
312 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
313 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
314 CXXThisValue = CXXABIThisValue;
315 CurCodeDecl = MD;
316 CurFuncDecl = MD;
317}
318
320 // Clear these to restore the invariants expected by
321 // StartFunction/FinishFunction.
322 CurCodeDecl = nullptr;
323 CurFuncDecl = nullptr;
324
326}
327
328void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
329 const ThunkInfo *Thunk,
330 bool IsUnprototyped) {
331 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
332 "Please use a new CGF for this thunk");
333 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
334
335 // Adjust the 'this' pointer if necessary
336 const CXXRecordDecl *ThisValueClass =
338 if (Thunk)
339 ThisValueClass = Thunk->ThisType->getPointeeCXXRecordDecl();
340
341 llvm::Value *AdjustedThisPtr =
342 Thunk ? CGM.getCXXABI().performThisAdjustment(*this, LoadCXXThisAddress(),
343 ThisValueClass, *Thunk)
344 : LoadCXXThis();
345
346 // If perfect forwarding is required a variadic method, a method using
347 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
348 // thunk requires a return adjustment, since that is impossible with musttail.
349 if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
350 if (Thunk && !Thunk->Return.isEmpty()) {
351 if (IsUnprototyped)
352 CGM.ErrorUnsupported(
353 MD, "return-adjusting thunk with incomplete parameter type");
354 else if (CurFnInfo->isVariadic())
355 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
356 "thunks for variadic functions");
357 else
358 CGM.ErrorUnsupported(
359 MD, "non-trivial argument copy for return-adjusting thunk");
360 }
361 EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
362 return;
363 }
364
365 // Start building CallArgs.
366 CallArgList CallArgs;
367 QualType ThisType = MD->getThisType();
368 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
369
371 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
372
373#ifndef NDEBUG
374 unsigned PrefixArgs = CallArgs.size() - 1;
375#endif
376 // Add the rest of the arguments.
377 for (const ParmVarDecl *PD : MD->parameters())
378 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
379
380 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
381
382#ifndef NDEBUG
383 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
384 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
385 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
386 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
387 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
388 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
389 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
390 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
391 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
392 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
393 assert(similar(CallFnInfo.arg_begin()[i].info,
394 CallFnInfo.arg_begin()[i].type,
395 CurFnInfo->arg_begin()[i].info,
396 CurFnInfo->arg_begin()[i].type));
397#endif
398
399 // Determine whether we have a return value slot to use.
400 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
401 ? ThisType
402 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
403 ? CGM.getContext().VoidPtrTy
404 : FPT->getReturnType();
405 ReturnValueSlot Slot;
406 if (!ResultType->isVoidType() &&
407 (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
408 hasAggregateEvaluationKind(ResultType)))
410 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
411
412 // Now emit our call.
413 llvm::CallBase *CallOrInvoke;
414 RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
415 CallArgs, &CallOrInvoke);
416
417 // Consider return adjustment if we have ThunkInfo.
418 if (Thunk && !Thunk->Return.isEmpty())
419 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
420 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
421 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
422
423 // Emit return.
424 if (!ResultType->isVoidType() && Slot.isNull())
425 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
426
427 // Disable the final ARC autorelease.
428 AutoreleaseResult = false;
429
430 FinishThunk();
431}
432
434 llvm::Value *AdjustedThisPtr,
435 llvm::FunctionCallee Callee) {
436 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
437 // to translate AST arguments into LLVM IR arguments. For thunks, we know
438 // that the caller prototype more or less matches the callee prototype with
439 // the exception of 'this'.
440 SmallVector<llvm::Value *, 8> Args(llvm::make_pointer_range(CurFn->args()));
441
442 // Set the adjusted 'this' pointer.
443 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
444 if (ThisAI.isDirect()) {
445 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
446 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
447 llvm::Type *ThisType = Args[ThisArgNo]->getType();
448 if (ThisType != AdjustedThisPtr->getType())
449 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
450 Args[ThisArgNo] = AdjustedThisPtr;
451 } else {
452 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
453 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
454 llvm::Type *ThisType = ThisAddr.getElementType();
455 if (ThisType != AdjustedThisPtr->getType())
456 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
457 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
458 }
459
460 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
461 // don't actually want to run them.
462 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
463 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
464
465 // Apply the standard set of call attributes.
466 unsigned CallingConv;
467 llvm::AttributeList Attrs;
468 CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
469 Attrs, CallingConv, /*AttrOnCallSite=*/true,
470 /*IsThunk=*/false);
471 Call->setAttributes(Attrs);
472 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
473
474 if (Call->getType()->isVoidTy())
475 Builder.CreateRetVoid();
476 else
477 Builder.CreateRet(Call);
478
479 // Finish the function to maintain CodeGenFunction invariants.
480 // FIXME: Don't emit unreachable code.
482
483 FinishThunk();
484}
485
486void CodeGenFunction::generateThunk(llvm::Function *Fn,
487 const CGFunctionInfo &FnInfo, GlobalDecl GD,
488 const ThunkInfo &Thunk,
489 bool IsUnprototyped) {
490 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
491 // Create a scope with an artificial location for the body of this function.
493
494 // Get our callee. Use a placeholder type if this method is unprototyped so
495 // that CodeGenModule doesn't try to set attributes.
496 llvm::Type *Ty;
497 if (IsUnprototyped)
498 Ty = llvm::StructType::get(getLLVMContext());
499 else
500 Ty = CGM.getTypes().GetFunctionType(FnInfo);
501
502 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
503
504 // Make the call and return the result.
505 EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
506 &Thunk, IsUnprototyped);
507}
508
510 bool IsUnprototyped, bool ForVTable) {
511 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
512 // provide thunks for us.
513 if (CGM.getTarget().getCXXABI().isMicrosoft())
514 return true;
515
516 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
517 // definitions of the main method. Therefore, emitting thunks with the vtable
518 // is purely an optimization. Emit the thunk if optimizations are enabled and
519 // all of the parameter types are complete.
520 if (ForVTable)
521 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
522
523 // Always emit thunks along with the method definition.
524 return true;
525}
526
527llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
528 const ThunkInfo &TI,
529 bool ForVTable) {
530 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
531
532 // First, get a declaration. Compute the mangled name. Don't worry about
533 // getting the function prototype right, since we may only need this
534 // declaration to fill in a vtable slot.
535 SmallString<256> Name;
536 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
537 llvm::raw_svector_ostream Out(Name);
538
539 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
540 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI,
541 /* elideOverrideInfo */ false, Out);
542 } else
543 MCtx.mangleThunk(MD, TI, /* elideOverrideInfo */ false, Out);
544
545 if (CGM.getContext().useAbbreviatedThunkName(GD, Name.str())) {
546 Name = "";
547 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
548 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI,
549 /* elideOverrideInfo */ true, Out);
550 else
551 MCtx.mangleThunk(MD, TI, /* elideOverrideInfo */ true, Out);
552 }
553
554 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
555 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
556
557 // If we don't need to emit a definition, return this declaration as is.
558 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
559 MD->getType()->castAs<FunctionType>());
560 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
561 return Thunk;
562
563 // Arrange a function prototype appropriate for a function definition. In some
564 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
565 const CGFunctionInfo &FnInfo =
566 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
567 : CGM.getTypes().arrangeGlobalDeclaration(GD);
568 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
569
570 // If the type of the underlying GlobalValue is wrong, we'll have to replace
571 // it. It should be a declaration.
572 llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
573 if (ThunkFn->getFunctionType() != ThunkFnTy) {
574 llvm::GlobalValue *OldThunkFn = ThunkFn;
575
576 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
577
578 // Remove the name from the old thunk function and get a new thunk.
579 OldThunkFn->setName(StringRef());
580 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
581 Name.str(), &CGM.getModule());
582 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
583
584 if (!OldThunkFn->use_empty()) {
585 OldThunkFn->replaceAllUsesWith(ThunkFn);
586 }
587
588 // Remove the old thunk.
589 OldThunkFn->eraseFromParent();
590 }
591
592 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
593 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
594
595 if (!ThunkFn->isDeclaration()) {
596 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
597 // There is already a thunk emitted for this function, do nothing.
598 return ThunkFn;
599 }
600
601 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
602 return ThunkFn;
603 }
604
605 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
606 // that the return type is meaningless. These thunks can be used to call
607 // functions with differing return types, and the caller is required to cast
608 // the prototype appropriately to extract the correct value.
609 if (IsUnprototyped)
610 ThunkFn->addFnAttr("thunk");
611
612 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
613
614 // Thunks for variadic methods are special because in general variadic
615 // arguments cannot be perfectly forwarded. In the general case, clang
616 // implements such thunks by cloning the original function body. However, for
617 // thunks with no return adjustment on targets that support musttail, we can
618 // use musttail to perfectly forward the variadic arguments.
619 bool ShouldCloneVarArgs = false;
620 if (!IsUnprototyped && ThunkFn->isVarArg()) {
621 ShouldCloneVarArgs = true;
622 if (TI.Return.isEmpty()) {
623 switch (CGM.getTriple().getArch()) {
624 case llvm::Triple::x86_64:
625 case llvm::Triple::x86:
626 case llvm::Triple::aarch64:
627 ShouldCloneVarArgs = false;
628 break;
629 default:
630 break;
631 }
632 }
633 }
634
635 if (ShouldCloneVarArgs) {
636 if (UseAvailableExternallyLinkage)
637 return ThunkFn;
638 ThunkFn =
639 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
640 } else {
641 // Normal thunk body generation.
642 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
643 }
644
645 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
646 return ThunkFn;
647}
648
650 const CXXMethodDecl *MD =
651 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
652
653 // We don't need to generate thunks for the base destructor.
655 return;
656
657 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
658 VTContext->getThunkInfo(GD);
659
660 if (!ThunkInfoVector)
661 return;
662
663 for (const ThunkInfo& Thunk : *ThunkInfoVector)
664 maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
665}
666
667void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
668 llvm::Constant *component,
669 unsigned vtableAddressPoint,
670 bool vtableHasLocalLinkage,
671 bool isCompleteDtor) const {
672 // No need to get the offset of a nullptr.
673 if (component->isNullValue())
674 return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
675
676 auto *globalVal =
677 cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
678 llvm::Module &module = CGM.getModule();
679
680 // We don't want to copy the linkage of the vtable exactly because we still
681 // want the stub/proxy to be emitted for properly calculating the offset.
682 // Examples where there would be no symbol emitted are available_externally
683 // and private linkages.
684 //
685 // `internal` linkage results in STB_LOCAL Elf binding while still manifesting a
686 // local symbol.
687 //
688 // `linkonce_odr` linkage results in a STB_DEFAULT Elf binding but also allows for
689 // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
690 // target that supports this replacement.
691 auto stubLinkage = vtableHasLocalLinkage
692 ? llvm::GlobalValue::InternalLinkage
693 : llvm::GlobalValue::LinkOnceODRLinkage;
694
695 llvm::Constant *target;
696 if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
697 target = llvm::DSOLocalEquivalent::get(func);
698 } else {
699 llvm::SmallString<16> rttiProxyName(globalVal->getName());
700 rttiProxyName.append(".rtti_proxy");
701
702 // The RTTI component may not always be emitted in the same linkage unit as
703 // the vtable. As a general case, we can make a dso_local proxy to the RTTI
704 // that points to the actual RTTI struct somewhere. This will result in a
705 // GOTPCREL relocation when taking the relative offset to the proxy.
706 llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
707 if (!proxy) {
708 proxy = new llvm::GlobalVariable(module, globalVal->getType(),
709 /*isConstant=*/true, stubLinkage,
710 globalVal, rttiProxyName);
711 proxy->setDSOLocal(true);
712 proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
713 if (!proxy->hasLocalLinkage()) {
714 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
715 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
716 }
717 // Do not instrument the rtti proxies with hwasan to avoid a duplicate
718 // symbol error. Aliases generated by hwasan will retain the same namebut
719 // the addresses they are set to may have different tags from different
720 // compilation units. We don't run into this without hwasan because the
721 // proxies are in comdat groups, but those aren't propagated to the alias.
723 }
724 target = proxy;
725 }
726
727 builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
728 /*position=*/vtableAddressPoint);
729}
730
731static bool UseRelativeLayout(const CodeGenModule &CGM) {
732 return CGM.getTarget().getCXXABI().isItaniumFamily() &&
734}
735
737 return UseRelativeLayout(CGM);
738}
739
741 if (UseRelativeLayout(*this))
742 return Int32Ty;
743 return GlobalsInt8PtrTy;
744}
745
747 return CGM.getVTableComponentType();
748}
749
751 ConstantArrayBuilder &builder,
752 CharUnits offset) {
753 builder.add(llvm::ConstantExpr::getIntToPtr(
754 llvm::ConstantInt::getSigned(CGM.PtrDiffTy, offset.getQuantity()),
755 CGM.GlobalsInt8PtrTy));
756}
757
759 ConstantArrayBuilder &builder,
760 CharUnits offset) {
761 builder.add(llvm::ConstantInt::getSigned(CGM.Int32Ty, offset.getQuantity()));
762}
763
764void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
765 const VTableLayout &layout,
766 unsigned componentIndex,
767 llvm::Constant *rtti,
768 unsigned &nextVTableThunkIndex,
769 unsigned vtableAddressPoint,
770 bool vtableHasLocalLinkage) {
771 auto &component = layout.vtable_components()[componentIndex];
772
773 auto addOffsetConstant =
775
776 switch (component.getKind()) {
778 return addOffsetConstant(CGM, builder, component.getVCallOffset());
779
781 return addOffsetConstant(CGM, builder, component.getVBaseOffset());
782
784 return addOffsetConstant(CGM, builder, component.getOffsetToTop());
785
787 if (useRelativeLayout())
788 return addRelativeComponent(builder, rtti, vtableAddressPoint,
789 vtableHasLocalLinkage,
790 /*isCompleteDtor=*/false);
791 else
792 return builder.add(rtti);
793
797 GlobalDecl GD = component.getGlobalDecl(
798 CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
799 CGM.getContext().getLangOpts()));
800
801 const bool IsThunk =
802 nextVTableThunkIndex < layout.vtable_thunks().size() &&
803 layout.vtable_thunks()[nextVTableThunkIndex].first == componentIndex;
804
805 if (CGM.getLangOpts().CUDA) {
806 // Emit NULL for methods we can't codegen on this
807 // side. Otherwise we'd end up with vtable with unresolved
808 // references.
809 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
810 // OK on device side: functions w/ __device__ attribute
811 // OK on host side: anything except __device__-only functions.
812 bool CanEmitMethod =
813 CGM.getLangOpts().CUDAIsDevice
814 ? MD->hasAttr<CUDADeviceAttr>()
815 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
816 if (!CanEmitMethod) {
817 if (IsThunk)
818 nextVTableThunkIndex++;
819 return builder.add(
820 llvm::ConstantExpr::getNullValue(CGM.GlobalsInt8PtrTy));
821 }
822 // Method is acceptable, continue processing as usual.
823 }
824
825 auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
826 // FIXME(PR43094): When merging comdat groups, lld can select a local
827 // symbol as the signature symbol even though it cannot be accessed
828 // outside that symbol's TU. The relative vtables ABI would make
829 // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
830 // depending on link order, the comdat groups could resolve to the one
831 // with the local symbol. As a temporary solution, fill these components
832 // with zero. We shouldn't be calling these in the first place anyway.
833 if (useRelativeLayout())
834 return llvm::ConstantPointerNull::get(CGM.GlobalsInt8PtrTy);
835
836 // For NVPTX devices in OpenMP emit special functon as null pointers,
837 // otherwise linking ends up with unresolved references.
838 if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsTargetDevice &&
839 CGM.getTriple().isNVPTX())
840 return llvm::ConstantPointerNull::get(CGM.GlobalsInt8PtrTy);
841 llvm::FunctionType *fnTy =
842 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
843 llvm::Constant *fn = cast<llvm::Constant>(
844 CGM.CreateRuntimeFunction(fnTy, name).getCallee());
845 if (auto f = dyn_cast<llvm::Function>(fn))
846 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
847 return fn;
848 };
849
850 llvm::Constant *fnPtr;
851
852 // Pure virtual member functions.
853 if (cast<CXXMethodDecl>(GD.getDecl())->isPureVirtual()) {
854 if (!PureVirtualFn)
855 PureVirtualFn =
856 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
857 fnPtr = PureVirtualFn;
858
859 // Deleted virtual member functions.
860 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
861 if (!DeletedVirtualFn)
862 DeletedVirtualFn =
863 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
864 fnPtr = DeletedVirtualFn;
865
866 // Thunks.
867 } else if (IsThunk) {
868 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
869
870 nextVTableThunkIndex++;
871 fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
872 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {
873 assert(thunkInfo.Method && "Method not set");
874 GD = GD.getWithDecl(thunkInfo.Method);
875 }
876
877 // Otherwise we can use the method definition directly.
878 } else {
879 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
880 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
881 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
883 }
884
885 if (useRelativeLayout()) {
886 return addRelativeComponent(
887 builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
888 component.getKind() == VTableComponent::CK_CompleteDtorPointer);
889 } else {
890 // TODO: this icky and only exists due to functions being in the generic
891 // address space, rather than the global one, even though they are
892 // globals; fixing said issue might be intrusive, and will be done
893 // later.
894 unsigned FnAS = fnPtr->getType()->getPointerAddressSpace();
895 unsigned GVAS = CGM.GlobalsInt8PtrTy->getPointerAddressSpace();
896
897 if (FnAS != GVAS)
898 fnPtr =
899 llvm::ConstantExpr::getAddrSpaceCast(fnPtr, CGM.GlobalsInt8PtrTy);
900 if (const auto &Schema =
901 CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
902 return builder.addSignedPointer(fnPtr, Schema, GD, QualType());
903 return builder.add(fnPtr);
904 }
905 }
906
908 if (useRelativeLayout())
909 return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
910 else
911 return builder.addNullPointer(CGM.GlobalsInt8PtrTy);
912 }
913
914 llvm_unreachable("Unexpected vtable component kind");
915}
916
917llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
919 llvm::Type *componentType = getVTableComponentType();
920 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
921 tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
922
923 return llvm::StructType::get(CGM.getLLVMContext(), tys);
924}
925
927 const VTableLayout &layout,
928 llvm::Constant *rtti,
929 bool vtableHasLocalLinkage) {
930 llvm::Type *componentType = getVTableComponentType();
931
932 const auto &addressPoints = layout.getAddressPointIndices();
933 unsigned nextVTableThunkIndex = 0;
934 for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
935 vtableIndex != endIndex; ++vtableIndex) {
936 auto vtableElem = builder.beginArray(componentType);
937
938 size_t vtableStart = layout.getVTableOffset(vtableIndex);
939 size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
940 for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
941 ++componentIndex) {
942 addVTableComponent(vtableElem, layout, componentIndex, rtti,
943 nextVTableThunkIndex, addressPoints[vtableIndex],
944 vtableHasLocalLinkage);
945 }
946 vtableElem.finishAndAddTo(builder);
947 }
948}
949
951 const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
952 llvm::GlobalVariable::LinkageTypes Linkage,
953 VTableAddressPointsMapTy &AddressPoints) {
954 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
955 DI->completeClassData(Base.getBase());
956
957 std::unique_ptr<VTableLayout> VTLayout(
958 getItaniumVTableContext().createConstructionVTableLayout(
959 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
960
961 // Add the address points.
962 AddressPoints = VTLayout->getAddressPoints();
963
964 // Get the mangled construction vtable name.
965 SmallString<256> OutName;
966 llvm::raw_svector_ostream Out(OutName);
967 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
968 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
969 Base.getBase(), Out);
970 SmallString<256> Name(OutName);
971
972 bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
973 bool VTableAliasExists =
974 UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
975 if (VTableAliasExists) {
976 // We previously made the vtable hidden and changed its name.
977 Name.append(".local");
978 }
979
980 llvm::Type *VTType = getVTableType(*VTLayout);
981
982 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
983 // guarantee that they actually will be available externally. Instead, when
984 // emitting an available_externally VTT, we provide references to an internal
985 // linkage construction vtable. The ABI only requires complete-object vtables
986 // to be the same for all instances of a type, not construction vtables.
987 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
988 Linkage = llvm::GlobalVariable::InternalLinkage;
989
990 llvm::Align Align = CGM.getDataLayout().getABITypeAlign(VTType);
991
992 // Create the variable that will hold the construction vtable.
993 llvm::GlobalVariable *VTable =
994 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
995
996 // V-tables are always unnamed_addr.
997 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
998
999 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
1000 CGM.getContext().getCanonicalTagType(Base.getBase()));
1001
1002 // Create and set the initializer.
1003 ConstantInitBuilder builder(CGM);
1004 auto components = builder.beginStruct();
1005 createVTableInitializer(components, *VTLayout, RTTI,
1006 VTable->hasLocalLinkage());
1007 components.finishAndSetAsInitializer(VTable);
1008
1009 // Set properties only after the initializer has been set to ensure that the
1010 // GV is treated as definition and not declaration.
1011 assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
1012 CGM.setGVProperties(VTable, RD);
1013
1014 CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout);
1015
1016 if (UsingRelativeLayout) {
1017 RemoveHwasanMetadata(VTable);
1018 if (!VTable->isDSOLocal())
1019 GenerateRelativeVTableAlias(VTable, OutName);
1020 }
1021
1022 return VTable;
1023}
1024
1025// Ensure this vtable is not instrumented by hwasan. That is, a global alias is
1026// not generated for it. This is mainly used by the relative-vtables ABI where
1027// vtables instead contain 32-bit offsets between the vtable and function
1028// pointers. Hwasan is disabled for these vtables for now because the tag in a
1029// vtable pointer may fail the overflow check when resolving 32-bit PLT
1030// relocations. A future alternative for this would be finding which usages of
1031// the vtable can continue to use the untagged hwasan value without any loss of
1032// value in hwasan.
1033void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *GV) const {
1034 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
1035 llvm::GlobalValue::SanitizerMetadata Meta;
1036 if (GV->hasSanitizerMetadata())
1037 Meta = GV->getSanitizerMetadata();
1038 Meta.NoHWAddress = true;
1039 GV->setSanitizerMetadata(Meta);
1040 }
1041}
1042
1043// If the VTable is not dso_local, then we will not be able to indicate that
1044// the VTable does not need a relocation and move into rodata. A frequent
1045// time this can occur is for classes that should be made public from a DSO
1046// (like in libc++). For cases like these, we can make the vtable hidden or
1047// internal and create a public alias with the same visibility and linkage as
1048// the original vtable type.
1049void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
1050 llvm::StringRef AliasNameRef) {
1051 assert(getItaniumVTableContext().isRelativeLayout() &&
1052 "Can only use this if the relative vtable ABI is used");
1053 assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
1054 "not guaranteed to be dso_local");
1055
1056 // If the vtable is available_externally, we shouldn't (or need to) generate
1057 // an alias for it in the first place since the vtable won't actually by
1058 // emitted in this compilation unit.
1059 if (VTable->hasAvailableExternallyLinkage())
1060 return;
1061
1062 // Create a new string in the event the alias is already the name of the
1063 // vtable. Using the reference directly could lead to use of an inititialized
1064 // value in the module's StringMap.
1065 llvm::SmallString<256> AliasName(AliasNameRef);
1066 VTable->setName(AliasName + ".local");
1067
1068 auto Linkage = VTable->getLinkage();
1069 assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
1070 "Invalid vtable alias linkage");
1071
1072 llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
1073 if (!VTableAlias) {
1074 VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
1075 VTable->getAddressSpace(), Linkage,
1076 AliasName, &CGM.getModule());
1077 } else {
1078 assert(VTableAlias->getValueType() == VTable->getValueType());
1079 assert(VTableAlias->getLinkage() == Linkage);
1080 }
1081 VTableAlias->setVisibility(VTable->getVisibility());
1082 VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
1083
1084 // Both of these will now imply dso_local for the vtable.
1085 if (!VTable->hasComdat()) {
1086 VTable->setLinkage(llvm::GlobalValue::InternalLinkage);
1087 } else {
1088 // If a relocation targets an internal linkage symbol, MC will generate the
1089 // relocation against the symbol's section instead of the symbol itself
1090 // (see ELFObjectWriter::shouldRelocateWithSymbol). If an internal symbol is
1091 // in a COMDAT section group, that section might be discarded, and then the
1092 // relocation to that section will generate a linker error. We therefore
1093 // make COMDAT vtables hidden instead of internal: they'll still not be
1094 // public, but relocations will reference the symbol instead of the section
1095 // and COMDAT deduplication will thus work as expected.
1096 VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1097 }
1098
1099 VTableAlias->setAliasee(VTable);
1100}
1101
1103 const CXXRecordDecl *RD) {
1104 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1106}
1107
1108/// Compute the required linkage of the vtable for the given class.
1109///
1110/// Note that we only call this at the end of the translation unit.
1111llvm::GlobalVariable::LinkageTypes
1113 if (!RD->isExternallyVisible())
1114 return llvm::GlobalVariable::InternalLinkage;
1115
1116 // In windows, the linkage of vtable is not related to modules.
1117 bool IsInNamedModule = !getTarget().getCXXABI().isMicrosoft() &&
1118 RD->isInNamedModule();
1119 // If the CXXRecordDecl is not in a module unit, we need to get
1120 // its key function. We're at the end of the translation unit, so the current
1121 // key function is fully correct.
1122 const CXXMethodDecl *keyFunction =
1123 IsInNamedModule ? nullptr : Context.getCurrentKeyFunction(RD);
1124 if (IsInNamedModule || (keyFunction && !RD->hasAttr<DLLImportAttr>())) {
1125 // If this class has a key function, use that to determine the
1126 // linkage of the vtable.
1127 const FunctionDecl *def = nullptr;
1128 if (keyFunction && keyFunction->hasBody(def))
1129 keyFunction = cast<CXXMethodDecl>(def);
1130
1131 bool IsExternalDefinition =
1132 IsInNamedModule ? RD->shouldEmitInExternalSource() : !def;
1133
1135 IsInNamedModule ? RD->getTemplateSpecializationKind()
1136 : keyFunction->getTemplateSpecializationKind();
1137
1138 switch (Kind) {
1139 case TSK_Undeclared:
1141 assert(
1142 (IsInNamedModule || def || CodeGenOpts.OptimizationLevel > 0 ||
1143 CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo) &&
1144 "Shouldn't query vtable linkage without the class in module units, "
1145 "key function, optimizations, or debug info");
1146 if (IsExternalDefinition && CodeGenOpts.OptimizationLevel > 0)
1147 return llvm::GlobalVariable::AvailableExternallyLinkage;
1148
1149 if (keyFunction && keyFunction->isInlined())
1150 return !Context.getLangOpts().AppleKext
1151 ? llvm::GlobalVariable::LinkOnceODRLinkage
1152 : llvm::Function::InternalLinkage;
1153
1154 return llvm::GlobalVariable::ExternalLinkage;
1155
1157 return !Context.getLangOpts().AppleKext ?
1158 llvm::GlobalVariable::LinkOnceODRLinkage :
1159 llvm::Function::InternalLinkage;
1160
1162 return !Context.getLangOpts().AppleKext ?
1163 llvm::GlobalVariable::WeakODRLinkage :
1164 llvm::Function::InternalLinkage;
1165
1167 return IsExternalDefinition
1168 ? llvm::GlobalVariable::AvailableExternallyLinkage
1169 : llvm::GlobalVariable::ExternalLinkage;
1170 }
1171 }
1172
1173 // -fapple-kext mode does not support weak linkage, so we must use
1174 // internal linkage.
1175 if (Context.getLangOpts().AppleKext)
1176 return llvm::Function::InternalLinkage;
1177
1178 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1179 llvm::GlobalValue::LinkOnceODRLinkage;
1180 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1181 llvm::GlobalValue::WeakODRLinkage;
1182 if (RD->hasAttr<DLLExportAttr>()) {
1183 // Cannot discard exported vtables.
1184 DiscardableODRLinkage = NonDiscardableODRLinkage;
1185 } else if (RD->hasAttr<DLLImportAttr>()) {
1186 // Imported vtables are available externally.
1187 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1188 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1189 }
1190
1191 switch (RD->getTemplateSpecializationKind()) {
1192 case TSK_Undeclared:
1195 return DiscardableODRLinkage;
1196
1198 // Explicit instantiations in MSVC do not provide vtables, so we must emit
1199 // our own.
1200 if (getTarget().getCXXABI().isMicrosoft())
1201 return DiscardableODRLinkage;
1202 return shouldEmitAvailableExternallyVTable(*this, RD)
1203 ? llvm::GlobalVariable::AvailableExternallyLinkage
1204 : llvm::GlobalVariable::ExternalLinkage;
1205
1207 return NonDiscardableODRLinkage;
1208 }
1209
1210 llvm_unreachable("Invalid TemplateSpecializationKind!");
1211}
1212
1213/// This is a callback from Sema to tell us that a particular vtable is
1214/// required to be emitted in this translation unit.
1215///
1216/// This is only called for vtables that _must_ be emitted (mainly due to key
1217/// functions). For weak vtables, CodeGen tracks when they are needed and
1218/// emits them as-needed.
1220 VTables.GenerateClassData(theClass);
1221}
1222
1223void
1225 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1226 DI->completeClassData(RD);
1227
1228 if (RD->getNumVBases())
1229 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1230
1231 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
1232}
1233
1234/// At this point in the translation unit, does it appear that can we
1235/// rely on the vtable being defined elsewhere in the program?
1236///
1237/// The response is really only definitive when called at the end of
1238/// the translation unit.
1239///
1240/// The only semantic restriction here is that the object file should
1241/// not contain a vtable definition when that vtable is defined
1242/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
1243/// vtables when unnecessary.
1245 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
1246
1247 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1248 // emit them even if there is an explicit template instantiation.
1249 if (CGM.getTarget().getCXXABI().isMicrosoft())
1250 return false;
1251
1252 // If we have an explicit instantiation declaration (and not a
1253 // definition), the vtable is defined elsewhere.
1256 return true;
1257
1258 // Otherwise, if the class is an instantiated template, the
1259 // vtable must be defined here.
1260 if (TSK == TSK_ImplicitInstantiation ||
1262 return false;
1263
1264 // Otherwise, if the class is attached to a module, the tables are uniquely
1265 // emitted in the object for the module unit in which it is defined.
1266 if (RD->isInNamedModule())
1267 return RD->shouldEmitInExternalSource();
1268
1269 // Otherwise, if the class doesn't have a key function (possibly
1270 // anymore), the vtable must be defined here.
1271 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1272 if (!keyFunction)
1273 return false;
1274
1275 // Otherwise, if we don't have a definition of the key function, the
1276 // vtable must be defined somewhere else.
1277 return !keyFunction->hasBody();
1278}
1279
1280/// Given that we're currently at the end of the translation unit, and
1281/// we've emitted a reference to the vtable for this class, should
1282/// we define that vtable?
1284 const CXXRecordDecl *RD) {
1285 // If vtable is internal then it has to be done.
1286 if (!CGM.getVTables().isVTableExternal(RD))
1287 return true;
1288
1289 // If it's external then maybe we will need it as available_externally.
1291}
1292
1293/// Given that at some point we emitted a reference to one or more
1294/// vtables, and that we are now at the end of the translation unit,
1295/// decide whether we should emit them.
1296void CodeGenModule::EmitDeferredVTables() {
1297#ifndef NDEBUG
1298 // Remember the size of DeferredVTables, because we're going to assume
1299 // that this entire operation doesn't modify it.
1300 size_t savedSize = DeferredVTables.size();
1301#endif
1302
1303 for (const CXXRecordDecl *RD : DeferredVTables)
1305 VTables.GenerateClassData(RD);
1306 else if (shouldOpportunisticallyEmitVTables())
1307 OpportunisticVTables.push_back(RD);
1308
1309 assert(savedSize == DeferredVTables.size() &&
1310 "deferred extra vtables during vtable emission?");
1311 DeferredVTables.clear();
1312}
1313
1315 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>() ||
1316 RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1317 return true;
1318
1319 if (!getCodeGenOpts().LTOVisibilityPublicStd)
1320 return false;
1321
1322 const DeclContext *DC = RD;
1323 while (true) {
1324 auto *D = cast<Decl>(DC);
1325 DC = DC->getParent();
1327 if (auto *ND = dyn_cast<NamespaceDecl>(D))
1328 if (const IdentifierInfo *II = ND->getIdentifier())
1329 if (II->isStr("std") || II->isStr("stdext"))
1330 return true;
1331 break;
1332 }
1333 }
1334
1335 return false;
1336}
1337
1341 return true;
1342
1343 if (!getTriple().isOSBinFormatCOFF() &&
1345 return false;
1346
1347 return !AlwaysHasLTOVisibilityPublic(RD);
1348}
1349
1350llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
1351 const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1352 // If we have already visited this RD (which means this is a recursive call
1353 // since the initial call should have an empty Visited set), return the max
1354 // visibility. The recursive calls below compute the min between the result
1355 // of the recursive call and the current TypeVis, so returning the max here
1356 // ensures that it will have no effect on the current TypeVis.
1357 if (!Visited.insert(RD).second)
1358 return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1359
1361 llvm::GlobalObject::VCallVisibility TypeVis;
1363 TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1364 else if (HasHiddenLTOVisibility(RD))
1365 TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1366 else
1367 TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1368
1369 for (const auto &B : RD->bases())
1370 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1371 TypeVis = std::min(
1372 TypeVis,
1373 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1374
1375 for (const auto &B : RD->vbases())
1376 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1377 TypeVis = std::min(
1378 TypeVis,
1379 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1380
1381 return TypeVis;
1382}
1383
1385 llvm::GlobalVariable *VTable,
1386 const VTableLayout &VTLayout) {
1387 // Emit type metadata on vtables with LTO or IR instrumentation or
1388 // speculative devirtualization.
1389 // In IR instrumentation, the type metadata is used to find out vtable
1390 // definitions (for type profiling) among all global variables.
1391 if (!getCodeGenOpts().LTOUnit && !getCodeGenOpts().hasProfileIRInstr() &&
1392 !getCodeGenOpts().DevirtualizeSpeculatively)
1393 return;
1394
1396
1397 struct AddressPoint {
1398 const CXXRecordDecl *Base;
1399 size_t Offset;
1400 std::string TypeName;
1401 bool operator<(const AddressPoint &RHS) const {
1402 int D = TypeName.compare(RHS.TypeName);
1403 return D < 0 || (D == 0 && Offset < RHS.Offset);
1404 }
1405 };
1406 std::vector<AddressPoint> AddressPoints;
1407 for (auto &&AP : VTLayout.getAddressPoints()) {
1408 AddressPoint N{AP.first.getBase(),
1409 VTLayout.getVTableOffset(AP.second.VTableIndex) +
1410 AP.second.AddressPointIndex,
1411 {}};
1412 llvm::raw_string_ostream Stream(N.TypeName);
1415 AddressPoints.push_back(std::move(N));
1416 }
1417
1418 // Sort the address points for determinism.
1419 llvm::sort(AddressPoints);
1420
1422 for (auto AP : AddressPoints) {
1423 // Create type metadata for the address point.
1424 AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
1425
1426 // The class associated with each address point could also potentially be
1427 // used for indirect calls via a member function pointer, so we need to
1428 // annotate the address of each function pointer with the appropriate member
1429 // function pointer type.
1430 for (unsigned I = 0; I != Comps.size(); ++I) {
1432 continue;
1434 Context.getMemberPointerType(Comps[I].getFunctionDecl()->getType(),
1435 /*Qualifier=*/std::nullopt, AP.Base));
1436 VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
1437 }
1438 }
1439
1440 if (getCodeGenOpts().VirtualFunctionElimination ||
1441 getCodeGenOpts().WholeProgramVTables) {
1442 llvm::DenseSet<const CXXRecordDecl *> Visited;
1443 llvm::GlobalObject::VCallVisibility TypeVis =
1444 GetVCallVisibilityLevel(RD, Visited);
1445 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1446 VTable->setVCallVisibilityMetadata(TypeVis);
1447 }
1448}
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
Definition CGVTables.cpp:76
static void resolveTopLevelMetadata(llvm::Function *Fn, llvm::ValueToValueMapTy &VMap)
This function clones a function's DISubprogram node and enters it into a value map with the intent th...
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM, const CXXRecordDecl *RD)
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM, const CXXRecordDecl *RD)
Given that we're currently at the end of the translation unit, and we've emitted a reference to the v...
static void AddRelativeLayoutOffset(const CodeGenModule &CGM, ConstantArrayBuilder &builder, CharUnits offset)
static void AddPointerLayoutOffset(const CodeGenModule &CGM, ConstantArrayBuilder &builder, CharUnits offset)
static bool similar(const ABIArgInfo &infoL, CanQualType typeL, const ABIArgInfo &infoR, CanQualType typeR)
Definition CGVTables.cpp:67
static bool UseRelativeLayout(const CodeGenModule &CGM)
static void setThunkProperties(CIRGenModule &cgm, const ThunkInfo &thunk, cir::FuncOp thunkFn, bool forVTable, GlobalDecl gd)
static bool shouldEmitVTableThunk(CIRGenModule &cgm, const CXXMethodDecl *md, bool isUnprototyped, bool forVTable)
static Decl::Kind getKind(const Decl *D)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
CanQualType getCanonicalTagType(const TagDecl *TD) const
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2827
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2286
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:608
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
base_class_range vbases()
Definition DeclCXX.h:625
bool isDynamicClass() const
Definition DeclCXX.h:574
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition CGBuilder.h:366
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it's possible to emit a vtable for RD, even though we do not know that the vtable h...
virtual llvm::Value * performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const CXXRecordDecl *UnadjustedClass, const ReturnAdjustment &RA)=0
virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment)=0
virtual bool exportThunk()=0
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
CGFunctionInfo - Class to encapsulate the information about a function definition.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:274
void add(RValue rvalue, QualType type)
Definition CGCall.h:302
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, llvm::FunctionCallee Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
Definition CGCall.cpp:4392
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, const ThunkInfo *Thunk, bool IsUnprototyped)
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
llvm::Function * GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5342
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::Type * ConvertTypeForMem(QualType T)
void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk, bool IsUnprototyped)
Generate a thunk for the given method.
void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo, bool IsUnprototyped)
static bool hasAggregateEvaluationKind(QualType T)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
const CGFunctionInfo * CurFnInfo
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::LLVMContext & getLLVMContext()
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:640
This class organizes the cross-function state that is used while generating LLVM code.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
llvm::GlobalObject::VCallVisibility GetVCallVisibilityLevel(const CXXRecordDecl *RD, llvm::DenseSet< const CXXRecordDecl * > &Visited)
Returns the vcall visibility of the given type.
llvm::Module & getModule() const
CodeGenVTables & getVTables()
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
const TargetInfo & getTarget() const
void EmitVTableTypeMetadata(const CXXRecordDecl *RD, llvm::GlobalVariable *VTable, const VTableLayout &VTLayout)
Emit type metadata for the given vtable using the given layout.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition CGClass.cpp:40
const llvm::Triple & getTriple() const
bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD)
Returns whether the given record has public LTO visibility (regardless of -lto-whole-program-visibili...
void EmitVTable(CXXRecordDecl *Class)
This is a callback from Sema to tell us that a particular vtable is required to be emitted in this tr...
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
ItaniumVTableContext & getItaniumVTableContext()
ASTContext & getContext() const
llvm::Type * getVTableComponentType() const
const CodeGenOptions & getCodeGenOpts() const
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
llvm::Constant * GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, GlobalDecl GD)
Get the address of the thunk for the given global decl.
Definition CGVTables.cpp:35
llvm::GlobalVariable * GetAddrOfVTable(const CXXRecordDecl *RD)
GetAddrOfVTable - Get the address of the VTable for the given record decl.
Definition CGVTables.cpp:41
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti, bool vtableHasLocalLinkage)
Add vtable components for the given vtable layout to the given global initializer.
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable, llvm::StringRef AliasNameRef)
Generate a public facing alias for the vtable and make the vtable either hidden or private.
ItaniumVTableContext & getItaniumVTableContext()
Definition CGVTables.h:87
CodeGenVTables(CodeGenModule &CGM)
Definition CGVTables.cpp:32
llvm::GlobalVariable * GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual, llvm::GlobalVariable::LinkageTypes Linkage, VTableAddressPointsMapTy &AddressPoints)
GenerateConstructionVTable - Generate a construction vtable for the given base subobject.
llvm::Type * getVTableType(const VTableLayout &layout)
Returns the type of a vtable with the given layout.
bool useRelativeLayout() const
Return true if the relative vtable layout is used.
llvm::Type * getVTableComponentType() const
Return the type used as components for a vtable.
bool isVTableExternal(const CXXRecordDecl *RD)
At this point in the translation unit, does it appear that can we rely on the vtable being defined el...
void RemoveHwasanMetadata(llvm::GlobalValue *GV) const
Specify a global should not be instrumented with hwasan.
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
void addRelativeOffsetToPosition(llvm::IntegerType *type, llvm::Constant *target, size_t position)
Same as addRelativeOffset(), but instead relative to an element in this aggregate,...
void add(llvm::Constant *value)
Add a new value to this initializer.
void addNullPointer(llvm::PointerType *ptrTy)
Add a null pointer of a specific type.
void addSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, GlobalDecl CalleeDecl, QualType CalleeType)
Add a signed pointer using the given pointer authentication schema.
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
A helper class of ConstantInitBuilder, used for building constant array initializers.
StructBuilder beginStruct(llvm::StructType *structTy=nullptr)
The standard implementation of ConstantInitBuilder used in Clang.
A helper class of ConstantInitBuilder, used for building constant struct initializers.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:375
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
static RValue get(llvm::Value *V)
Definition CGValue.h:99
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:379
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isInNamedModule() const
Whether this declaration comes from a named module.
SourceLocation getLocation() const
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:577
bool shouldEmitInExternalSource() const
Whether the definition of the declaration should be emitted in external sources.
Represents a function declaration or definition.
Definition Decl.h:2000
param_iterator param_end()
Definition Decl.h:2787
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4418
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3200
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3247
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
QualType getReturnType() const
Definition TypeBase.h:4851
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
GlobalDecl getWithDecl(const Decl *D)
Definition GlobalDecl.h:172
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
One of these records is kept for each identifier that is lexed.
GlobalDecl findOriginalMethod(GlobalDecl GD)
Return the method that added the v-table slot that will be used to call the given method.
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, const ThunkInfo &Thunk, bool ElideOverrideInfo, raw_ostream &)=0
virtual void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool ElideOverrideInfo, raw_ostream &)=0
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition Decl.cpp:1226
bool isExternallyVisible() const
Definition Decl.h:433
Represents a parameter to a function.
Definition Decl.h:1790
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8472
Encodes a location in the source.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool isVoidType() const
Definition TypeBase.h:8991
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1922
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
@ CK_DeletingDtorPointer
A pointer to the deleting destructor.
@ CK_UnusedFunctionPointer
An entry that is never used.
@ CK_CompleteDtorPointer
A pointer to the complete destructor.
SmallVector< ThunkInfo, 1 > ThunkInfoVectorTy
const AddressPointsIndexMapTy & getAddressPointIndices() const
size_t getVTableOffset(size_t i) const
ArrayRef< VTableComponent > vtable_components() const
size_t getNumVTables() const
ArrayRef< VTableThunkTy > vtable_thunks() const
const AddressPointsMapTy & getAddressPoints() const
size_t getVTableSize(size_t i) const
QualType getType() const
Definition Decl.h:723
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
U cast(CodeGen::Address addr)
Definition Address.h:327
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
bool isEmpty() const
Definition Thunk.h:70
The this pointer adjustment as well as an optional return adjustment for a thunk.
Definition Thunk.h:157
ReturnAdjustment Return
The return adjustment.
Definition Thunk.h:162
const Type * ThisType
Definition Thunk.h:173