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