CGVTables.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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. #include "CGCXXABI.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/RecordLayout.h"
  17. #include "clang/Basic/CodeGenOptions.h"
  18. #include "clang/CodeGen/CGFunctionInfo.h"
  19. #include "clang/CodeGen/ConstantInitBuilder.h"
  20. #include "llvm/IR/IntrinsicInst.h"
  21. #include "llvm/Support/Format.h"
  22. #include "llvm/Transforms/Utils/Cloning.h"
  23. #include <algorithm>
  24. #include <cstdio>
  25. using namespace clang;
  26. using namespace CodeGen;
  27. CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
  28. : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
  29. llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
  30. GlobalDecl GD) {
  31. return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
  32. /*DontDefer=*/true, /*IsThunk=*/true);
  33. }
  34. static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
  35. llvm::Function *ThunkFn, bool ForVTable,
  36. GlobalDecl GD) {
  37. CGM.setFunctionLinkage(GD, ThunkFn);
  38. CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
  39. !Thunk.Return.isEmpty());
  40. // Set the right visibility.
  41. CGM.setGVProperties(ThunkFn, GD);
  42. if (!CGM.getCXXABI().exportThunk()) {
  43. ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  44. ThunkFn->setDSOLocal(true);
  45. }
  46. if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
  47. ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
  48. }
  49. #ifndef NDEBUG
  50. static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
  51. const ABIArgInfo &infoR, CanQualType typeR) {
  52. return (infoL.getKind() == infoR.getKind() &&
  53. (typeL == typeR ||
  54. (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
  55. (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
  56. }
  57. #endif
  58. static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
  59. QualType ResultType, RValue RV,
  60. const ThunkInfo &Thunk) {
  61. // Emit the return adjustment.
  62. bool NullCheckValue = !ResultType->isReferenceType();
  63. llvm::BasicBlock *AdjustNull = nullptr;
  64. llvm::BasicBlock *AdjustNotNull = nullptr;
  65. llvm::BasicBlock *AdjustEnd = nullptr;
  66. llvm::Value *ReturnValue = RV.getScalarVal();
  67. if (NullCheckValue) {
  68. AdjustNull = CGF.createBasicBlock("adjust.null");
  69. AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
  70. AdjustEnd = CGF.createBasicBlock("adjust.end");
  71. llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
  72. CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
  73. CGF.EmitBlock(AdjustNotNull);
  74. }
  75. auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
  76. auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
  77. ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
  78. Address(ReturnValue, ClassAlign),
  79. Thunk.Return);
  80. if (NullCheckValue) {
  81. CGF.Builder.CreateBr(AdjustEnd);
  82. CGF.EmitBlock(AdjustNull);
  83. CGF.Builder.CreateBr(AdjustEnd);
  84. CGF.EmitBlock(AdjustEnd);
  85. llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
  86. PHI->addIncoming(ReturnValue, AdjustNotNull);
  87. PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
  88. AdjustNull);
  89. ReturnValue = PHI;
  90. }
  91. return RValue::get(ReturnValue);
  92. }
  93. /// This function clones a function's DISubprogram node and enters it into
  94. /// a value map with the intent that the map can be utilized by the cloner
  95. /// to short-circuit Metadata node mapping.
  96. /// Furthermore, the function resolves any DILocalVariable nodes referenced
  97. /// by dbg.value intrinsics so they can be properly mapped during cloning.
  98. static void resolveTopLevelMetadata(llvm::Function *Fn,
  99. llvm::ValueToValueMapTy &VMap) {
  100. // Clone the DISubprogram node and put it into the Value map.
  101. auto *DIS = Fn->getSubprogram();
  102. if (!DIS)
  103. return;
  104. auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
  105. VMap.MD()[DIS].reset(NewDIS);
  106. // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
  107. // they are referencing.
  108. for (auto &BB : Fn->getBasicBlockList()) {
  109. for (auto &I : BB) {
  110. if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
  111. auto *DILocal = DII->getVariable();
  112. if (!DILocal->isResolved())
  113. DILocal->resolve();
  114. }
  115. }
  116. }
  117. }
  118. // This function does roughly the same thing as GenerateThunk, but in a
  119. // very different way, so that va_start and va_end work correctly.
  120. // FIXME: This function assumes "this" is the first non-sret LLVM argument of
  121. // a function, and that there is an alloca built in the entry block
  122. // for all accesses to "this".
  123. // FIXME: This function assumes there is only one "ret" statement per function.
  124. // FIXME: Cloning isn't correct in the presence of indirect goto!
  125. // FIXME: This implementation of thunks bloats codesize by duplicating the
  126. // function definition. There are alternatives:
  127. // 1. Add some sort of stub support to LLVM for cases where we can
  128. // do a this adjustment, then a sibcall.
  129. // 2. We could transform the definition to take a va_list instead of an
  130. // actual variable argument list, then have the thunks (including a
  131. // no-op thunk for the regular definition) call va_start/va_end.
  132. // There's a bit of per-call overhead for this solution, but it's
  133. // better for codesize if the definition is long.
  134. llvm::Function *
  135. CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
  136. const CGFunctionInfo &FnInfo,
  137. GlobalDecl GD, const ThunkInfo &Thunk) {
  138. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  139. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  140. QualType ResultType = FPT->getReturnType();
  141. // Get the original function
  142. assert(FnInfo.isVariadic());
  143. llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
  144. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  145. llvm::Function *BaseFn = cast<llvm::Function>(Callee);
  146. // Cloning can't work if we don't have a definition. The Microsoft ABI may
  147. // require thunks when a definition is not available. Emit an error in these
  148. // cases.
  149. if (!MD->isDefined()) {
  150. CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
  151. return Fn;
  152. }
  153. assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
  154. // Clone to thunk.
  155. llvm::ValueToValueMapTy VMap;
  156. // We are cloning a function while some Metadata nodes are still unresolved.
  157. // Ensure that the value mapper does not encounter any of them.
  158. resolveTopLevelMetadata(BaseFn, VMap);
  159. llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
  160. Fn->replaceAllUsesWith(NewFn);
  161. NewFn->takeName(Fn);
  162. Fn->eraseFromParent();
  163. Fn = NewFn;
  164. // "Initialize" CGF (minimally).
  165. CurFn = Fn;
  166. // Get the "this" value
  167. llvm::Function::arg_iterator AI = Fn->arg_begin();
  168. if (CGM.ReturnTypeUsesSRet(FnInfo))
  169. ++AI;
  170. // Find the first store of "this", which will be to the alloca associated
  171. // with "this".
  172. Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
  173. llvm::BasicBlock *EntryBB = &Fn->front();
  174. llvm::BasicBlock::iterator ThisStore =
  175. std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
  176. return isa<llvm::StoreInst>(I) &&
  177. I.getOperand(0) == ThisPtr.getPointer();
  178. });
  179. assert(ThisStore != EntryBB->end() &&
  180. "Store of this should be in entry block?");
  181. // Adjust "this", if necessary.
  182. Builder.SetInsertPoint(&*ThisStore);
  183. llvm::Value *AdjustedThisPtr =
  184. CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
  185. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
  186. ThisStore->getOperand(0)->getType());
  187. ThisStore->setOperand(0, AdjustedThisPtr);
  188. if (!Thunk.Return.isEmpty()) {
  189. // Fix up the returned value, if necessary.
  190. for (llvm::BasicBlock &BB : *Fn) {
  191. llvm::Instruction *T = BB.getTerminator();
  192. if (isa<llvm::ReturnInst>(T)) {
  193. RValue RV = RValue::get(T->getOperand(0));
  194. T->eraseFromParent();
  195. Builder.SetInsertPoint(&BB);
  196. RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
  197. Builder.CreateRet(RV.getScalarVal());
  198. break;
  199. }
  200. }
  201. }
  202. return Fn;
  203. }
  204. void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
  205. const CGFunctionInfo &FnInfo,
  206. bool IsUnprototyped) {
  207. assert(!CurGD.getDecl() && "CurGD was already set!");
  208. CurGD = GD;
  209. CurFuncIsThunk = true;
  210. // Build FunctionArgs.
  211. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  212. QualType ThisType = MD->getThisType();
  213. QualType ResultType;
  214. if (IsUnprototyped)
  215. ResultType = CGM.getContext().VoidTy;
  216. else if (CGM.getCXXABI().HasThisReturn(GD))
  217. ResultType = ThisType;
  218. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  219. ResultType = CGM.getContext().VoidPtrTy;
  220. else
  221. ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
  222. FunctionArgList FunctionArgs;
  223. // Create the implicit 'this' parameter declaration.
  224. CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
  225. // Add the rest of the parameters, if we have a prototype to work with.
  226. if (!IsUnprototyped) {
  227. FunctionArgs.append(MD->param_begin(), MD->param_end());
  228. if (isa<CXXDestructorDecl>(MD))
  229. CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
  230. FunctionArgs);
  231. }
  232. // Start defining the function.
  233. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  234. StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
  235. MD->getLocation());
  236. // Create a scope with an artificial location for the body of this function.
  237. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  238. // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
  239. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  240. CXXThisValue = CXXABIThisValue;
  241. CurCodeDecl = MD;
  242. CurFuncDecl = MD;
  243. }
  244. void CodeGenFunction::FinishThunk() {
  245. // Clear these to restore the invariants expected by
  246. // StartFunction/FinishFunction.
  247. CurCodeDecl = nullptr;
  248. CurFuncDecl = nullptr;
  249. FinishFunction();
  250. }
  251. void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
  252. const ThunkInfo *Thunk,
  253. bool IsUnprototyped) {
  254. assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
  255. "Please use a new CGF for this thunk");
  256. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
  257. // Adjust the 'this' pointer if necessary
  258. llvm::Value *AdjustedThisPtr =
  259. Thunk ? CGM.getCXXABI().performThisAdjustment(
  260. *this, LoadCXXThisAddress(), Thunk->This)
  261. : LoadCXXThis();
  262. // If perfect forwarding is required a variadic method, a method using
  263. // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
  264. // thunk requires a return adjustment, since that is impossible with musttail.
  265. if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
  266. if (Thunk && !Thunk->Return.isEmpty()) {
  267. if (IsUnprototyped)
  268. CGM.ErrorUnsupported(
  269. MD, "return-adjusting thunk with incomplete parameter type");
  270. else if (CurFnInfo->isVariadic())
  271. llvm_unreachable("shouldn't try to emit musttail return-adjusting "
  272. "thunks for variadic functions");
  273. else
  274. CGM.ErrorUnsupported(
  275. MD, "non-trivial argument copy for return-adjusting thunk");
  276. }
  277. EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
  278. return;
  279. }
  280. // Start building CallArgs.
  281. CallArgList CallArgs;
  282. QualType ThisType = MD->getThisType();
  283. CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
  284. if (isa<CXXDestructorDecl>(MD))
  285. CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
  286. #ifndef NDEBUG
  287. unsigned PrefixArgs = CallArgs.size() - 1;
  288. #endif
  289. // Add the rest of the arguments.
  290. for (const ParmVarDecl *PD : MD->parameters())
  291. EmitDelegateCallArg(CallArgs, PD, SourceLocation());
  292. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  293. #ifndef NDEBUG
  294. const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
  295. CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
  296. assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
  297. CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
  298. CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
  299. assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
  300. similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
  301. CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
  302. assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
  303. for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
  304. assert(similar(CallFnInfo.arg_begin()[i].info,
  305. CallFnInfo.arg_begin()[i].type,
  306. CurFnInfo->arg_begin()[i].info,
  307. CurFnInfo->arg_begin()[i].type));
  308. #endif
  309. // Determine whether we have a return value slot to use.
  310. QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
  311. ? ThisType
  312. : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
  313. ? CGM.getContext().VoidPtrTy
  314. : FPT->getReturnType();
  315. ReturnValueSlot Slot;
  316. if (!ResultType->isVoidType() &&
  317. CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
  318. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  319. // Now emit our call.
  320. llvm::CallBase *CallOrInvoke;
  321. RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
  322. CallArgs, &CallOrInvoke);
  323. // Consider return adjustment if we have ThunkInfo.
  324. if (Thunk && !Thunk->Return.isEmpty())
  325. RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
  326. else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
  327. Call->setTailCallKind(llvm::CallInst::TCK_Tail);
  328. // Emit return.
  329. if (!ResultType->isVoidType() && Slot.isNull())
  330. CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
  331. // Disable the final ARC autorelease.
  332. AutoreleaseResult = false;
  333. FinishThunk();
  334. }
  335. void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
  336. llvm::Value *AdjustedThisPtr,
  337. llvm::FunctionCallee Callee) {
  338. // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
  339. // to translate AST arguments into LLVM IR arguments. For thunks, we know
  340. // that the caller prototype more or less matches the callee prototype with
  341. // the exception of 'this'.
  342. SmallVector<llvm::Value *, 8> Args;
  343. for (llvm::Argument &A : CurFn->args())
  344. Args.push_back(&A);
  345. // Set the adjusted 'this' pointer.
  346. const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
  347. if (ThisAI.isDirect()) {
  348. const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
  349. int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
  350. llvm::Type *ThisType = Args[ThisArgNo]->getType();
  351. if (ThisType != AdjustedThisPtr->getType())
  352. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
  353. Args[ThisArgNo] = AdjustedThisPtr;
  354. } else {
  355. assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
  356. Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
  357. llvm::Type *ThisType = ThisAddr.getElementType();
  358. if (ThisType != AdjustedThisPtr->getType())
  359. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
  360. Builder.CreateStore(AdjustedThisPtr, ThisAddr);
  361. }
  362. // Emit the musttail call manually. Even if the prologue pushed cleanups, we
  363. // don't actually want to run them.
  364. llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
  365. Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
  366. // Apply the standard set of call attributes.
  367. unsigned CallingConv;
  368. llvm::AttributeList Attrs;
  369. CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
  370. Attrs, CallingConv, /*AttrOnCallSite=*/true);
  371. Call->setAttributes(Attrs);
  372. Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  373. if (Call->getType()->isVoidTy())
  374. Builder.CreateRetVoid();
  375. else
  376. Builder.CreateRet(Call);
  377. // Finish the function to maintain CodeGenFunction invariants.
  378. // FIXME: Don't emit unreachable code.
  379. EmitBlock(createBasicBlock());
  380. FinishFunction();
  381. }
  382. void CodeGenFunction::generateThunk(llvm::Function *Fn,
  383. const CGFunctionInfo &FnInfo, GlobalDecl GD,
  384. const ThunkInfo &Thunk,
  385. bool IsUnprototyped) {
  386. StartThunk(Fn, GD, FnInfo, IsUnprototyped);
  387. // Create a scope with an artificial location for the body of this function.
  388. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  389. // Get our callee. Use a placeholder type if this method is unprototyped so
  390. // that CodeGenModule doesn't try to set attributes.
  391. llvm::Type *Ty;
  392. if (IsUnprototyped)
  393. Ty = llvm::StructType::get(getLLVMContext());
  394. else
  395. Ty = CGM.getTypes().GetFunctionType(FnInfo);
  396. llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  397. // Fix up the function type for an unprototyped musttail call.
  398. if (IsUnprototyped)
  399. Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
  400. // Make the call and return the result.
  401. EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
  402. &Thunk, IsUnprototyped);
  403. }
  404. static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
  405. bool IsUnprototyped, bool ForVTable) {
  406. // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
  407. // provide thunks for us.
  408. if (CGM.getTarget().getCXXABI().isMicrosoft())
  409. return true;
  410. // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
  411. // definitions of the main method. Therefore, emitting thunks with the vtable
  412. // is purely an optimization. Emit the thunk if optimizations are enabled and
  413. // all of the parameter types are complete.
  414. if (ForVTable)
  415. return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
  416. // Always emit thunks along with the method definition.
  417. return true;
  418. }
  419. llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
  420. const ThunkInfo &TI,
  421. bool ForVTable) {
  422. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  423. // First, get a declaration. Compute the mangled name. Don't worry about
  424. // getting the function prototype right, since we may only need this
  425. // declaration to fill in a vtable slot.
  426. SmallString<256> Name;
  427. MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
  428. llvm::raw_svector_ostream Out(Name);
  429. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
  430. MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
  431. else
  432. MCtx.mangleThunk(MD, TI, Out);
  433. llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
  434. llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
  435. // If we don't need to emit a definition, return this declaration as is.
  436. bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
  437. MD->getType()->castAs<FunctionType>());
  438. if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
  439. return Thunk;
  440. // Arrange a function prototype appropriate for a function definition. In some
  441. // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
  442. const CGFunctionInfo &FnInfo =
  443. IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
  444. : CGM.getTypes().arrangeGlobalDeclaration(GD);
  445. llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
  446. // If the type of the underlying GlobalValue is wrong, we'll have to replace
  447. // it. It should be a declaration.
  448. llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
  449. if (ThunkFn->getFunctionType() != ThunkFnTy) {
  450. llvm::GlobalValue *OldThunkFn = ThunkFn;
  451. assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
  452. // Remove the name from the old thunk function and get a new thunk.
  453. OldThunkFn->setName(StringRef());
  454. ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
  455. Name.str(), &CGM.getModule());
  456. CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
  457. // If needed, replace the old thunk with a bitcast.
  458. if (!OldThunkFn->use_empty()) {
  459. llvm::Constant *NewPtrForOldDecl =
  460. llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
  461. OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
  462. }
  463. // Remove the old thunk.
  464. OldThunkFn->eraseFromParent();
  465. }
  466. bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
  467. bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
  468. if (!ThunkFn->isDeclaration()) {
  469. if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
  470. // There is already a thunk emitted for this function, do nothing.
  471. return ThunkFn;
  472. }
  473. setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
  474. return ThunkFn;
  475. }
  476. // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
  477. // that the return type is meaningless. These thunks can be used to call
  478. // functions with differing return types, and the caller is required to cast
  479. // the prototype appropriately to extract the correct value.
  480. if (IsUnprototyped)
  481. ThunkFn->addFnAttr("thunk");
  482. CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
  483. // Thunks for variadic methods are special because in general variadic
  484. // arguments cannot be perferctly forwarded. In the general case, clang
  485. // implements such thunks by cloning the original function body. However, for
  486. // thunks with no return adjustment on targets that support musttail, we can
  487. // use musttail to perfectly forward the variadic arguments.
  488. bool ShouldCloneVarArgs = false;
  489. if (!IsUnprototyped && ThunkFn->isVarArg()) {
  490. ShouldCloneVarArgs = true;
  491. if (TI.Return.isEmpty()) {
  492. switch (CGM.getTriple().getArch()) {
  493. case llvm::Triple::x86_64:
  494. case llvm::Triple::x86:
  495. case llvm::Triple::aarch64:
  496. ShouldCloneVarArgs = false;
  497. break;
  498. default:
  499. break;
  500. }
  501. }
  502. }
  503. if (ShouldCloneVarArgs) {
  504. if (UseAvailableExternallyLinkage)
  505. return ThunkFn;
  506. ThunkFn =
  507. CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
  508. } else {
  509. // Normal thunk body generation.
  510. CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
  511. }
  512. setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
  513. return ThunkFn;
  514. }
  515. void CodeGenVTables::EmitThunks(GlobalDecl GD) {
  516. const CXXMethodDecl *MD =
  517. cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
  518. // We don't need to generate thunks for the base destructor.
  519. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  520. return;
  521. const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
  522. VTContext->getThunkInfo(GD);
  523. if (!ThunkInfoVector)
  524. return;
  525. for (const ThunkInfo& Thunk : *ThunkInfoVector)
  526. maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
  527. }
  528. void CodeGenVTables::addVTableComponent(
  529. ConstantArrayBuilder &builder, const VTableLayout &layout,
  530. unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
  531. auto &component = layout.vtable_components()[idx];
  532. auto addOffsetConstant = [&](CharUnits offset) {
  533. builder.add(llvm::ConstantExpr::getIntToPtr(
  534. llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
  535. CGM.Int8PtrTy));
  536. };
  537. switch (component.getKind()) {
  538. case VTableComponent::CK_VCallOffset:
  539. return addOffsetConstant(component.getVCallOffset());
  540. case VTableComponent::CK_VBaseOffset:
  541. return addOffsetConstant(component.getVBaseOffset());
  542. case VTableComponent::CK_OffsetToTop:
  543. return addOffsetConstant(component.getOffsetToTop());
  544. case VTableComponent::CK_RTTI:
  545. return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
  546. case VTableComponent::CK_FunctionPointer:
  547. case VTableComponent::CK_CompleteDtorPointer:
  548. case VTableComponent::CK_DeletingDtorPointer: {
  549. GlobalDecl GD;
  550. // Get the right global decl.
  551. switch (component.getKind()) {
  552. default:
  553. llvm_unreachable("Unexpected vtable component kind");
  554. case VTableComponent::CK_FunctionPointer:
  555. GD = component.getFunctionDecl();
  556. break;
  557. case VTableComponent::CK_CompleteDtorPointer:
  558. GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
  559. break;
  560. case VTableComponent::CK_DeletingDtorPointer:
  561. GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
  562. break;
  563. }
  564. if (CGM.getLangOpts().CUDA) {
  565. // Emit NULL for methods we can't codegen on this
  566. // side. Otherwise we'd end up with vtable with unresolved
  567. // references.
  568. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  569. // OK on device side: functions w/ __device__ attribute
  570. // OK on host side: anything except __device__-only functions.
  571. bool CanEmitMethod =
  572. CGM.getLangOpts().CUDAIsDevice
  573. ? MD->hasAttr<CUDADeviceAttr>()
  574. : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
  575. if (!CanEmitMethod)
  576. return builder.addNullPointer(CGM.Int8PtrTy);
  577. // Method is acceptable, continue processing as usual.
  578. }
  579. auto getSpecialVirtualFn = [&](StringRef name) {
  580. llvm::FunctionType *fnTy =
  581. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  582. llvm::Constant *fn = cast<llvm::Constant>(
  583. CGM.CreateRuntimeFunction(fnTy, name).getCallee());
  584. if (auto f = dyn_cast<llvm::Function>(fn))
  585. f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  586. return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
  587. };
  588. llvm::Constant *fnPtr;
  589. // Pure virtual member functions.
  590. if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
  591. if (!PureVirtualFn)
  592. PureVirtualFn =
  593. getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
  594. fnPtr = PureVirtualFn;
  595. // Deleted virtual member functions.
  596. } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
  597. if (!DeletedVirtualFn)
  598. DeletedVirtualFn =
  599. getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
  600. fnPtr = DeletedVirtualFn;
  601. // Thunks.
  602. } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
  603. layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
  604. auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
  605. nextVTableThunkIndex++;
  606. fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
  607. // Otherwise we can use the method definition directly.
  608. } else {
  609. llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
  610. fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
  611. }
  612. fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
  613. builder.add(fnPtr);
  614. return;
  615. }
  616. case VTableComponent::CK_UnusedFunctionPointer:
  617. return builder.addNullPointer(CGM.Int8PtrTy);
  618. }
  619. llvm_unreachable("Unexpected vtable component kind");
  620. }
  621. llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
  622. SmallVector<llvm::Type *, 4> tys;
  623. for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
  624. tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
  625. }
  626. return llvm::StructType::get(CGM.getLLVMContext(), tys);
  627. }
  628. void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
  629. const VTableLayout &layout,
  630. llvm::Constant *rtti) {
  631. unsigned nextVTableThunkIndex = 0;
  632. for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
  633. auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
  634. size_t thisIndex = layout.getVTableOffset(i);
  635. size_t nextIndex = thisIndex + layout.getVTableSize(i);
  636. for (unsigned i = thisIndex; i != nextIndex; ++i) {
  637. addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
  638. }
  639. vtableElem.finishAndAddTo(builder);
  640. }
  641. }
  642. llvm::GlobalVariable *
  643. CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
  644. const BaseSubobject &Base,
  645. bool BaseIsVirtual,
  646. llvm::GlobalVariable::LinkageTypes Linkage,
  647. VTableAddressPointsMapTy& AddressPoints) {
  648. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  649. DI->completeClassData(Base.getBase());
  650. std::unique_ptr<VTableLayout> VTLayout(
  651. getItaniumVTableContext().createConstructionVTableLayout(
  652. Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
  653. // Add the address points.
  654. AddressPoints = VTLayout->getAddressPoints();
  655. // Get the mangled construction vtable name.
  656. SmallString<256> OutName;
  657. llvm::raw_svector_ostream Out(OutName);
  658. cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
  659. .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
  660. Base.getBase(), Out);
  661. StringRef Name = OutName.str();
  662. llvm::Type *VTType = getVTableType(*VTLayout);
  663. // Construction vtable symbols are not part of the Itanium ABI, so we cannot
  664. // guarantee that they actually will be available externally. Instead, when
  665. // emitting an available_externally VTT, we provide references to an internal
  666. // linkage construction vtable. The ABI only requires complete-object vtables
  667. // to be the same for all instances of a type, not construction vtables.
  668. if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
  669. Linkage = llvm::GlobalVariable::InternalLinkage;
  670. unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
  671. // Create the variable that will hold the construction vtable.
  672. llvm::GlobalVariable *VTable =
  673. CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
  674. // V-tables are always unnamed_addr.
  675. VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  676. llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
  677. CGM.getContext().getTagDeclType(Base.getBase()));
  678. // Create and set the initializer.
  679. ConstantInitBuilder builder(CGM);
  680. auto components = builder.beginStruct();
  681. createVTableInitializer(components, *VTLayout, RTTI);
  682. components.finishAndSetAsInitializer(VTable);
  683. // Set properties only after the initializer has been set to ensure that the
  684. // GV is treated as definition and not declaration.
  685. assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
  686. CGM.setGVProperties(VTable, RD);
  687. CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
  688. return VTable;
  689. }
  690. static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
  691. const CXXRecordDecl *RD) {
  692. return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  693. CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
  694. }
  695. /// Compute the required linkage of the vtable for the given class.
  696. ///
  697. /// Note that we only call this at the end of the translation unit.
  698. llvm::GlobalVariable::LinkageTypes
  699. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  700. if (!RD->isExternallyVisible())
  701. return llvm::GlobalVariable::InternalLinkage;
  702. // We're at the end of the translation unit, so the current key
  703. // function is fully correct.
  704. const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
  705. if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
  706. // If this class has a key function, use that to determine the
  707. // linkage of the vtable.
  708. const FunctionDecl *def = nullptr;
  709. if (keyFunction->hasBody(def))
  710. keyFunction = cast<CXXMethodDecl>(def);
  711. switch (keyFunction->getTemplateSpecializationKind()) {
  712. case TSK_Undeclared:
  713. case TSK_ExplicitSpecialization:
  714. assert((def || CodeGenOpts.OptimizationLevel > 0 ||
  715. CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
  716. "Shouldn't query vtable linkage without key function, "
  717. "optimizations, or debug info");
  718. if (!def && CodeGenOpts.OptimizationLevel > 0)
  719. return llvm::GlobalVariable::AvailableExternallyLinkage;
  720. if (keyFunction->isInlined())
  721. return !Context.getLangOpts().AppleKext ?
  722. llvm::GlobalVariable::LinkOnceODRLinkage :
  723. llvm::Function::InternalLinkage;
  724. return llvm::GlobalVariable::ExternalLinkage;
  725. case TSK_ImplicitInstantiation:
  726. return !Context.getLangOpts().AppleKext ?
  727. llvm::GlobalVariable::LinkOnceODRLinkage :
  728. llvm::Function::InternalLinkage;
  729. case TSK_ExplicitInstantiationDefinition:
  730. return !Context.getLangOpts().AppleKext ?
  731. llvm::GlobalVariable::WeakODRLinkage :
  732. llvm::Function::InternalLinkage;
  733. case TSK_ExplicitInstantiationDeclaration:
  734. llvm_unreachable("Should not have been asked to emit this");
  735. }
  736. }
  737. // -fapple-kext mode does not support weak linkage, so we must use
  738. // internal linkage.
  739. if (Context.getLangOpts().AppleKext)
  740. return llvm::Function::InternalLinkage;
  741. llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
  742. llvm::GlobalValue::LinkOnceODRLinkage;
  743. llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
  744. llvm::GlobalValue::WeakODRLinkage;
  745. if (RD->hasAttr<DLLExportAttr>()) {
  746. // Cannot discard exported vtables.
  747. DiscardableODRLinkage = NonDiscardableODRLinkage;
  748. } else if (RD->hasAttr<DLLImportAttr>()) {
  749. // Imported vtables are available externally.
  750. DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
  751. NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
  752. }
  753. switch (RD->getTemplateSpecializationKind()) {
  754. case TSK_Undeclared:
  755. case TSK_ExplicitSpecialization:
  756. case TSK_ImplicitInstantiation:
  757. return DiscardableODRLinkage;
  758. case TSK_ExplicitInstantiationDeclaration:
  759. // Explicit instantiations in MSVC do not provide vtables, so we must emit
  760. // our own.
  761. if (getTarget().getCXXABI().isMicrosoft())
  762. return DiscardableODRLinkage;
  763. return shouldEmitAvailableExternallyVTable(*this, RD)
  764. ? llvm::GlobalVariable::AvailableExternallyLinkage
  765. : llvm::GlobalVariable::ExternalLinkage;
  766. case TSK_ExplicitInstantiationDefinition:
  767. return NonDiscardableODRLinkage;
  768. }
  769. llvm_unreachable("Invalid TemplateSpecializationKind!");
  770. }
  771. /// This is a callback from Sema to tell us that a particular vtable is
  772. /// required to be emitted in this translation unit.
  773. ///
  774. /// This is only called for vtables that _must_ be emitted (mainly due to key
  775. /// functions). For weak vtables, CodeGen tracks when they are needed and
  776. /// emits them as-needed.
  777. void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
  778. VTables.GenerateClassData(theClass);
  779. }
  780. void
  781. CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
  782. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  783. DI->completeClassData(RD);
  784. if (RD->getNumVBases())
  785. CGM.getCXXABI().emitVirtualInheritanceTables(RD);
  786. CGM.getCXXABI().emitVTableDefinitions(*this, RD);
  787. }
  788. /// At this point in the translation unit, does it appear that can we
  789. /// rely on the vtable being defined elsewhere in the program?
  790. ///
  791. /// The response is really only definitive when called at the end of
  792. /// the translation unit.
  793. ///
  794. /// The only semantic restriction here is that the object file should
  795. /// not contain a vtable definition when that vtable is defined
  796. /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
  797. /// vtables when unnecessary.
  798. bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
  799. assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
  800. // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
  801. // emit them even if there is an explicit template instantiation.
  802. if (CGM.getTarget().getCXXABI().isMicrosoft())
  803. return false;
  804. // If we have an explicit instantiation declaration (and not a
  805. // definition), the vtable is defined elsewhere.
  806. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  807. if (TSK == TSK_ExplicitInstantiationDeclaration)
  808. return true;
  809. // Otherwise, if the class is an instantiated template, the
  810. // vtable must be defined here.
  811. if (TSK == TSK_ImplicitInstantiation ||
  812. TSK == TSK_ExplicitInstantiationDefinition)
  813. return false;
  814. // Otherwise, if the class doesn't have a key function (possibly
  815. // anymore), the vtable must be defined here.
  816. const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
  817. if (!keyFunction)
  818. return false;
  819. // Otherwise, if we don't have a definition of the key function, the
  820. // vtable must be defined somewhere else.
  821. return !keyFunction->hasBody();
  822. }
  823. /// Given that we're currently at the end of the translation unit, and
  824. /// we've emitted a reference to the vtable for this class, should
  825. /// we define that vtable?
  826. static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
  827. const CXXRecordDecl *RD) {
  828. // If vtable is internal then it has to be done.
  829. if (!CGM.getVTables().isVTableExternal(RD))
  830. return true;
  831. // If it's external then maybe we will need it as available_externally.
  832. return shouldEmitAvailableExternallyVTable(CGM, RD);
  833. }
  834. /// Given that at some point we emitted a reference to one or more
  835. /// vtables, and that we are now at the end of the translation unit,
  836. /// decide whether we should emit them.
  837. void CodeGenModule::EmitDeferredVTables() {
  838. #ifndef NDEBUG
  839. // Remember the size of DeferredVTables, because we're going to assume
  840. // that this entire operation doesn't modify it.
  841. size_t savedSize = DeferredVTables.size();
  842. #endif
  843. for (const CXXRecordDecl *RD : DeferredVTables)
  844. if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
  845. VTables.GenerateClassData(RD);
  846. else if (shouldOpportunisticallyEmitVTables())
  847. OpportunisticVTables.push_back(RD);
  848. assert(savedSize == DeferredVTables.size() &&
  849. "deferred extra vtables during vtable emission?");
  850. DeferredVTables.clear();
  851. }
  852. bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
  853. LinkageInfo LV = RD->getLinkageAndVisibility();
  854. if (!isExternallyVisible(LV.getLinkage()))
  855. return true;
  856. if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
  857. return false;
  858. if (getTriple().isOSBinFormatCOFF()) {
  859. if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
  860. return false;
  861. } else {
  862. if (LV.getVisibility() != HiddenVisibility)
  863. return false;
  864. }
  865. if (getCodeGenOpts().LTOVisibilityPublicStd) {
  866. const DeclContext *DC = RD;
  867. while (1) {
  868. auto *D = cast<Decl>(DC);
  869. DC = DC->getParent();
  870. if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
  871. if (auto *ND = dyn_cast<NamespaceDecl>(D))
  872. if (const IdentifierInfo *II = ND->getIdentifier())
  873. if (II->isStr("std") || II->isStr("stdext"))
  874. return false;
  875. break;
  876. }
  877. }
  878. }
  879. return true;
  880. }
  881. void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
  882. const VTableLayout &VTLayout) {
  883. if (!getCodeGenOpts().LTOUnit)
  884. return;
  885. CharUnits PointerWidth =
  886. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  887. typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
  888. std::vector<AddressPoint> AddressPoints;
  889. for (auto &&AP : VTLayout.getAddressPoints())
  890. AddressPoints.push_back(std::make_pair(
  891. AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
  892. AP.second.AddressPointIndex));
  893. // Sort the address points for determinism.
  894. llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
  895. const AddressPoint &AP2) {
  896. if (&AP1 == &AP2)
  897. return false;
  898. std::string S1;
  899. llvm::raw_string_ostream O1(S1);
  900. getCXXABI().getMangleContext().mangleTypeName(
  901. QualType(AP1.first->getTypeForDecl(), 0), O1);
  902. O1.flush();
  903. std::string S2;
  904. llvm::raw_string_ostream O2(S2);
  905. getCXXABI().getMangleContext().mangleTypeName(
  906. QualType(AP2.first->getTypeForDecl(), 0), O2);
  907. O2.flush();
  908. if (S1 < S2)
  909. return true;
  910. if (S1 != S2)
  911. return false;
  912. return AP1.second < AP2.second;
  913. });
  914. ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
  915. for (auto AP : AddressPoints) {
  916. // Create type metadata for the address point.
  917. AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
  918. // The class associated with each address point could also potentially be
  919. // used for indirect calls via a member function pointer, so we need to
  920. // annotate the address of each function pointer with the appropriate member
  921. // function pointer type.
  922. for (unsigned I = 0; I != Comps.size(); ++I) {
  923. if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
  924. continue;
  925. llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
  926. Context.getMemberPointerType(
  927. Comps[I].getFunctionDecl()->getType(),
  928. Context.getRecordType(AP.first).getTypePtr()));
  929. VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
  930. }
  931. }
  932. }