JumpDiagnostics.cpp revision 65d78312ce026092cb6e7b1d4d06f05e18d02aa0
1//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=// 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 file implements the JumpScopeChecker class, which is used to diagnose 11// jumps that enter a protected scope in an invalid way. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/SemaInternal.h" 16#include "clang/AST/DeclCXX.h" 17#include "clang/AST/Expr.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/StmtCXX.h" 20#include "clang/AST/StmtObjC.h" 21#include "llvm/ADT/BitVector.h" 22using namespace clang; 23 24namespace { 25 26/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps 27/// into VLA and other protected scopes. For example, this rejects: 28/// goto L; 29/// int a[n]; 30/// L: 31/// 32class JumpScopeChecker { 33 Sema &S; 34 35 /// GotoScope - This is a record that we use to keep track of all of the 36 /// scopes that are introduced by VLAs and other things that scope jumps like 37 /// gotos. This scope tree has nothing to do with the source scope tree, 38 /// because you can have multiple VLA scopes per compound statement, and most 39 /// compound statements don't introduce any scopes. 40 struct GotoScope { 41 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for 42 /// the parent scope is the function body. 43 unsigned ParentScope; 44 45 /// InDiag - The note to emit if there is a jump into this scope. 46 unsigned InDiag; 47 48 /// OutDiag - The note to emit if there is an indirect jump out 49 /// of this scope. Direct jumps always clean up their current scope 50 /// in an orderly way. 51 unsigned OutDiag; 52 53 /// Loc - Location to emit the diagnostic. 54 SourceLocation Loc; 55 56 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag, 57 SourceLocation L) 58 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {} 59 }; 60 61 SmallVector<GotoScope, 48> Scopes; 62 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes; 63 SmallVector<Stmt*, 16> Jumps; 64 65 SmallVector<IndirectGotoStmt*, 4> IndirectJumps; 66 SmallVector<LabelDecl*, 4> IndirectJumpTargets; 67public: 68 JumpScopeChecker(Stmt *Body, Sema &S); 69private: 70 void BuildScopeInformation(Decl *D, unsigned &ParentScope); 71 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl, 72 unsigned &ParentScope); 73 void BuildScopeInformation(Stmt *S, unsigned &origParentScope); 74 75 void VerifyJumps(); 76 void VerifyIndirectJumps(); 77 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes); 78 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope, 79 LabelDecl *Target, unsigned TargetScope); 80 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, 81 unsigned JumpDiag, unsigned JumpDiagWarning, 82 unsigned JumpDiagCXX98Compat); 83 84 unsigned GetDeepestCommonScope(unsigned A, unsigned B); 85}; 86} // end anonymous namespace 87 88 89JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) { 90 // Add a scope entry for function scope. 91 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation())); 92 93 // Build information for the top level compound statement, so that we have a 94 // defined scope record for every "goto" and label. 95 unsigned BodyParentScope = 0; 96 BuildScopeInformation(Body, BodyParentScope); 97 98 // Check that all jumps we saw are kosher. 99 VerifyJumps(); 100 VerifyIndirectJumps(); 101} 102 103/// GetDeepestCommonScope - Finds the innermost scope enclosing the 104/// two scopes. 105unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) { 106 while (A != B) { 107 // Inner scopes are created after outer scopes and therefore have 108 // higher indices. 109 if (A < B) { 110 assert(Scopes[B].ParentScope < B); 111 B = Scopes[B].ParentScope; 112 } else { 113 assert(Scopes[A].ParentScope < A); 114 A = Scopes[A].ParentScope; 115 } 116 } 117 return A; 118} 119 120typedef std::pair<unsigned,unsigned> ScopePair; 121 122/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a 123/// diagnostic that should be emitted if control goes over it. If not, return 0. 124static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) { 125 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 126 unsigned InDiag = 0; 127 if (VD->getType()->isVariablyModifiedType()) 128 InDiag = diag::note_protected_by_vla; 129 130 if (VD->hasAttr<BlocksAttr>()) 131 return ScopePair(diag::note_protected_by___block, 132 diag::note_exits___block); 133 134 if (VD->hasAttr<CleanupAttr>()) 135 return ScopePair(diag::note_protected_by_cleanup, 136 diag::note_exits_cleanup); 137 138 if (Context.getLangOpts().ObjCAutoRefCount && VD->hasLocalStorage()) { 139 switch (VD->getType().getObjCLifetime()) { 140 case Qualifiers::OCL_None: 141 case Qualifiers::OCL_ExplicitNone: 142 case Qualifiers::OCL_Autoreleasing: 143 break; 144 145 case Qualifiers::OCL_Strong: 146 case Qualifiers::OCL_Weak: 147 return ScopePair(diag::note_protected_by_objc_ownership, 148 diag::note_exits_objc_ownership); 149 } 150 } 151 152 if (Context.getLangOpts().CPlusPlus && VD->hasLocalStorage()) { 153 // C++11 [stmt.dcl]p3: 154 // A program that jumps from a point where a variable with automatic 155 // storage duration is not in scope to a point where it is in scope 156 // is ill-formed unless the variable has scalar type, class type with 157 // a trivial default constructor and a trivial destructor, a 158 // cv-qualified version of one of these types, or an array of one of 159 // the preceding types and is declared without an initializer. 160 161 // C++03 [stmt.dcl.p3: 162 // A program that jumps from a point where a local variable 163 // with automatic storage duration is not in scope to a point 164 // where it is in scope is ill-formed unless the variable has 165 // POD type and is declared without an initializer. 166 167 const Expr *Init = VD->getInit(); 168 if (!Init) 169 return ScopePair(InDiag, 0); 170 171 const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init); 172 if (EWC) 173 Init = EWC->getSubExpr(); 174 175 const MaterializeTemporaryExpr *M = NULL; 176 Init = Init->findMaterializedTemporary(M); 177 178 SmallVector<SubobjectAdjustment, 2> Adjustments; 179 Init = Init->skipRValueSubobjectAdjustments(Adjustments); 180 181 QualType QT = Init->getType(); 182 if (QT.isNull()) 183 return ScopePair(diag::note_protected_by_variable_init, 0); 184 185 const Type *T = QT.getTypePtr(); 186 if (T->isArrayType()) 187 T = T->getBaseElementTypeUnsafe(); 188 189 const CXXRecordDecl *Record = T->getAsCXXRecordDecl(); 190 if (!Record) 191 return ScopePair(diag::note_protected_by_variable_init, 0); 192 193 // If we need to call a non trivial destructor for this variable, 194 // record an out diagnostic. 195 unsigned OutDiag = 0; 196 if (!Init->isGLValue() && !Record->hasTrivialDestructor()) 197 OutDiag = diag::note_exits_dtor; 198 199 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(Init)) { 200 const CXXConstructorDecl *ctor = cce->getConstructor(); 201 if (ctor->isTrivial() && ctor->isDefaultConstructor()) { 202 if (OutDiag) 203 InDiag = diag::note_protected_by_variable_nontriv_destructor; 204 else if (!Record->isPOD()) 205 InDiag = diag::note_protected_by_variable_non_pod; 206 return ScopePair(InDiag, OutDiag); 207 } 208 } 209 210 return ScopePair(diag::note_protected_by_variable_init, OutDiag); 211 } 212 213 return ScopePair(InDiag, 0); 214 } 215 216 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { 217 if (TD->getUnderlyingType()->isVariablyModifiedType()) 218 return ScopePair(diag::note_protected_by_vla_typedef, 0); 219 } 220 221 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) { 222 if (TD->getUnderlyingType()->isVariablyModifiedType()) 223 return ScopePair(diag::note_protected_by_vla_type_alias, 0); 224 } 225 226 return ScopePair(0U, 0U); 227} 228 229/// \brief Build scope information for a declaration that is part of a DeclStmt. 230void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) { 231 // If this decl causes a new scope, push and switch to it. 232 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D); 233 if (Diags.first || Diags.second) { 234 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second, 235 D->getLocation())); 236 ParentScope = Scopes.size()-1; 237 } 238 239 // If the decl has an initializer, walk it with the potentially new 240 // scope we just installed. 241 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 242 if (Expr *Init = VD->getInit()) 243 BuildScopeInformation(Init, ParentScope); 244} 245 246/// \brief Build scope information for a captured block literal variables. 247void JumpScopeChecker::BuildScopeInformation(VarDecl *D, 248 const BlockDecl *BDecl, 249 unsigned &ParentScope) { 250 // exclude captured __block variables; there's no destructor 251 // associated with the block literal for them. 252 if (D->hasAttr<BlocksAttr>()) 253 return; 254 QualType T = D->getType(); 255 QualType::DestructionKind destructKind = T.isDestructedType(); 256 if (destructKind != QualType::DK_none) { 257 std::pair<unsigned,unsigned> Diags; 258 switch (destructKind) { 259 case QualType::DK_cxx_destructor: 260 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj, 261 diag::note_exits_block_captures_cxx_obj); 262 break; 263 case QualType::DK_objc_strong_lifetime: 264 Diags = ScopePair(diag::note_enters_block_captures_strong, 265 diag::note_exits_block_captures_strong); 266 break; 267 case QualType::DK_objc_weak_lifetime: 268 Diags = ScopePair(diag::note_enters_block_captures_weak, 269 diag::note_exits_block_captures_weak); 270 break; 271 case QualType::DK_none: 272 llvm_unreachable("non-lifetime captured variable"); 273 } 274 SourceLocation Loc = D->getLocation(); 275 if (Loc.isInvalid()) 276 Loc = BDecl->getLocation(); 277 Scopes.push_back(GotoScope(ParentScope, 278 Diags.first, Diags.second, Loc)); 279 ParentScope = Scopes.size()-1; 280 } 281} 282 283/// BuildScopeInformation - The statements from CI to CE are known to form a 284/// coherent VLA scope with a specified parent node. Walk through the 285/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively 286/// walking the AST as needed. 287void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) { 288 // If this is a statement, rather than an expression, scopes within it don't 289 // propagate out into the enclosing scope. Otherwise we have to worry 290 // about block literals, which have the lifetime of their enclosing statement. 291 unsigned independentParentScope = origParentScope; 292 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S)) 293 ? origParentScope : independentParentScope); 294 295 bool SkipFirstSubStmt = false; 296 297 // If we found a label, remember that it is in ParentScope scope. 298 switch (S->getStmtClass()) { 299 case Stmt::AddrLabelExprClass: 300 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel()); 301 break; 302 303 case Stmt::IndirectGotoStmtClass: 304 // "goto *&&lbl;" is a special case which we treat as equivalent 305 // to a normal goto. In addition, we don't calculate scope in the 306 // operand (to avoid recording the address-of-label use), which 307 // works only because of the restricted set of expressions which 308 // we detect as constant targets. 309 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) { 310 LabelAndGotoScopes[S] = ParentScope; 311 Jumps.push_back(S); 312 return; 313 } 314 315 LabelAndGotoScopes[S] = ParentScope; 316 IndirectJumps.push_back(cast<IndirectGotoStmt>(S)); 317 break; 318 319 case Stmt::SwitchStmtClass: 320 // Evaluate the condition variable before entering the scope of the switch 321 // statement. 322 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) { 323 BuildScopeInformation(Var, ParentScope); 324 SkipFirstSubStmt = true; 325 } 326 // Fall through 327 328 case Stmt::GotoStmtClass: 329 // Remember both what scope a goto is in as well as the fact that we have 330 // it. This makes the second scan not have to walk the AST again. 331 LabelAndGotoScopes[S] = ParentScope; 332 Jumps.push_back(S); 333 break; 334 335 case Stmt::CXXTryStmtClass: { 336 CXXTryStmt *TS = cast<CXXTryStmt>(S); 337 unsigned newParentScope; 338 Scopes.push_back(GotoScope(ParentScope, 339 diag::note_protected_by_cxx_try, 340 diag::note_exits_cxx_try, 341 TS->getSourceRange().getBegin())); 342 if (Stmt *TryBlock = TS->getTryBlock()) 343 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1)); 344 345 // Jump from the catch into the try is not allowed either. 346 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) { 347 CXXCatchStmt *CS = TS->getHandler(I); 348 Scopes.push_back(GotoScope(ParentScope, 349 diag::note_protected_by_cxx_catch, 350 diag::note_exits_cxx_catch, 351 CS->getSourceRange().getBegin())); 352 BuildScopeInformation(CS->getHandlerBlock(), 353 (newParentScope = Scopes.size()-1)); 354 } 355 return; 356 } 357 358 default: 359 break; 360 } 361 362 for (Stmt::child_range CI = S->children(); CI; ++CI) { 363 if (SkipFirstSubStmt) { 364 SkipFirstSubStmt = false; 365 continue; 366 } 367 368 Stmt *SubStmt = *CI; 369 if (SubStmt == 0) continue; 370 371 // Cases, labels, and defaults aren't "scope parents". It's also 372 // important to handle these iteratively instead of recursively in 373 // order to avoid blowing out the stack. 374 while (true) { 375 Stmt *Next; 376 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt)) 377 Next = CS->getSubStmt(); 378 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt)) 379 Next = DS->getSubStmt(); 380 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt)) 381 Next = LS->getSubStmt(); 382 else 383 break; 384 385 LabelAndGotoScopes[SubStmt] = ParentScope; 386 SubStmt = Next; 387 } 388 389 // If this is a declstmt with a VLA definition, it defines a scope from here 390 // to the end of the containing context. 391 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) { 392 // The decl statement creates a scope if any of the decls in it are VLAs 393 // or have the cleanup attribute. 394 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end(); 395 I != E; ++I) 396 BuildScopeInformation(*I, ParentScope); 397 continue; 398 } 399 // Disallow jumps into any part of an @try statement by pushing a scope and 400 // walking all sub-stmts in that scope. 401 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) { 402 unsigned newParentScope; 403 // Recursively walk the AST for the @try part. 404 Scopes.push_back(GotoScope(ParentScope, 405 diag::note_protected_by_objc_try, 406 diag::note_exits_objc_try, 407 AT->getAtTryLoc())); 408 if (Stmt *TryPart = AT->getTryBody()) 409 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1)); 410 411 // Jump from the catch to the finally or try is not valid. 412 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) { 413 ObjCAtCatchStmt *AC = AT->getCatchStmt(I); 414 Scopes.push_back(GotoScope(ParentScope, 415 diag::note_protected_by_objc_catch, 416 diag::note_exits_objc_catch, 417 AC->getAtCatchLoc())); 418 // @catches are nested and it isn't 419 BuildScopeInformation(AC->getCatchBody(), 420 (newParentScope = Scopes.size()-1)); 421 } 422 423 // Jump from the finally to the try or catch is not valid. 424 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) { 425 Scopes.push_back(GotoScope(ParentScope, 426 diag::note_protected_by_objc_finally, 427 diag::note_exits_objc_finally, 428 AF->getAtFinallyLoc())); 429 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1)); 430 } 431 432 continue; 433 } 434 435 unsigned newParentScope; 436 // Disallow jumps into the protected statement of an @synchronized, but 437 // allow jumps into the object expression it protects. 438 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){ 439 // Recursively walk the AST for the @synchronized object expr, it is 440 // evaluated in the normal scope. 441 BuildScopeInformation(AS->getSynchExpr(), ParentScope); 442 443 // Recursively walk the AST for the @synchronized part, protected by a new 444 // scope. 445 Scopes.push_back(GotoScope(ParentScope, 446 diag::note_protected_by_objc_synchronized, 447 diag::note_exits_objc_synchronized, 448 AS->getAtSynchronizedLoc())); 449 BuildScopeInformation(AS->getSynchBody(), 450 (newParentScope = Scopes.size()-1)); 451 continue; 452 } 453 454 // Disallow jumps into the protected statement of an @autoreleasepool. 455 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){ 456 // Recursively walk the AST for the @autoreleasepool part, protected by a new 457 // scope. 458 Scopes.push_back(GotoScope(ParentScope, 459 diag::note_protected_by_objc_autoreleasepool, 460 diag::note_exits_objc_autoreleasepool, 461 AS->getAtLoc())); 462 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1)); 463 continue; 464 } 465 466 // Disallow jumps past full-expressions that use blocks with 467 // non-trivial cleanups of their captures. This is theoretically 468 // implementable but a lot of work which we haven't felt up to doing. 469 if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) { 470 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) { 471 const BlockDecl *BDecl = EWC->getObject(i); 472 for (BlockDecl::capture_const_iterator ci = BDecl->capture_begin(), 473 ce = BDecl->capture_end(); ci != ce; ++ci) { 474 VarDecl *variable = ci->getVariable(); 475 BuildScopeInformation(variable, BDecl, ParentScope); 476 } 477 } 478 } 479 480 // Recursively walk the AST. 481 BuildScopeInformation(SubStmt, ParentScope); 482 } 483} 484 485/// VerifyJumps - Verify each element of the Jumps array to see if they are 486/// valid, emitting diagnostics if not. 487void JumpScopeChecker::VerifyJumps() { 488 while (!Jumps.empty()) { 489 Stmt *Jump = Jumps.pop_back_val(); 490 491 // With a goto, 492 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) { 493 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(), 494 diag::err_goto_into_protected_scope, 495 diag::warn_goto_into_protected_scope, 496 diag::warn_cxx98_compat_goto_into_protected_scope); 497 continue; 498 } 499 500 // We only get indirect gotos here when they have a constant target. 501 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) { 502 LabelDecl *Target = IGS->getConstantTarget(); 503 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(), 504 diag::err_goto_into_protected_scope, 505 diag::warn_goto_into_protected_scope, 506 diag::warn_cxx98_compat_goto_into_protected_scope); 507 continue; 508 } 509 510 SwitchStmt *SS = cast<SwitchStmt>(Jump); 511 for (SwitchCase *SC = SS->getSwitchCaseList(); SC; 512 SC = SC->getNextSwitchCase()) { 513 assert(LabelAndGotoScopes.count(SC) && "Case not visited?"); 514 SourceLocation Loc; 515 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC)) 516 Loc = CS->getLocStart(); 517 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) 518 Loc = DS->getLocStart(); 519 else 520 Loc = SC->getLocStart(); 521 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0, 522 diag::warn_cxx98_compat_switch_into_protected_scope); 523 } 524 } 525} 526 527/// VerifyIndirectJumps - Verify whether any possible indirect jump 528/// might cross a protection boundary. Unlike direct jumps, indirect 529/// jumps count cleanups as protection boundaries: since there's no 530/// way to know where the jump is going, we can't implicitly run the 531/// right cleanups the way we can with direct jumps. 532/// 533/// Thus, an indirect jump is "trivial" if it bypasses no 534/// initializations and no teardowns. More formally, an indirect jump 535/// from A to B is trivial if the path out from A to DCA(A,B) is 536/// trivial and the path in from DCA(A,B) to B is trivial, where 537/// DCA(A,B) is the deepest common ancestor of A and B. 538/// Jump-triviality is transitive but asymmetric. 539/// 540/// A path in is trivial if none of the entered scopes have an InDiag. 541/// A path out is trivial is none of the exited scopes have an OutDiag. 542/// 543/// Under these definitions, this function checks that the indirect 544/// jump between A and B is trivial for every indirect goto statement A 545/// and every label B whose address was taken in the function. 546void JumpScopeChecker::VerifyIndirectJumps() { 547 if (IndirectJumps.empty()) return; 548 549 // If there aren't any address-of-label expressions in this function, 550 // complain about the first indirect goto. 551 if (IndirectJumpTargets.empty()) { 552 S.Diag(IndirectJumps[0]->getGotoLoc(), 553 diag::err_indirect_goto_without_addrlabel); 554 return; 555 } 556 557 // Collect a single representative of every scope containing an 558 // indirect goto. For most code bases, this substantially cuts 559 // down on the number of jump sites we'll have to consider later. 560 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope; 561 SmallVector<JumpScope, 32> JumpScopes; 562 { 563 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap; 564 for (SmallVectorImpl<IndirectGotoStmt*>::iterator 565 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) { 566 IndirectGotoStmt *IG = *I; 567 assert(LabelAndGotoScopes.count(IG) && 568 "indirect jump didn't get added to scopes?"); 569 unsigned IGScope = LabelAndGotoScopes[IG]; 570 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope]; 571 if (!Entry) Entry = IG; 572 } 573 JumpScopes.reserve(JumpScopesMap.size()); 574 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator 575 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I) 576 JumpScopes.push_back(*I); 577 } 578 579 // Collect a single representative of every scope containing a 580 // label whose address was taken somewhere in the function. 581 // For most code bases, there will be only one such scope. 582 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes; 583 for (SmallVectorImpl<LabelDecl*>::iterator 584 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end(); 585 I != E; ++I) { 586 LabelDecl *TheLabel = *I; 587 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) && 588 "Referenced label didn't get added to scopes?"); 589 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()]; 590 LabelDecl *&Target = TargetScopes[LabelScope]; 591 if (!Target) Target = TheLabel; 592 } 593 594 // For each target scope, make sure it's trivially reachable from 595 // every scope containing a jump site. 596 // 597 // A path between scopes always consists of exitting zero or more 598 // scopes, then entering zero or more scopes. We build a set of 599 // of scopes S from which the target scope can be trivially 600 // entered, then verify that every jump scope can be trivially 601 // exitted to reach a scope in S. 602 llvm::BitVector Reachable(Scopes.size(), false); 603 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator 604 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) { 605 unsigned TargetScope = TI->first; 606 LabelDecl *TargetLabel = TI->second; 607 608 Reachable.reset(); 609 610 // Mark all the enclosing scopes from which you can safely jump 611 // into the target scope. 'Min' will end up being the index of 612 // the shallowest such scope. 613 unsigned Min = TargetScope; 614 while (true) { 615 Reachable.set(Min); 616 617 // Don't go beyond the outermost scope. 618 if (Min == 0) break; 619 620 // Stop if we can't trivially enter the current scope. 621 if (Scopes[Min].InDiag) break; 622 623 Min = Scopes[Min].ParentScope; 624 } 625 626 // Walk through all the jump sites, checking that they can trivially 627 // reach this label scope. 628 for (SmallVectorImpl<JumpScope>::iterator 629 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) { 630 unsigned Scope = I->first; 631 632 // Walk out the "scope chain" for this scope, looking for a scope 633 // we've marked reachable. For well-formed code this amortizes 634 // to O(JumpScopes.size() / Scopes.size()): we only iterate 635 // when we see something unmarked, and in well-formed code we 636 // mark everything we iterate past. 637 bool IsReachable = false; 638 while (true) { 639 if (Reachable.test(Scope)) { 640 // If we find something reachable, mark all the scopes we just 641 // walked through as reachable. 642 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope) 643 Reachable.set(S); 644 IsReachable = true; 645 break; 646 } 647 648 // Don't walk out if we've reached the top-level scope or we've 649 // gotten shallower than the shallowest reachable scope. 650 if (Scope == 0 || Scope < Min) break; 651 652 // Don't walk out through an out-diagnostic. 653 if (Scopes[Scope].OutDiag) break; 654 655 Scope = Scopes[Scope].ParentScope; 656 } 657 658 // Only diagnose if we didn't find something. 659 if (IsReachable) continue; 660 661 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope); 662 } 663 } 664} 665 666/// Return true if a particular error+note combination must be downgraded to a 667/// warning in Microsoft mode. 668static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) { 669 return (JumpDiag == diag::err_goto_into_protected_scope && 670 (InDiagNote == diag::note_protected_by_variable_init || 671 InDiagNote == diag::note_protected_by_variable_nontriv_destructor)); 672} 673 674/// Return true if a particular note should be downgraded to a compatibility 675/// warning in C++11 mode. 676static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) { 677 return S.getLangOpts().CPlusPlus0x && 678 InDiagNote == diag::note_protected_by_variable_non_pod; 679} 680 681/// Produce primary diagnostic for an indirect jump statement. 682static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump, 683 LabelDecl *Target, bool &Diagnosed) { 684 if (Diagnosed) 685 return; 686 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope); 687 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target); 688 Diagnosed = true; 689} 690 691/// Produce note diagnostics for a jump into a protected scope. 692void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) { 693 assert(!ToScopes.empty()); 694 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I) 695 if (Scopes[ToScopes[I]].InDiag) 696 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag); 697} 698 699/// Diagnose an indirect jump which is known to cross scopes. 700void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump, 701 unsigned JumpScope, 702 LabelDecl *Target, 703 unsigned TargetScope) { 704 assert(JumpScope != TargetScope); 705 706 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope); 707 bool Diagnosed = false; 708 709 // Walk out the scope chain until we reach the common ancestor. 710 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope) 711 if (Scopes[I].OutDiag) { 712 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed); 713 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag); 714 } 715 716 SmallVector<unsigned, 10> ToScopesCXX98Compat; 717 718 // Now walk into the scopes containing the label whose address was taken. 719 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope) 720 if (IsCXX98CompatWarning(S, Scopes[I].InDiag)) 721 ToScopesCXX98Compat.push_back(I); 722 else if (Scopes[I].InDiag) { 723 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed); 724 S.Diag(Scopes[I].Loc, Scopes[I].InDiag); 725 } 726 727 // Diagnose this jump if it would be ill-formed in C++98. 728 if (!Diagnosed && !ToScopesCXX98Compat.empty()) { 729 S.Diag(Jump->getGotoLoc(), 730 diag::warn_cxx98_compat_indirect_goto_in_protected_scope); 731 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target); 732 NoteJumpIntoScopes(ToScopesCXX98Compat); 733 } 734} 735 736/// CheckJump - Validate that the specified jump statement is valid: that it is 737/// jumping within or out of its current scope, not into a deeper one. 738void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, 739 unsigned JumpDiagError, unsigned JumpDiagWarning, 740 unsigned JumpDiagCXX98Compat) { 741 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?"); 742 unsigned FromScope = LabelAndGotoScopes[From]; 743 744 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?"); 745 unsigned ToScope = LabelAndGotoScopes[To]; 746 747 // Common case: exactly the same scope, which is fine. 748 if (FromScope == ToScope) return; 749 750 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope); 751 752 // It's okay to jump out from a nested scope. 753 if (CommonScope == ToScope) return; 754 755 // Pull out (and reverse) any scopes we might need to diagnose skipping. 756 SmallVector<unsigned, 10> ToScopesCXX98Compat; 757 SmallVector<unsigned, 10> ToScopesError; 758 SmallVector<unsigned, 10> ToScopesWarning; 759 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) { 760 if (S.getLangOpts().MicrosoftMode && JumpDiagWarning != 0 && 761 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag)) 762 ToScopesWarning.push_back(I); 763 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag)) 764 ToScopesCXX98Compat.push_back(I); 765 else if (Scopes[I].InDiag) 766 ToScopesError.push_back(I); 767 } 768 769 // Handle warnings. 770 if (!ToScopesWarning.empty()) { 771 S.Diag(DiagLoc, JumpDiagWarning); 772 NoteJumpIntoScopes(ToScopesWarning); 773 } 774 775 // Handle errors. 776 if (!ToScopesError.empty()) { 777 S.Diag(DiagLoc, JumpDiagError); 778 NoteJumpIntoScopes(ToScopesError); 779 } 780 781 // Handle -Wc++98-compat warnings if the jump is well-formed. 782 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) { 783 S.Diag(DiagLoc, JumpDiagCXX98Compat); 784 NoteJumpIntoScopes(ToScopesCXX98Compat); 785 } 786} 787 788void Sema::DiagnoseInvalidJumps(Stmt *Body) { 789 (void)JumpScopeChecker(Body, *this); 790} 791