1 //===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the JumpScopeChecker class, which is used to diagnose
11 // jumps that enter a protected scope in an invalid way.
13 //===----------------------------------------------------------------------===//
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/StmtObjC.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "llvm/ADT/BitVector.h"
22 using namespace clang;
26 /// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
27 /// into VLA and other protected scopes. For example, this rejects:
32 class JumpScopeChecker {
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.
41 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
42 /// the parent scope is the function body.
45 /// InDiag - The note to emit if there is a jump into this scope.
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.
53 /// Loc - Location to emit the diagnostic.
56 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
58 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
61 SmallVector<GotoScope, 48> Scopes;
62 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
63 SmallVector<Stmt*, 16> Jumps;
65 SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
66 SmallVector<LabelDecl*, 4> IndirectJumpTargets;
68 JumpScopeChecker(Stmt *Body, Sema &S);
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);
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);
84 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
86 } // end anonymous namespace
89 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
90 // Add a scope entry for function scope.
91 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
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);
98 // Check that all jumps we saw are kosher.
100 VerifyIndirectJumps();
103 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
105 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
107 // Inner scopes are created after outer scopes and therefore have
110 assert(Scopes[B].ParentScope < B);
111 B = Scopes[B].ParentScope;
113 assert(Scopes[A].ParentScope < A);
114 A = Scopes[A].ParentScope;
120 typedef std::pair<unsigned,unsigned> ScopePair;
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.
124 static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
125 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
127 if (VD->getType()->isVariablyModifiedType())
128 InDiag = diag::note_protected_by_vla;
130 if (VD->hasAttr<BlocksAttr>())
131 return ScopePair(diag::note_protected_by___block,
132 diag::note_exits___block);
134 if (VD->hasAttr<CleanupAttr>())
135 return ScopePair(diag::note_protected_by_cleanup,
136 diag::note_exits_cleanup);
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:
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);
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.
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.
167 const Expr *Init = VD->getInit();
169 return ScopePair(InDiag, 0);
171 const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init);
173 Init = EWC->getSubExpr();
175 const MaterializeTemporaryExpr *M = NULL;
176 Init = Init->findMaterializedTemporary(M);
178 SmallVector<SubobjectAdjustment, 2> Adjustments;
179 Init = Init->skipRValueSubobjectAdjustments(Adjustments);
181 QualType QT = Init->getType();
183 return ScopePair(diag::note_protected_by_variable_init, 0);
185 const Type *T = QT.getTypePtr();
186 if (T->isArrayType())
187 T = T->getBaseElementTypeUnsafe();
189 const CXXRecordDecl *Record = T->getAsCXXRecordDecl();
191 return ScopePair(diag::note_protected_by_variable_init, 0);
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;
199 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(Init)) {
200 const CXXConstructorDecl *ctor = cce->getConstructor();
201 if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
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);
210 return ScopePair(diag::note_protected_by_variable_init, OutDiag);
213 return ScopePair(InDiag, 0);
216 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
217 if (TD->getUnderlyingType()->isVariablyModifiedType())
218 return ScopePair(diag::note_protected_by_vla_typedef, 0);
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);
226 return ScopePair(0U, 0U);
229 /// \brief Build scope information for a declaration that is part of a DeclStmt.
230 void 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,
236 ParentScope = Scopes.size()-1;
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);
246 /// \brief Build scope information for a captured block literal variables.
247 void 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>())
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);
263 case QualType::DK_objc_strong_lifetime:
264 Diags = ScopePair(diag::note_enters_block_captures_strong,
265 diag::note_exits_block_captures_strong);
267 case QualType::DK_objc_weak_lifetime:
268 Diags = ScopePair(diag::note_enters_block_captures_weak,
269 diag::note_exits_block_captures_weak);
271 case QualType::DK_none:
272 llvm_unreachable("non-lifetime captured variable");
274 SourceLocation Loc = D->getLocation();
276 Loc = BDecl->getLocation();
277 Scopes.push_back(GotoScope(ParentScope,
278 Diags.first, Diags.second, Loc));
279 ParentScope = Scopes.size()-1;
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.
287 void 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);
295 bool SkipFirstSubStmt = false;
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());
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;
315 LabelAndGotoScopes[S] = ParentScope;
316 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
319 case Stmt::SwitchStmtClass:
320 // Evaluate the condition variable before entering the scope of the switch
322 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
323 BuildScopeInformation(Var, ParentScope);
324 SkipFirstSubStmt = true;
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;
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));
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));
362 for (Stmt::child_range CI = S->children(); CI; ++CI) {
363 if (SkipFirstSubStmt) {
364 SkipFirstSubStmt = false;
369 if (SubStmt == 0) continue;
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.
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();
385 LabelAndGotoScopes[SubStmt] = ParentScope;
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();
396 BuildScopeInformation(*I, ParentScope);
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,
408 if (Stmt *TryPart = AT->getTryBody())
409 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
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));
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));
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);
443 // Recursively walk the AST for the @synchronized part, protected by a new
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));
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
458 Scopes.push_back(GotoScope(ParentScope,
459 diag::note_protected_by_objc_autoreleasepool,
460 diag::note_exits_objc_autoreleasepool,
462 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
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);
480 // Recursively walk the AST.
481 BuildScopeInformation(SubStmt, ParentScope);
485 /// VerifyJumps - Verify each element of the Jumps array to see if they are
486 /// valid, emitting diagnostics if not.
487 void JumpScopeChecker::VerifyJumps() {
488 while (!Jumps.empty()) {
489 Stmt *Jump = Jumps.pop_back_val();
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);
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);
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 CheckJump(SS, SC, SC->getLocStart(),
515 diag::err_switch_into_protected_scope, 0,
516 diag::warn_cxx98_compat_switch_into_protected_scope);
521 /// VerifyIndirectJumps - Verify whether any possible indirect jump
522 /// might cross a protection boundary. Unlike direct jumps, indirect
523 /// jumps count cleanups as protection boundaries: since there's no
524 /// way to know where the jump is going, we can't implicitly run the
525 /// right cleanups the way we can with direct jumps.
527 /// Thus, an indirect jump is "trivial" if it bypasses no
528 /// initializations and no teardowns. More formally, an indirect jump
529 /// from A to B is trivial if the path out from A to DCA(A,B) is
530 /// trivial and the path in from DCA(A,B) to B is trivial, where
531 /// DCA(A,B) is the deepest common ancestor of A and B.
532 /// Jump-triviality is transitive but asymmetric.
534 /// A path in is trivial if none of the entered scopes have an InDiag.
535 /// A path out is trivial is none of the exited scopes have an OutDiag.
537 /// Under these definitions, this function checks that the indirect
538 /// jump between A and B is trivial for every indirect goto statement A
539 /// and every label B whose address was taken in the function.
540 void JumpScopeChecker::VerifyIndirectJumps() {
541 if (IndirectJumps.empty()) return;
543 // If there aren't any address-of-label expressions in this function,
544 // complain about the first indirect goto.
545 if (IndirectJumpTargets.empty()) {
546 S.Diag(IndirectJumps[0]->getGotoLoc(),
547 diag::err_indirect_goto_without_addrlabel);
551 // Collect a single representative of every scope containing an
552 // indirect goto. For most code bases, this substantially cuts
553 // down on the number of jump sites we'll have to consider later.
554 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
555 SmallVector<JumpScope, 32> JumpScopes;
557 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
558 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
559 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
560 IndirectGotoStmt *IG = *I;
561 assert(LabelAndGotoScopes.count(IG) &&
562 "indirect jump didn't get added to scopes?");
563 unsigned IGScope = LabelAndGotoScopes[IG];
564 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
565 if (!Entry) Entry = IG;
567 JumpScopes.reserve(JumpScopesMap.size());
568 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
569 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
570 JumpScopes.push_back(*I);
573 // Collect a single representative of every scope containing a
574 // label whose address was taken somewhere in the function.
575 // For most code bases, there will be only one such scope.
576 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
577 for (SmallVectorImpl<LabelDecl*>::iterator
578 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
580 LabelDecl *TheLabel = *I;
581 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
582 "Referenced label didn't get added to scopes?");
583 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
584 LabelDecl *&Target = TargetScopes[LabelScope];
585 if (!Target) Target = TheLabel;
588 // For each target scope, make sure it's trivially reachable from
589 // every scope containing a jump site.
591 // A path between scopes always consists of exitting zero or more
592 // scopes, then entering zero or more scopes. We build a set of
593 // of scopes S from which the target scope can be trivially
594 // entered, then verify that every jump scope can be trivially
595 // exitted to reach a scope in S.
596 llvm::BitVector Reachable(Scopes.size(), false);
597 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
598 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
599 unsigned TargetScope = TI->first;
600 LabelDecl *TargetLabel = TI->second;
604 // Mark all the enclosing scopes from which you can safely jump
605 // into the target scope. 'Min' will end up being the index of
606 // the shallowest such scope.
607 unsigned Min = TargetScope;
611 // Don't go beyond the outermost scope.
614 // Stop if we can't trivially enter the current scope.
615 if (Scopes[Min].InDiag) break;
617 Min = Scopes[Min].ParentScope;
620 // Walk through all the jump sites, checking that they can trivially
621 // reach this label scope.
622 for (SmallVectorImpl<JumpScope>::iterator
623 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
624 unsigned Scope = I->first;
626 // Walk out the "scope chain" for this scope, looking for a scope
627 // we've marked reachable. For well-formed code this amortizes
628 // to O(JumpScopes.size() / Scopes.size()): we only iterate
629 // when we see something unmarked, and in well-formed code we
630 // mark everything we iterate past.
631 bool IsReachable = false;
633 if (Reachable.test(Scope)) {
634 // If we find something reachable, mark all the scopes we just
635 // walked through as reachable.
636 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
642 // Don't walk out if we've reached the top-level scope or we've
643 // gotten shallower than the shallowest reachable scope.
644 if (Scope == 0 || Scope < Min) break;
646 // Don't walk out through an out-diagnostic.
647 if (Scopes[Scope].OutDiag) break;
649 Scope = Scopes[Scope].ParentScope;
652 // Only diagnose if we didn't find something.
653 if (IsReachable) continue;
655 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
660 /// Return true if a particular error+note combination must be downgraded to a
661 /// warning in Microsoft mode.
662 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
663 return (JumpDiag == diag::err_goto_into_protected_scope &&
664 (InDiagNote == diag::note_protected_by_variable_init ||
665 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
668 /// Return true if a particular note should be downgraded to a compatibility
669 /// warning in C++11 mode.
670 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
671 return S.getLangOpts().CPlusPlus0x &&
672 InDiagNote == diag::note_protected_by_variable_non_pod;
675 /// Produce primary diagnostic for an indirect jump statement.
676 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
677 LabelDecl *Target, bool &Diagnosed) {
680 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
681 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
685 /// Produce note diagnostics for a jump into a protected scope.
686 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
687 assert(!ToScopes.empty());
688 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
689 if (Scopes[ToScopes[I]].InDiag)
690 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
693 /// Diagnose an indirect jump which is known to cross scopes.
694 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
697 unsigned TargetScope) {
698 assert(JumpScope != TargetScope);
700 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
701 bool Diagnosed = false;
703 // Walk out the scope chain until we reach the common ancestor.
704 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
705 if (Scopes[I].OutDiag) {
706 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
707 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
710 SmallVector<unsigned, 10> ToScopesCXX98Compat;
712 // Now walk into the scopes containing the label whose address was taken.
713 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
714 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
715 ToScopesCXX98Compat.push_back(I);
716 else if (Scopes[I].InDiag) {
717 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
718 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
721 // Diagnose this jump if it would be ill-formed in C++98.
722 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
723 S.Diag(Jump->getGotoLoc(),
724 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
725 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
726 NoteJumpIntoScopes(ToScopesCXX98Compat);
730 /// CheckJump - Validate that the specified jump statement is valid: that it is
731 /// jumping within or out of its current scope, not into a deeper one.
732 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
733 unsigned JumpDiagError, unsigned JumpDiagWarning,
734 unsigned JumpDiagCXX98Compat) {
735 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
736 unsigned FromScope = LabelAndGotoScopes[From];
738 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
739 unsigned ToScope = LabelAndGotoScopes[To];
741 // Common case: exactly the same scope, which is fine.
742 if (FromScope == ToScope) return;
744 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
746 // It's okay to jump out from a nested scope.
747 if (CommonScope == ToScope) return;
749 // Pull out (and reverse) any scopes we might need to diagnose skipping.
750 SmallVector<unsigned, 10> ToScopesCXX98Compat;
751 SmallVector<unsigned, 10> ToScopesError;
752 SmallVector<unsigned, 10> ToScopesWarning;
753 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
754 if (S.getLangOpts().MicrosoftMode && JumpDiagWarning != 0 &&
755 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
756 ToScopesWarning.push_back(I);
757 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
758 ToScopesCXX98Compat.push_back(I);
759 else if (Scopes[I].InDiag)
760 ToScopesError.push_back(I);
764 if (!ToScopesWarning.empty()) {
765 S.Diag(DiagLoc, JumpDiagWarning);
766 NoteJumpIntoScopes(ToScopesWarning);
770 if (!ToScopesError.empty()) {
771 S.Diag(DiagLoc, JumpDiagError);
772 NoteJumpIntoScopes(ToScopesError);
775 // Handle -Wc++98-compat warnings if the jump is well-formed.
776 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
777 S.Diag(DiagLoc, JumpDiagCXX98Compat);
778 NoteJumpIntoScopes(ToScopesCXX98Compat);
782 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
783 (void)JumpScopeChecker(Body, *this);