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