CGVTables.cpp 37 KB

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