CGVTables.cpp 42 KB

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