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 for (auto &BB : *Fn) {
144 for (auto &I : BB) {
145 for (llvm::DbgVariableRecord &DVR :
146 llvm::filterDbgVars(I.getDbgRecordRange())) {
147 auto *DILocal = DVR.getVariable();
148 if (!DILocal->isResolved())
149 DILocal->resolve();
150 }
151 if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
152 auto *DILocal = DII->getVariable();
153 if (!DILocal->isResolved())
154 DILocal->resolve();
155 }
156 }
157 }
158}
159
160// This function does roughly the same thing as GenerateThunk, but in a
161// very different way, so that va_start and va_end work correctly.
162// FIXME: This function assumes "this" is the first non-sret LLVM argument of
163// a function, and that there is an alloca built in the entry block
164// for all accesses to "this".
165// FIXME: This function assumes there is only one "ret" statement per function.
166// FIXME: Cloning isn't correct in the presence of indirect goto!
167// FIXME: This implementation of thunks bloats codesize by duplicating the
168// function definition. There are alternatives:
169// 1. Add some sort of stub support to LLVM for cases where we can
170// do a this adjustment, then a sibcall.
171// 2. We could transform the definition to take a va_list instead of an
172// actual variable argument list, then have the thunks (including a
173// no-op thunk for the regular definition) call va_start/va_end.
174// There's a bit of per-call overhead for this solution, but it's
175// better for codesize if the definition is long.
176llvm::Function *
178 const CGFunctionInfo &FnInfo,
179 GlobalDecl GD, const ThunkInfo &Thunk) {
180 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
181 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
182 QualType ResultType = FPT->getReturnType();
183
184 // Get the original function
185 assert(FnInfo.isVariadic());
186 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
187 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
188 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
189
190 // Cloning can't work if we don't have a definition. The Microsoft ABI may
191 // require thunks when a definition is not available. Emit an error in these
192 // cases.
193 if (!MD->isDefined()) {
194 CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
195 return Fn;
196 }
197 assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
198
199 // Clone to thunk.
200 llvm::ValueToValueMapTy VMap;
201
202 // We are cloning a function while some Metadata nodes are still unresolved.
203 // Ensure that the value mapper does not encounter any of them.
204 resolveTopLevelMetadata(BaseFn, VMap);
205 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
206 Fn->replaceAllUsesWith(NewFn);
207 NewFn->takeName(Fn);
208 Fn->eraseFromParent();
209 Fn = NewFn;
210
211 // "Initialize" CGF (minimally).
212 CurFn = Fn;
213
214 // Get the "this" value
215 llvm::Function::arg_iterator AI = Fn->arg_begin();
216 if (CGM.ReturnTypeUsesSRet(FnInfo))
217 ++AI;
218
219 // Find the first store of "this", which will be to the alloca associated
220 // with "this".
223 CGM.getClassPointerAlignment(MD->getParent()));
224 llvm::BasicBlock *EntryBB = &Fn->front();
225 llvm::BasicBlock::iterator ThisStore =
226 llvm::find_if(*EntryBB, [&](llvm::Instruction &I) {
227 return isa<llvm::StoreInst>(I) && I.getOperand(0) == &*AI;
228 });
229 assert(ThisStore != EntryBB->end() &&
230 "Store of this should be in entry block?");
231 // Adjust "this", if necessary.
232 Builder.SetInsertPoint(&*ThisStore);
233
234 const CXXRecordDecl *ThisValueClass = Thunk.ThisType->getPointeeCXXRecordDecl();
235 llvm::Value *AdjustedThisPtr = CGM.getCXXABI().performThisAdjustment(
236 *this, ThisPtr, ThisValueClass, Thunk);
237 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
238 ThisStore->getOperand(0)->getType());
239 ThisStore->setOperand(0, AdjustedThisPtr);
240
241 if (!Thunk.Return.isEmpty()) {
242 // Fix up the returned value, if necessary.
243 for (llvm::BasicBlock &BB : *Fn) {
244 llvm::Instruction *T = BB.getTerminator();
246 RValue RV = RValue::get(T->getOperand(0));
247 T->eraseFromParent();
248 Builder.SetInsertPoint(&BB);
249 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
250 Builder.CreateRet(RV.getScalarVal());
251 break;
252 }
253 }
254 }
255
256 return Fn;
257}
258
259void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
260 const CGFunctionInfo &FnInfo,
261 bool IsUnprototyped) {
262 assert(!CurGD.getDecl() && "CurGD was already set!");
263 CurGD = GD;
264 CurFuncIsThunk = true;
265
266 // Build FunctionArgs.
267 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
268 QualType ThisType = MD->getThisType();
269 QualType ResultType;
270 if (IsUnprototyped)
271 ResultType = CGM.getContext().VoidTy;
272 else if (CGM.getCXXABI().HasThisReturn(GD))
273 ResultType = ThisType;
274 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
275 ResultType = CGM.getContext().VoidPtrTy;
276 else
277 ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
278 FunctionArgList FunctionArgs;
279
280 // Create the implicit 'this' parameter declaration.
281 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
282
283 // Add the rest of the parameters, if we have a prototype to work with.
284 if (!IsUnprototyped) {
285 FunctionArgs.append(MD->param_begin(), MD->param_end());
286
288 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
289 FunctionArgs);
290 }
291
292 // Start defining the function.
293 auto NL = ApplyDebugLocation::CreateEmpty(*this);
294 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
295 MD->getLocation());
296 // Create a scope with an artificial location for the body of this function.
298
299 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
300 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
301 CXXThisValue = CXXABIThisValue;
302 CurCodeDecl = MD;
303 CurFuncDecl = MD;
304}
305
307 // Clear these to restore the invariants expected by
308 // StartFunction/FinishFunction.
309 CurCodeDecl = nullptr;
310 CurFuncDecl = nullptr;
311
313}
314
315void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
316 const ThunkInfo *Thunk,
317 bool IsUnprototyped) {
318 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
319 "Please use a new CGF for this thunk");
320 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
321
322 // Adjust the 'this' pointer if necessary
323 const CXXRecordDecl *ThisValueClass =
325 if (Thunk)
326 ThisValueClass = Thunk->ThisType->getPointeeCXXRecordDecl();
327
328 llvm::Value *AdjustedThisPtr =
329 Thunk ? CGM.getCXXABI().performThisAdjustment(*this, LoadCXXThisAddress(),
330 ThisValueClass, *Thunk)
331 : LoadCXXThis();
332
333 // If perfect forwarding is required a variadic method, a method using
334 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
335 // thunk requires a return adjustment, since that is impossible with musttail.
336 if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
337 if (Thunk && !Thunk->Return.isEmpty()) {
338 if (IsUnprototyped)
339 CGM.ErrorUnsupported(
340 MD, "return-adjusting thunk with incomplete parameter type");
341 else if (CurFnInfo->isVariadic())
342 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
343 "thunks for variadic functions");
344 else
345 CGM.ErrorUnsupported(
346 MD, "non-trivial argument copy for return-adjusting thunk");
347 }
348 EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
349 return;
350 }
351
352 // Start building CallArgs.
353 CallArgList CallArgs;
354 QualType ThisType = MD->getThisType();
355 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
356
358 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
359
360#ifndef NDEBUG
361 unsigned PrefixArgs = CallArgs.size() - 1;
362#endif
363 // Add the rest of the arguments.
364 for (const ParmVarDecl *PD : MD->parameters())
365 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
366
367 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
368
369#ifndef NDEBUG
370 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
371 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
372 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
373 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
374 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
375 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
376 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
377 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
378 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
379 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
380 assert(similar(CallFnInfo.arg_begin()[i].info,
381 CallFnInfo.arg_begin()[i].type,
382 CurFnInfo->arg_begin()[i].info,
383 CurFnInfo->arg_begin()[i].type));
384#endif
385
386 // Determine whether we have a return value slot to use.
387 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
388 ? ThisType
389 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
390 ? CGM.getContext().VoidPtrTy
391 : FPT->getReturnType();
392 ReturnValueSlot Slot;
393 if (!ResultType->isVoidType() &&
394 (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
395 hasAggregateEvaluationKind(ResultType)))
397 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
398
399 // Now emit our call.
400 llvm::CallBase *CallOrInvoke;
401 RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
402 CallArgs, &CallOrInvoke);
403
404 // Consider return adjustment if we have ThunkInfo.
405 if (Thunk && !Thunk->Return.isEmpty())
406 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
407 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
408 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
409
410 // Emit return.
411 if (!ResultType->isVoidType() && Slot.isNull())
412 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
413
414 // Disable the final ARC autorelease.
415 AutoreleaseResult = false;
416
417 FinishThunk();
418}
419
421 llvm::Value *AdjustedThisPtr,
422 llvm::FunctionCallee Callee) {
423 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
424 // to translate AST arguments into LLVM IR arguments. For thunks, we know
425 // that the caller prototype more or less matches the callee prototype with
426 // the exception of 'this'.
427 SmallVector<llvm::Value *, 8> Args(llvm::make_pointer_range(CurFn->args()));
428
429 // Set the adjusted 'this' pointer.
430 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
431 if (ThisAI.isDirect()) {
432 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
433 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
434 llvm::Type *ThisType = Args[ThisArgNo]->getType();
435 if (ThisType != AdjustedThisPtr->getType())
436 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
437 Args[ThisArgNo] = AdjustedThisPtr;
438 } else {
439 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
440 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
441 llvm::Type *ThisType = ThisAddr.getElementType();
442 if (ThisType != AdjustedThisPtr->getType())
443 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
444 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
445 }
446
447 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
448 // don't actually want to run them.
449 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
450 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
451
452 // Apply the standard set of call attributes.
453 unsigned CallingConv;
454 llvm::AttributeList Attrs;
455 CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
456 Attrs, CallingConv, /*AttrOnCallSite=*/true,
457 /*IsThunk=*/false);
458 Call->setAttributes(Attrs);
459 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
460
461 if (Call->getType()->isVoidTy())
462 Builder.CreateRetVoid();
463 else
464 Builder.CreateRet(Call);
465
466 // Finish the function to maintain CodeGenFunction invariants.
467 // FIXME: Don't emit unreachable code.
469
470 FinishThunk();
471}
472
473void CodeGenFunction::generateThunk(llvm::Function *Fn,
474 const CGFunctionInfo &FnInfo, GlobalDecl GD,
475 const ThunkInfo &Thunk,
476 bool IsUnprototyped) {
477 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
478 // Create a scope with an artificial location for the body of this function.
480
481 // Get our callee. Use a placeholder type if this method is unprototyped so
482 // that CodeGenModule doesn't try to set attributes.
483 llvm::Type *Ty;
484 if (IsUnprototyped)
485 Ty = llvm::StructType::get(getLLVMContext());
486 else
487 Ty = CGM.getTypes().GetFunctionType(FnInfo);
488
489 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
490
491 // Make the call and return the result.
492 EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
493 &Thunk, IsUnprototyped);
494}
495
497 bool IsUnprototyped, bool ForVTable) {
498 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
499 // provide thunks for us.
500 if (CGM.getTarget().getCXXABI().isMicrosoft())
501 return true;
502
503 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
504 // definitions of the main method. Therefore, emitting thunks with the vtable
505 // is purely an optimization. Emit the thunk if optimizations are enabled and
506 // all of the parameter types are complete.
507 if (ForVTable)
508 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
509
510 // Always emit thunks along with the method definition.
511 return true;
512}
513
514llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
515 const ThunkInfo &TI,
516 bool ForVTable) {
517 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
518
519 // First, get a declaration. Compute the mangled name. Don't worry about
520 // getting the function prototype right, since we may only need this
521 // declaration to fill in a vtable slot.
522 SmallString<256> Name;
523 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
524 llvm::raw_svector_ostream Out(Name);
525
526 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
527 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI,
528 /* elideOverrideInfo */ false, Out);
529 } else
530 MCtx.mangleThunk(MD, TI, /* elideOverrideInfo */ false, Out);
531
532 if (CGM.getContext().useAbbreviatedThunkName(GD, Name.str())) {
533 Name = "";
534 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
535 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI,
536 /* elideOverrideInfo */ true, Out);
537 else
538 MCtx.mangleThunk(MD, TI, /* elideOverrideInfo */ true, Out);
539 }
540
541 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
542 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
543
544 // If we don't need to emit a definition, return this declaration as is.
545 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
546 MD->getType()->castAs<FunctionType>());
547 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
548 return Thunk;
549
550 // Arrange a function prototype appropriate for a function definition. In some
551 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
552 const CGFunctionInfo &FnInfo =
553 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
554 : CGM.getTypes().arrangeGlobalDeclaration(GD);
555 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
556
557 // If the type of the underlying GlobalValue is wrong, we'll have to replace
558 // it. It should be a declaration.
559 llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
560 if (ThunkFn->getFunctionType() != ThunkFnTy) {
561 llvm::GlobalValue *OldThunkFn = ThunkFn;
562
563 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
564
565 // Remove the name from the old thunk function and get a new thunk.
566 OldThunkFn->setName(StringRef());
567 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
568 Name.str(), &CGM.getModule());
569 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
570
571 if (!OldThunkFn->use_empty()) {
572 OldThunkFn->replaceAllUsesWith(ThunkFn);
573 }
574
575 // Remove the old thunk.
576 OldThunkFn->eraseFromParent();
577 }
578
579 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
580 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
581
582 if (!ThunkFn->isDeclaration()) {
583 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
584 // There is already a thunk emitted for this function, do nothing.
585 return ThunkFn;
586 }
587
588 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
589 return ThunkFn;
590 }
591
592 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
593 // that the return type is meaningless. These thunks can be used to call
594 // functions with differing return types, and the caller is required to cast
595 // the prototype appropriately to extract the correct value.
596 if (IsUnprototyped)
597 ThunkFn->addFnAttr("thunk");
598
599 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
600
601 // Thunks for variadic methods are special because in general variadic
602 // arguments cannot be perfectly forwarded. In the general case, clang
603 // implements such thunks by cloning the original function body. However, for
604 // thunks with no return adjustment on targets that support musttail, we can
605 // use musttail to perfectly forward the variadic arguments.
606 bool ShouldCloneVarArgs = false;
607 if (!IsUnprototyped && ThunkFn->isVarArg()) {
608 ShouldCloneVarArgs = true;
609 if (TI.Return.isEmpty()) {
610 switch (CGM.getTriple().getArch()) {
611 case llvm::Triple::x86_64:
612 case llvm::Triple::x86:
613 case llvm::Triple::aarch64:
614 ShouldCloneVarArgs = false;
615 break;
616 default:
617 break;
618 }
619 }
620 }
621
622 if (ShouldCloneVarArgs) {
623 if (UseAvailableExternallyLinkage)
624 return ThunkFn;
625 ThunkFn =
626 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
627 } else {
628 // Normal thunk body generation.
629 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
630 }
631
632 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
633 return ThunkFn;
634}
635
637 const CXXMethodDecl *MD =
638 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
639
640 // We don't need to generate thunks for the base destructor.
642 return;
643
644 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
645 VTContext->getThunkInfo(GD);
646
647 if (!ThunkInfoVector)
648 return;
649
650 for (const ThunkInfo& Thunk : *ThunkInfoVector)
651 maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
652}
653
654void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
655 llvm::Constant *component,
656 unsigned vtableAddressPoint,
657 bool vtableHasLocalLinkage,
658 bool isCompleteDtor) const {
659 // No need to get the offset of a nullptr.
660 if (component->isNullValue())
661 return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
662
663 auto *globalVal =
664 cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
665 llvm::Module &module = CGM.getModule();
666
667 // We don't want to copy the linkage of the vtable exactly because we still
668 // want the stub/proxy to be emitted for properly calculating the offset.
669 // Examples where there would be no symbol emitted are available_externally
670 // and private linkages.
671 //
672 // `internal` linkage results in STB_LOCAL Elf binding while still manifesting a
673 // local symbol.
674 //
675 // `linkonce_odr` linkage results in a STB_DEFAULT Elf binding but also allows for
676 // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
677 // target that supports this replacement.
678 auto stubLinkage = vtableHasLocalLinkage
679 ? llvm::GlobalValue::InternalLinkage
680 : llvm::GlobalValue::LinkOnceODRLinkage;
681
682 llvm::Constant *target;
683 if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
684 target = llvm::DSOLocalEquivalent::get(func);
685 } else {
686 llvm::SmallString<16> rttiProxyName(globalVal->getName());
687 rttiProxyName.append(".rtti_proxy");
688
689 // The RTTI component may not always be emitted in the same linkage unit as
690 // the vtable. As a general case, we can make a dso_local proxy to the RTTI
691 // that points to the actual RTTI struct somewhere. This will result in a
692 // GOTPCREL relocation when taking the relative offset to the proxy.
693 llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
694 if (!proxy) {
695 proxy = new llvm::GlobalVariable(module, globalVal->getType(),
696 /*isConstant=*/true, stubLinkage,
697 globalVal, rttiProxyName);
698 proxy->setDSOLocal(true);
699 proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
700 if (!proxy->hasLocalLinkage()) {
701 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
702 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
703 }
704 // Do not instrument the rtti proxies with hwasan to avoid a duplicate
705 // symbol error. Aliases generated by hwasan will retain the same namebut
706 // the addresses they are set to may have different tags from different
707 // compilation units. We don't run into this without hwasan because the
708 // proxies are in comdat groups, but those aren't propagated to the alias.
710 }
711 target = proxy;
712 }
713
714 builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
715 /*position=*/vtableAddressPoint);
716}
717
718static bool UseRelativeLayout(const CodeGenModule &CGM) {
719 return CGM.getTarget().getCXXABI().isItaniumFamily() &&
721}
722
724 return UseRelativeLayout(CGM);
725}
726
728 if (UseRelativeLayout(*this))
729 return Int32Ty;
730 return GlobalsInt8PtrTy;
731}
732
734 return CGM.getVTableComponentType();
735}
736
738 ConstantArrayBuilder &builder,
739 CharUnits offset) {
740 builder.add(llvm::ConstantExpr::getIntToPtr(
741 llvm::ConstantInt::getSigned(CGM.PtrDiffTy, offset.getQuantity()),
742 CGM.GlobalsInt8PtrTy));
743}
744
746 ConstantArrayBuilder &builder,
747 CharUnits offset) {
748 builder.add(llvm::ConstantInt::getSigned(CGM.Int32Ty, offset.getQuantity()));
749}
750
751void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
752 const VTableLayout &layout,
753 unsigned componentIndex,
754 llvm::Constant *rtti,
755 unsigned &nextVTableThunkIndex,
756 unsigned vtableAddressPoint,
757 bool vtableHasLocalLinkage) {
758 auto &component = layout.vtable_components()[componentIndex];
759
760 auto addOffsetConstant =
762
763 switch (component.getKind()) {
765 return addOffsetConstant(CGM, builder, component.getVCallOffset());
766
768 return addOffsetConstant(CGM, builder, component.getVBaseOffset());
769
771 return addOffsetConstant(CGM, builder, component.getOffsetToTop());
772
774 if (useRelativeLayout())
775 return addRelativeComponent(builder, rtti, vtableAddressPoint,
776 vtableHasLocalLinkage,
777 /*isCompleteDtor=*/false);
778 else
779 return builder.add(rtti);
780
784 GlobalDecl GD = component.getGlobalDecl(
785 CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
786 CGM.getContext().getLangOpts()));
787
788 const bool IsThunk =
789 nextVTableThunkIndex < layout.vtable_thunks().size() &&
790 layout.vtable_thunks()[nextVTableThunkIndex].first == componentIndex;
791
792 if (CGM.getLangOpts().CUDA) {
793 // Emit NULL for methods we can't codegen on this
794 // side. Otherwise we'd end up with vtable with unresolved
795 // references.
796 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
797 // OK on device side: functions w/ __device__ attribute
798 // OK on host side: anything except __device__-only functions.
799 bool CanEmitMethod =
800 CGM.getLangOpts().CUDAIsDevice
801 ? MD->hasAttr<CUDADeviceAttr>()
802 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
803 if (!CanEmitMethod) {
804 if (IsThunk)
805 nextVTableThunkIndex++;
806 return builder.add(
807 llvm::ConstantExpr::getNullValue(CGM.GlobalsInt8PtrTy));
808 }
809 // Method is acceptable, continue processing as usual.
810 }
811
812 auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
813 // FIXME(PR43094): When merging comdat groups, lld can select a local
814 // symbol as the signature symbol even though it cannot be accessed
815 // outside that symbol's TU. The relative vtables ABI would make
816 // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
817 // depending on link order, the comdat groups could resolve to the one
818 // with the local symbol. As a temporary solution, fill these components
819 // with zero. We shouldn't be calling these in the first place anyway.
820 if (useRelativeLayout())
821 return llvm::ConstantPointerNull::get(CGM.GlobalsInt8PtrTy);
822
823 // For NVPTX devices in OpenMP emit special functon as null pointers,
824 // otherwise linking ends up with unresolved references.
825 if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsTargetDevice &&
826 CGM.getTriple().isNVPTX())
827 return llvm::ConstantPointerNull::get(CGM.GlobalsInt8PtrTy);
828 llvm::FunctionType *fnTy =
829 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
830 llvm::Constant *fn = cast<llvm::Constant>(
831 CGM.CreateRuntimeFunction(fnTy, name).getCallee());
832 if (auto f = dyn_cast<llvm::Function>(fn))
833 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
834 return fn;
835 };
836
837 llvm::Constant *fnPtr;
838
839 // Pure virtual member functions.
840 if (cast<CXXMethodDecl>(GD.getDecl())->isPureVirtual()) {
841 if (!PureVirtualFn)
842 PureVirtualFn =
843 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
844 fnPtr = PureVirtualFn;
845
846 // Deleted virtual member functions.
847 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
848 if (!DeletedVirtualFn)
849 DeletedVirtualFn =
850 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
851 fnPtr = DeletedVirtualFn;
852
853 // Thunks.
854 } else if (IsThunk) {
855 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
856
857 nextVTableThunkIndex++;
858 fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
859 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {
860 assert(thunkInfo.Method && "Method not set");
861 GD = GD.getWithDecl(thunkInfo.Method);
862 }
863
864 // Otherwise we can use the method definition directly.
865 } else {
866 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
867 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
868 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
870 }
871
872 if (useRelativeLayout()) {
873 return addRelativeComponent(
874 builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
875 component.getKind() == VTableComponent::CK_CompleteDtorPointer);
876 } else {
877 // TODO: this icky and only exists due to functions being in the generic
878 // address space, rather than the global one, even though they are
879 // globals; fixing said issue might be intrusive, and will be done
880 // later.
881 unsigned FnAS = fnPtr->getType()->getPointerAddressSpace();
882 unsigned GVAS = CGM.GlobalsInt8PtrTy->getPointerAddressSpace();
883
884 if (FnAS != GVAS)
885 fnPtr =
886 llvm::ConstantExpr::getAddrSpaceCast(fnPtr, CGM.GlobalsInt8PtrTy);
887 if (const auto &Schema =
888 CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
889 return builder.addSignedPointer(fnPtr, Schema, GD, QualType());
890 return builder.add(fnPtr);
891 }
892 }
893
895 if (useRelativeLayout())
896 return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
897 else
898 return builder.addNullPointer(CGM.GlobalsInt8PtrTy);
899 }
900
901 llvm_unreachable("Unexpected vtable component kind");
902}
903
904llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
906 llvm::Type *componentType = getVTableComponentType();
907 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
908 tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
909
910 return llvm::StructType::get(CGM.getLLVMContext(), tys);
911}
912
914 const VTableLayout &layout,
915 llvm::Constant *rtti,
916 bool vtableHasLocalLinkage) {
917 llvm::Type *componentType = getVTableComponentType();
918
919 const auto &addressPoints = layout.getAddressPointIndices();
920 unsigned nextVTableThunkIndex = 0;
921 for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
922 vtableIndex != endIndex; ++vtableIndex) {
923 auto vtableElem = builder.beginArray(componentType);
924
925 size_t vtableStart = layout.getVTableOffset(vtableIndex);
926 size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
927 for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
928 ++componentIndex) {
929 addVTableComponent(vtableElem, layout, componentIndex, rtti,
930 nextVTableThunkIndex, addressPoints[vtableIndex],
931 vtableHasLocalLinkage);
932 }
933 vtableElem.finishAndAddTo(builder);
934 }
935}
936
938 const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
939 llvm::GlobalVariable::LinkageTypes Linkage,
940 VTableAddressPointsMapTy &AddressPoints) {
941 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
942 DI->completeClassData(Base.getBase());
943
944 std::unique_ptr<VTableLayout> VTLayout(
945 getItaniumVTableContext().createConstructionVTableLayout(
946 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
947
948 // Add the address points.
949 AddressPoints = VTLayout->getAddressPoints();
950
951 // Get the mangled construction vtable name.
952 SmallString<256> OutName;
953 llvm::raw_svector_ostream Out(OutName);
954 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
955 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
956 Base.getBase(), Out);
957 SmallString<256> Name(OutName);
958
959 bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
960 bool VTableAliasExists =
961 UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
962 if (VTableAliasExists) {
963 // We previously made the vtable hidden and changed its name.
964 Name.append(".local");
965 }
966
967 llvm::Type *VTType = getVTableType(*VTLayout);
968
969 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
970 // guarantee that they actually will be available externally. Instead, when
971 // emitting an available_externally VTT, we provide references to an internal
972 // linkage construction vtable. The ABI only requires complete-object vtables
973 // to be the same for all instances of a type, not construction vtables.
974 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
975 Linkage = llvm::GlobalVariable::InternalLinkage;
976
977 llvm::Align Align = CGM.getDataLayout().getABITypeAlign(VTType);
978
979 // Create the variable that will hold the construction vtable.
980 llvm::GlobalVariable *VTable =
981 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
982
983 // V-tables are always unnamed_addr.
984 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
985
986 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
987 CGM.getContext().getCanonicalTagType(Base.getBase()));
988
989 // Create and set the initializer.
990 ConstantInitBuilder builder(CGM);
991 auto components = builder.beginStruct();
992 createVTableInitializer(components, *VTLayout, RTTI,
993 VTable->hasLocalLinkage());
994 components.finishAndSetAsInitializer(VTable);
995
996 // Set properties only after the initializer has been set to ensure that the
997 // GV is treated as definition and not declaration.
998 assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
999 CGM.setGVProperties(VTable, RD);
1000
1001 CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout);
1002
1003 if (UsingRelativeLayout) {
1004 RemoveHwasanMetadata(VTable);
1005 if (!VTable->isDSOLocal())
1006 GenerateRelativeVTableAlias(VTable, OutName);
1007 }
1008
1009 return VTable;
1010}
1011
1012// Ensure this vtable is not instrumented by hwasan. That is, a global alias is
1013// not generated for it. This is mainly used by the relative-vtables ABI where
1014// vtables instead contain 32-bit offsets between the vtable and function
1015// pointers. Hwasan is disabled for these vtables for now because the tag in a
1016// vtable pointer may fail the overflow check when resolving 32-bit PLT
1017// relocations. A future alternative for this would be finding which usages of
1018// the vtable can continue to use the untagged hwasan value without any loss of
1019// value in hwasan.
1020void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *GV) const {
1021 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
1022 llvm::GlobalValue::SanitizerMetadata Meta;
1023 if (GV->hasSanitizerMetadata())
1024 Meta = GV->getSanitizerMetadata();
1025 Meta.NoHWAddress = true;
1026 GV->setSanitizerMetadata(Meta);
1027 }
1028}
1029
1030// If the VTable is not dso_local, then we will not be able to indicate that
1031// the VTable does not need a relocation and move into rodata. A frequent
1032// time this can occur is for classes that should be made public from a DSO
1033// (like in libc++). For cases like these, we can make the vtable hidden or
1034// internal and create a public alias with the same visibility and linkage as
1035// the original vtable type.
1036void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
1037 llvm::StringRef AliasNameRef) {
1038 assert(getItaniumVTableContext().isRelativeLayout() &&
1039 "Can only use this if the relative vtable ABI is used");
1040 assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
1041 "not guaranteed to be dso_local");
1042
1043 // If the vtable is available_externally, we shouldn't (or need to) generate
1044 // an alias for it in the first place since the vtable won't actually by
1045 // emitted in this compilation unit.
1046 if (VTable->hasAvailableExternallyLinkage())
1047 return;
1048
1049 // Create a new string in the event the alias is already the name of the
1050 // vtable. Using the reference directly could lead to use of an inititialized
1051 // value in the module's StringMap.
1052 llvm::SmallString<256> AliasName(AliasNameRef);
1053 VTable->setName(AliasName + ".local");
1054
1055 auto Linkage = VTable->getLinkage();
1056 assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
1057 "Invalid vtable alias linkage");
1058
1059 llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
1060 if (!VTableAlias) {
1061 VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
1062 VTable->getAddressSpace(), Linkage,
1063 AliasName, &CGM.getModule());
1064 } else {
1065 assert(VTableAlias->getValueType() == VTable->getValueType());
1066 assert(VTableAlias->getLinkage() == Linkage);
1067 }
1068 VTableAlias->setVisibility(VTable->getVisibility());
1069 VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
1070
1071 // Both of these will now imply dso_local for the vtable.
1072 if (!VTable->hasComdat()) {
1073 VTable->setLinkage(llvm::GlobalValue::InternalLinkage);
1074 } else {
1075 // If a relocation targets an internal linkage symbol, MC will generate the
1076 // relocation against the symbol's section instead of the symbol itself
1077 // (see ELFObjectWriter::shouldRelocateWithSymbol). If an internal symbol is
1078 // in a COMDAT section group, that section might be discarded, and then the
1079 // relocation to that section will generate a linker error. We therefore
1080 // make COMDAT vtables hidden instead of internal: they'll still not be
1081 // public, but relocations will reference the symbol instead of the section
1082 // and COMDAT deduplication will thus work as expected.
1083 VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1084 }
1085
1086 VTableAlias->setAliasee(VTable);
1087}
1088
1090 const CXXRecordDecl *RD) {
1091 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1093}
1094
1095/// Compute the required linkage of the vtable for the given class.
1096///
1097/// Note that we only call this at the end of the translation unit.
1098llvm::GlobalVariable::LinkageTypes
1100 if (!RD->isExternallyVisible())
1101 return llvm::GlobalVariable::InternalLinkage;
1102
1103 // In windows, the linkage of vtable is not related to modules.
1104 bool IsInNamedModule = !getTarget().getCXXABI().isMicrosoft() &&
1105 RD->isInNamedModule();
1106 // If the CXXRecordDecl is not in a module unit, we need to get
1107 // its key function. We're at the end of the translation unit, so the current
1108 // key function is fully correct.
1109 const CXXMethodDecl *keyFunction =
1110 IsInNamedModule ? nullptr : Context.getCurrentKeyFunction(RD);
1111 if (IsInNamedModule || (keyFunction && !RD->hasAttr<DLLImportAttr>())) {
1112 // If this class has a key function, use that to determine the
1113 // linkage of the vtable.
1114 const FunctionDecl *def = nullptr;
1115 if (keyFunction && keyFunction->hasBody(def))
1116 keyFunction = cast<CXXMethodDecl>(def);
1117
1118 bool IsExternalDefinition =
1119 IsInNamedModule ? RD->shouldEmitInExternalSource() : !def;
1120
1122 IsInNamedModule ? RD->getTemplateSpecializationKind()
1123 : keyFunction->getTemplateSpecializationKind();
1124
1125 switch (Kind) {
1126 case TSK_Undeclared:
1128 assert(
1129 (IsInNamedModule || def || CodeGenOpts.OptimizationLevel > 0 ||
1130 CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo) &&
1131 "Shouldn't query vtable linkage without the class in module units, "
1132 "key function, optimizations, or debug info");
1133 if (IsExternalDefinition && CodeGenOpts.OptimizationLevel > 0)
1134 return llvm::GlobalVariable::AvailableExternallyLinkage;
1135
1136 if (keyFunction && keyFunction->isInlined())
1137 return !Context.getLangOpts().AppleKext
1138 ? llvm::GlobalVariable::LinkOnceODRLinkage
1139 : llvm::Function::InternalLinkage;
1140
1141 return llvm::GlobalVariable::ExternalLinkage;
1142
1144 return !Context.getLangOpts().AppleKext ?
1145 llvm::GlobalVariable::LinkOnceODRLinkage :
1146 llvm::Function::InternalLinkage;
1147
1149 return !Context.getLangOpts().AppleKext ?
1150 llvm::GlobalVariable::WeakODRLinkage :
1151 llvm::Function::InternalLinkage;
1152
1154 return IsExternalDefinition
1155 ? llvm::GlobalVariable::AvailableExternallyLinkage
1156 : llvm::GlobalVariable::ExternalLinkage;
1157 }
1158 }
1159
1160 // -fapple-kext mode does not support weak linkage, so we must use
1161 // internal linkage.
1162 if (Context.getLangOpts().AppleKext)
1163 return llvm::Function::InternalLinkage;
1164
1165 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1166 llvm::GlobalValue::LinkOnceODRLinkage;
1167 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1168 llvm::GlobalValue::WeakODRLinkage;
1169 if (RD->hasAttr<DLLExportAttr>()) {
1170 // Cannot discard exported vtables.
1171 DiscardableODRLinkage = NonDiscardableODRLinkage;
1172 } else if (RD->hasAttr<DLLImportAttr>()) {
1173 // Imported vtables are available externally.
1174 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1175 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1176 }
1177
1178 switch (RD->getTemplateSpecializationKind()) {
1179 case TSK_Undeclared:
1182 return DiscardableODRLinkage;
1183
1185 // Explicit instantiations in MSVC do not provide vtables, so we must emit
1186 // our own.
1187 if (getTarget().getCXXABI().isMicrosoft())
1188 return DiscardableODRLinkage;
1189 return shouldEmitAvailableExternallyVTable(*this, RD)
1190 ? llvm::GlobalVariable::AvailableExternallyLinkage
1191 : llvm::GlobalVariable::ExternalLinkage;
1192
1194 return NonDiscardableODRLinkage;
1195 }
1196
1197 llvm_unreachable("Invalid TemplateSpecializationKind!");
1198}
1199
1200/// This is a callback from Sema to tell us that a particular vtable is
1201/// required to be emitted in this translation unit.
1202///
1203/// This is only called for vtables that _must_ be emitted (mainly due to key
1204/// functions). For weak vtables, CodeGen tracks when they are needed and
1205/// emits them as-needed.
1207 VTables.GenerateClassData(theClass);
1208}
1209
1210void
1212 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1213 DI->completeClassData(RD);
1214
1215 if (RD->getNumVBases())
1216 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1217
1218 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
1219}
1220
1221/// At this point in the translation unit, does it appear that can we
1222/// rely on the vtable being defined elsewhere in the program?
1223///
1224/// The response is really only definitive when called at the end of
1225/// the translation unit.
1226///
1227/// The only semantic restriction here is that the object file should
1228/// not contain a vtable definition when that vtable is defined
1229/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
1230/// vtables when unnecessary.
1232 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
1233
1234 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1235 // emit them even if there is an explicit template instantiation.
1236 if (CGM.getTarget().getCXXABI().isMicrosoft())
1237 return false;
1238
1239 // If we have an explicit instantiation declaration (and not a
1240 // definition), the vtable is defined elsewhere.
1243 return true;
1244
1245 // Otherwise, if the class is an instantiated template, the
1246 // vtable must be defined here.
1247 if (TSK == TSK_ImplicitInstantiation ||
1249 return false;
1250
1251 // Otherwise, if the class is attached to a module, the tables are uniquely
1252 // emitted in the object for the module unit in which it is defined.
1253 if (RD->isInNamedModule())
1254 return RD->shouldEmitInExternalSource();
1255
1256 // Otherwise, if the class doesn't have a key function (possibly
1257 // anymore), the vtable must be defined here.
1258 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1259 if (!keyFunction)
1260 return false;
1261
1262 // Otherwise, if we don't have a definition of the key function, the
1263 // vtable must be defined somewhere else.
1264 return !keyFunction->hasBody();
1265}
1266
1267/// Given that we're currently at the end of the translation unit, and
1268/// we've emitted a reference to the vtable for this class, should
1269/// we define that vtable?
1271 const CXXRecordDecl *RD) {
1272 // If vtable is internal then it has to be done.
1273 if (!CGM.getVTables().isVTableExternal(RD))
1274 return true;
1275
1276 // If it's external then maybe we will need it as available_externally.
1278}
1279
1280/// Given that at some point we emitted a reference to one or more
1281/// vtables, and that we are now at the end of the translation unit,
1282/// decide whether we should emit them.
1283void CodeGenModule::EmitDeferredVTables() {
1284#ifndef NDEBUG
1285 // Remember the size of DeferredVTables, because we're going to assume
1286 // that this entire operation doesn't modify it.
1287 size_t savedSize = DeferredVTables.size();
1288#endif
1289
1290 for (const CXXRecordDecl *RD : DeferredVTables)
1292 VTables.GenerateClassData(RD);
1293 else if (shouldOpportunisticallyEmitVTables())
1294 OpportunisticVTables.push_back(RD);
1295
1296 assert(savedSize == DeferredVTables.size() &&
1297 "deferred extra vtables during vtable emission?");
1298 DeferredVTables.clear();
1299}
1300
1302 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>() ||
1303 RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1304 return true;
1305
1306 if (!getCodeGenOpts().LTOVisibilityPublicStd)
1307 return false;
1308
1309 const DeclContext *DC = RD;
1310 while (true) {
1311 auto *D = cast<Decl>(DC);
1312 DC = DC->getParent();
1314 if (auto *ND = dyn_cast<NamespaceDecl>(D))
1315 if (const IdentifierInfo *II = ND->getIdentifier())
1316 if (II->isStr("std") || II->isStr("stdext"))
1317 return true;
1318 break;
1319 }
1320 }
1321
1322 return false;
1323}
1324
1328 return true;
1329
1330 if (!getTriple().isOSBinFormatCOFF() &&
1332 return false;
1333
1334 return !AlwaysHasLTOVisibilityPublic(RD);
1335}
1336
1337llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
1338 const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1339 // If we have already visited this RD (which means this is a recursive call
1340 // since the initial call should have an empty Visited set), return the max
1341 // visibility. The recursive calls below compute the min between the result
1342 // of the recursive call and the current TypeVis, so returning the max here
1343 // ensures that it will have no effect on the current TypeVis.
1344 if (!Visited.insert(RD).second)
1345 return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1346
1348 llvm::GlobalObject::VCallVisibility TypeVis;
1350 TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1351 else if (HasHiddenLTOVisibility(RD))
1352 TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1353 else
1354 TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1355
1356 for (const auto &B : RD->bases())
1357 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1358 TypeVis = std::min(
1359 TypeVis,
1360 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1361
1362 for (const auto &B : RD->vbases())
1363 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1364 TypeVis = std::min(
1365 TypeVis,
1366 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1367
1368 return TypeVis;
1369}
1370
1372 llvm::GlobalVariable *VTable,
1373 const VTableLayout &VTLayout) {
1374 // Emit type metadata on vtables with LTO or IR instrumentation or
1375 // speculative devirtualization.
1376 // In IR instrumentation, the type metadata is used to find out vtable
1377 // definitions (for type profiling) among all global variables.
1378 if (!getCodeGenOpts().LTOUnit && !getCodeGenOpts().hasProfileIRInstr() &&
1379 !getCodeGenOpts().DevirtualizeSpeculatively)
1380 return;
1381
1383
1384 struct AddressPoint {
1385 const CXXRecordDecl *Base;
1386 size_t Offset;
1387 std::string TypeName;
1388 bool operator<(const AddressPoint &RHS) const {
1389 int D = TypeName.compare(RHS.TypeName);
1390 return D < 0 || (D == 0 && Offset < RHS.Offset);
1391 }
1392 };
1393 std::vector<AddressPoint> AddressPoints;
1394 for (auto &&AP : VTLayout.getAddressPoints()) {
1395 AddressPoint N{AP.first.getBase(),
1396 VTLayout.getVTableOffset(AP.second.VTableIndex) +
1397 AP.second.AddressPointIndex,
1398 {}};
1399 llvm::raw_string_ostream Stream(N.TypeName);
1402 AddressPoints.push_back(std::move(N));
1403 }
1404
1405 // Sort the address points for determinism.
1406 llvm::sort(AddressPoints);
1407
1409 for (auto AP : AddressPoints) {
1410 // Create type metadata for the address point.
1411 AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
1412
1413 // The class associated with each address point could also potentially be
1414 // used for indirect calls via a member function pointer, so we need to
1415 // annotate the address of each function pointer with the appropriate member
1416 // function pointer type.
1417 for (unsigned I = 0; I != Comps.size(); ++I) {
1419 continue;
1421 Context.getMemberPointerType(Comps[I].getFunctionDecl()->getType(),
1422 /*Qualifier=*/std::nullopt, AP.Base));
1423 VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
1424 }
1425 }
1426
1427 if (getCodeGenOpts().VirtualFunctionElimination ||
1428 getCodeGenOpts().WholeProgramVTables) {
1429 llvm::DenseSet<const CXXRecordDecl *> Visited;
1430 llvm::GlobalObject::VCallVisibility TypeVis =
1431 GetVCallVisibilityLevel(RD, Visited);
1432 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1433 VTable->setVCallVisibilityMetadata(TypeVis);
1434 }
1435}
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
Definition CGVTables.cpp:76
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk, llvm::Function *ThunkFn, bool ForVTable, GlobalDecl GD)
Definition CGVTables.cpp:47
static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD, bool IsUnprototyped, bool ForVTable)
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 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:2129
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2809
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2279
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:2050
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:360
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:4302
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:5249
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:656
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:4417
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3199
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:3246
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
QualType getReturnType() const
Definition TypeBase.h:4805
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:8376
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:8891
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:9178
bool isReferenceType() const
Definition TypeBase.h:8553
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:1910
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
const FunctionProtoType * T
@ 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