CGVTables.cpp 41 KB

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