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