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)) {
126 unsigned InDiag = 0, OutDiag = 0;
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 if (const Expr *init = VD->getInit()) {
168 // We actually give variables of record type (or array thereof)
169 // an initializer even if that initializer only calls a trivial
170 // ctor. Detect that case.
171 // FIXME: With generalized initializer lists, this may
172 // classify "X x{};" as having no initializer.
173 unsigned inDiagToUse = diag::note_protected_by_variable_init;
175 const CXXRecordDecl *record = 0;
177 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(init)) {
178 const CXXConstructorDecl *ctor = cce->getConstructor();
179 record = ctor->getParent();
181 if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
182 if (!record->hasTrivialDestructor())
183 inDiagToUse = diag::note_protected_by_variable_nontriv_destructor;
184 else if (!record->isPOD())
185 inDiagToUse = diag::note_protected_by_variable_non_pod;
189 } else if (VD->getType()->isArrayType()) {
190 record = VD->getType()->getBaseElementTypeUnsafe()
191 ->getAsCXXRecordDecl();
195 InDiag = inDiagToUse;
197 // Also object to indirect jumps which leave scopes with dtors.
198 if (record && !record->hasTrivialDestructor())
199 OutDiag = diag::note_exits_dtor;
203 return ScopePair(InDiag, OutDiag);
206 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
207 if (TD->getUnderlyingType()->isVariablyModifiedType())
208 return ScopePair(diag::note_protected_by_vla_typedef, 0);
211 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
212 if (TD->getUnderlyingType()->isVariablyModifiedType())
213 return ScopePair(diag::note_protected_by_vla_type_alias, 0);
216 return ScopePair(0U, 0U);
219 /// \brief Build scope information for a declaration that is part of a DeclStmt.
220 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
221 // If this decl causes a new scope, push and switch to it.
222 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D);
223 if (Diags.first || Diags.second) {
224 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
226 ParentScope = Scopes.size()-1;
229 // If the decl has an initializer, walk it with the potentially new
230 // scope we just installed.
231 if (VarDecl *VD = dyn_cast<VarDecl>(D))
232 if (Expr *Init = VD->getInit())
233 BuildScopeInformation(Init, ParentScope);
236 /// \brief Build scope information for a captured block literal variables.
237 void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
238 const BlockDecl *BDecl,
239 unsigned &ParentScope) {
240 // exclude captured __block variables; there's no destructor
241 // associated with the block literal for them.
242 if (D->hasAttr<BlocksAttr>())
244 QualType T = D->getType();
245 QualType::DestructionKind destructKind = T.isDestructedType();
246 if (destructKind != QualType::DK_none) {
247 std::pair<unsigned,unsigned> Diags;
248 switch (destructKind) {
249 case QualType::DK_cxx_destructor:
250 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
251 diag::note_exits_block_captures_cxx_obj);
253 case QualType::DK_objc_strong_lifetime:
254 Diags = ScopePair(diag::note_enters_block_captures_strong,
255 diag::note_exits_block_captures_strong);
257 case QualType::DK_objc_weak_lifetime:
258 Diags = ScopePair(diag::note_enters_block_captures_weak,
259 diag::note_exits_block_captures_weak);
261 case QualType::DK_none:
262 llvm_unreachable("non-lifetime captured variable");
264 SourceLocation Loc = D->getLocation();
266 Loc = BDecl->getLocation();
267 Scopes.push_back(GotoScope(ParentScope,
268 Diags.first, Diags.second, Loc));
269 ParentScope = Scopes.size()-1;
273 /// BuildScopeInformation - The statements from CI to CE are known to form a
274 /// coherent VLA scope with a specified parent node. Walk through the
275 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
276 /// walking the AST as needed.
277 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
278 // If this is a statement, rather than an expression, scopes within it don't
279 // propagate out into the enclosing scope. Otherwise we have to worry
280 // about block literals, which have the lifetime of their enclosing statement.
281 unsigned independentParentScope = origParentScope;
282 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
283 ? origParentScope : independentParentScope);
285 bool SkipFirstSubStmt = false;
287 // If we found a label, remember that it is in ParentScope scope.
288 switch (S->getStmtClass()) {
289 case Stmt::AddrLabelExprClass:
290 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
293 case Stmt::IndirectGotoStmtClass:
294 // "goto *&&lbl;" is a special case which we treat as equivalent
295 // to a normal goto. In addition, we don't calculate scope in the
296 // operand (to avoid recording the address-of-label use), which
297 // works only because of the restricted set of expressions which
298 // we detect as constant targets.
299 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
300 LabelAndGotoScopes[S] = ParentScope;
305 LabelAndGotoScopes[S] = ParentScope;
306 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
309 case Stmt::SwitchStmtClass:
310 // Evaluate the condition variable before entering the scope of the switch
312 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
313 BuildScopeInformation(Var, ParentScope);
314 SkipFirstSubStmt = true;
318 case Stmt::GotoStmtClass:
319 // Remember both what scope a goto is in as well as the fact that we have
320 // it. This makes the second scan not have to walk the AST again.
321 LabelAndGotoScopes[S] = ParentScope;
329 for (Stmt::child_range CI = S->children(); CI; ++CI) {
330 if (SkipFirstSubStmt) {
331 SkipFirstSubStmt = false;
336 if (SubStmt == 0) continue;
338 // Cases, labels, and defaults aren't "scope parents". It's also
339 // important to handle these iteratively instead of recursively in
340 // order to avoid blowing out the stack.
343 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
344 Next = CS->getSubStmt();
345 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
346 Next = DS->getSubStmt();
347 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
348 Next = LS->getSubStmt();
352 LabelAndGotoScopes[SubStmt] = ParentScope;
356 // If this is a declstmt with a VLA definition, it defines a scope from here
357 // to the end of the containing context.
358 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
359 // The decl statement creates a scope if any of the decls in it are VLAs
360 // or have the cleanup attribute.
361 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
363 BuildScopeInformation(*I, ParentScope);
366 // Disallow jumps into any part of an @try statement by pushing a scope and
367 // walking all sub-stmts in that scope.
368 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
369 unsigned newParentScope;
370 // Recursively walk the AST for the @try part.
371 Scopes.push_back(GotoScope(ParentScope,
372 diag::note_protected_by_objc_try,
373 diag::note_exits_objc_try,
375 if (Stmt *TryPart = AT->getTryBody())
376 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
378 // Jump from the catch to the finally or try is not valid.
379 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
380 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
381 Scopes.push_back(GotoScope(ParentScope,
382 diag::note_protected_by_objc_catch,
383 diag::note_exits_objc_catch,
384 AC->getAtCatchLoc()));
385 // @catches are nested and it isn't
386 BuildScopeInformation(AC->getCatchBody(),
387 (newParentScope = Scopes.size()-1));
390 // Jump from the finally to the try or catch is not valid.
391 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
392 Scopes.push_back(GotoScope(ParentScope,
393 diag::note_protected_by_objc_finally,
394 diag::note_exits_objc_finally,
395 AF->getAtFinallyLoc()));
396 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
402 unsigned newParentScope;
403 // Disallow jumps into the protected statement of an @synchronized, but
404 // allow jumps into the object expression it protects.
405 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
406 // Recursively walk the AST for the @synchronized object expr, it is
407 // evaluated in the normal scope.
408 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
410 // Recursively walk the AST for the @synchronized part, protected by a new
412 Scopes.push_back(GotoScope(ParentScope,
413 diag::note_protected_by_objc_synchronized,
414 diag::note_exits_objc_synchronized,
415 AS->getAtSynchronizedLoc()));
416 BuildScopeInformation(AS->getSynchBody(),
417 (newParentScope = Scopes.size()-1));
421 // Disallow jumps into any part of a C++ try statement. This is pretty
422 // much the same as for Obj-C.
423 if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
424 Scopes.push_back(GotoScope(ParentScope,
425 diag::note_protected_by_cxx_try,
426 diag::note_exits_cxx_try,
427 TS->getSourceRange().getBegin()));
428 if (Stmt *TryBlock = TS->getTryBlock())
429 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
431 // Jump from the catch into the try is not allowed either.
432 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
433 CXXCatchStmt *CS = TS->getHandler(I);
434 Scopes.push_back(GotoScope(ParentScope,
435 diag::note_protected_by_cxx_catch,
436 diag::note_exits_cxx_catch,
437 CS->getSourceRange().getBegin()));
438 BuildScopeInformation(CS->getHandlerBlock(),
439 (newParentScope = Scopes.size()-1));
445 // Disallow jumps into the protected statement of an @autoreleasepool.
446 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
447 // Recursively walk the AST for the @autoreleasepool part, protected by a new
449 Scopes.push_back(GotoScope(ParentScope,
450 diag::note_protected_by_objc_autoreleasepool,
451 diag::note_exits_objc_autoreleasepool,
453 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
457 if (const BlockExpr *BE = dyn_cast<BlockExpr>(SubStmt)) {
458 const BlockDecl *BDecl = BE->getBlockDecl();
459 for (BlockDecl::capture_const_iterator ci = BDecl->capture_begin(),
460 ce = BDecl->capture_end(); ci != ce; ++ci) {
461 VarDecl *variable = ci->getVariable();
462 BuildScopeInformation(variable, BDecl, ParentScope);
466 // Recursively walk the AST.
467 BuildScopeInformation(SubStmt, ParentScope);
471 /// VerifyJumps - Verify each element of the Jumps array to see if they are
472 /// valid, emitting diagnostics if not.
473 void JumpScopeChecker::VerifyJumps() {
474 while (!Jumps.empty()) {
475 Stmt *Jump = Jumps.pop_back_val();
478 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
479 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
480 diag::err_goto_into_protected_scope,
481 diag::warn_goto_into_protected_scope,
482 diag::warn_cxx98_compat_goto_into_protected_scope);
486 // We only get indirect gotos here when they have a constant target.
487 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
488 LabelDecl *Target = IGS->getConstantTarget();
489 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
490 diag::err_goto_into_protected_scope,
491 diag::warn_goto_into_protected_scope,
492 diag::warn_cxx98_compat_goto_into_protected_scope);
496 SwitchStmt *SS = cast<SwitchStmt>(Jump);
497 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
498 SC = SC->getNextSwitchCase()) {
499 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
500 CheckJump(SS, SC, SC->getLocStart(),
501 diag::err_switch_into_protected_scope, 0,
502 diag::warn_cxx98_compat_switch_into_protected_scope);
507 /// VerifyIndirectJumps - Verify whether any possible indirect jump
508 /// might cross a protection boundary. Unlike direct jumps, indirect
509 /// jumps count cleanups as protection boundaries: since there's no
510 /// way to know where the jump is going, we can't implicitly run the
511 /// right cleanups the way we can with direct jumps.
513 /// Thus, an indirect jump is "trivial" if it bypasses no
514 /// initializations and no teardowns. More formally, an indirect jump
515 /// from A to B is trivial if the path out from A to DCA(A,B) is
516 /// trivial and the path in from DCA(A,B) to B is trivial, where
517 /// DCA(A,B) is the deepest common ancestor of A and B.
518 /// Jump-triviality is transitive but asymmetric.
520 /// A path in is trivial if none of the entered scopes have an InDiag.
521 /// A path out is trivial is none of the exited scopes have an OutDiag.
523 /// Under these definitions, this function checks that the indirect
524 /// jump between A and B is trivial for every indirect goto statement A
525 /// and every label B whose address was taken in the function.
526 void JumpScopeChecker::VerifyIndirectJumps() {
527 if (IndirectJumps.empty()) return;
529 // If there aren't any address-of-label expressions in this function,
530 // complain about the first indirect goto.
531 if (IndirectJumpTargets.empty()) {
532 S.Diag(IndirectJumps[0]->getGotoLoc(),
533 diag::err_indirect_goto_without_addrlabel);
537 // Collect a single representative of every scope containing an
538 // indirect goto. For most code bases, this substantially cuts
539 // down on the number of jump sites we'll have to consider later.
540 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
541 SmallVector<JumpScope, 32> JumpScopes;
543 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
544 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
545 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
546 IndirectGotoStmt *IG = *I;
547 assert(LabelAndGotoScopes.count(IG) &&
548 "indirect jump didn't get added to scopes?");
549 unsigned IGScope = LabelAndGotoScopes[IG];
550 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
551 if (!Entry) Entry = IG;
553 JumpScopes.reserve(JumpScopesMap.size());
554 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
555 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
556 JumpScopes.push_back(*I);
559 // Collect a single representative of every scope containing a
560 // label whose address was taken somewhere in the function.
561 // For most code bases, there will be only one such scope.
562 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
563 for (SmallVectorImpl<LabelDecl*>::iterator
564 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
566 LabelDecl *TheLabel = *I;
567 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
568 "Referenced label didn't get added to scopes?");
569 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
570 LabelDecl *&Target = TargetScopes[LabelScope];
571 if (!Target) Target = TheLabel;
574 // For each target scope, make sure it's trivially reachable from
575 // every scope containing a jump site.
577 // A path between scopes always consists of exitting zero or more
578 // scopes, then entering zero or more scopes. We build a set of
579 // of scopes S from which the target scope can be trivially
580 // entered, then verify that every jump scope can be trivially
581 // exitted to reach a scope in S.
582 llvm::BitVector Reachable(Scopes.size(), false);
583 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
584 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
585 unsigned TargetScope = TI->first;
586 LabelDecl *TargetLabel = TI->second;
590 // Mark all the enclosing scopes from which you can safely jump
591 // into the target scope. 'Min' will end up being the index of
592 // the shallowest such scope.
593 unsigned Min = TargetScope;
597 // Don't go beyond the outermost scope.
600 // Stop if we can't trivially enter the current scope.
601 if (Scopes[Min].InDiag) break;
603 Min = Scopes[Min].ParentScope;
606 // Walk through all the jump sites, checking that they can trivially
607 // reach this label scope.
608 for (SmallVectorImpl<JumpScope>::iterator
609 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
610 unsigned Scope = I->first;
612 // Walk out the "scope chain" for this scope, looking for a scope
613 // we've marked reachable. For well-formed code this amortizes
614 // to O(JumpScopes.size() / Scopes.size()): we only iterate
615 // when we see something unmarked, and in well-formed code we
616 // mark everything we iterate past.
617 bool IsReachable = false;
619 if (Reachable.test(Scope)) {
620 // If we find something reachable, mark all the scopes we just
621 // walked through as reachable.
622 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
628 // Don't walk out if we've reached the top-level scope or we've
629 // gotten shallower than the shallowest reachable scope.
630 if (Scope == 0 || Scope < Min) break;
632 // Don't walk out through an out-diagnostic.
633 if (Scopes[Scope].OutDiag) break;
635 Scope = Scopes[Scope].ParentScope;
638 // Only diagnose if we didn't find something.
639 if (IsReachable) continue;
641 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
646 /// Return true if a particular error+note combination must be downgraded to a
647 /// warning in Microsoft mode.
648 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
649 return (JumpDiag == diag::err_goto_into_protected_scope &&
650 (InDiagNote == diag::note_protected_by_variable_init ||
651 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
654 /// Return true if a particular note should be downgraded to a compatibility
655 /// warning in C++11 mode.
656 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
657 return S.getLangOpts().CPlusPlus0x &&
658 InDiagNote == diag::note_protected_by_variable_non_pod;
661 /// Produce primary diagnostic for an indirect jump statement.
662 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
663 LabelDecl *Target, bool &Diagnosed) {
666 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
667 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
671 /// Produce note diagnostics for a jump into a protected scope.
672 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
673 assert(!ToScopes.empty());
674 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
675 if (Scopes[ToScopes[I]].InDiag)
676 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
679 /// Diagnose an indirect jump which is known to cross scopes.
680 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
683 unsigned TargetScope) {
684 assert(JumpScope != TargetScope);
686 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
687 bool Diagnosed = false;
689 // Walk out the scope chain until we reach the common ancestor.
690 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
691 if (Scopes[I].OutDiag) {
692 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
693 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
696 SmallVector<unsigned, 10> ToScopesCXX98Compat;
698 // Now walk into the scopes containing the label whose address was taken.
699 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
700 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
701 ToScopesCXX98Compat.push_back(I);
702 else if (Scopes[I].InDiag) {
703 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
704 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
707 // Diagnose this jump if it would be ill-formed in C++98.
708 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
709 S.Diag(Jump->getGotoLoc(),
710 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
711 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
712 NoteJumpIntoScopes(ToScopesCXX98Compat);
716 /// CheckJump - Validate that the specified jump statement is valid: that it is
717 /// jumping within or out of its current scope, not into a deeper one.
718 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
719 unsigned JumpDiagError, unsigned JumpDiagWarning,
720 unsigned JumpDiagCXX98Compat) {
721 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
722 unsigned FromScope = LabelAndGotoScopes[From];
724 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
725 unsigned ToScope = LabelAndGotoScopes[To];
727 // Common case: exactly the same scope, which is fine.
728 if (FromScope == ToScope) return;
730 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
732 // It's okay to jump out from a nested scope.
733 if (CommonScope == ToScope) return;
735 // Pull out (and reverse) any scopes we might need to diagnose skipping.
736 SmallVector<unsigned, 10> ToScopesCXX98Compat;
737 SmallVector<unsigned, 10> ToScopesError;
738 SmallVector<unsigned, 10> ToScopesWarning;
739 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
740 if (S.getLangOpts().MicrosoftMode && JumpDiagWarning != 0 &&
741 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
742 ToScopesWarning.push_back(I);
743 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
744 ToScopesCXX98Compat.push_back(I);
745 else if (Scopes[I].InDiag)
746 ToScopesError.push_back(I);
750 if (!ToScopesWarning.empty()) {
751 S.Diag(DiagLoc, JumpDiagWarning);
752 NoteJumpIntoScopes(ToScopesWarning);
756 if (!ToScopesError.empty()) {
757 S.Diag(DiagLoc, JumpDiagError);
758 NoteJumpIntoScopes(ToScopesError);
761 // Handle -Wc++98-compat warnings if the jump is well-formed.
762 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
763 S.Diag(DiagLoc, JumpDiagCXX98Compat);
764 NoteJumpIntoScopes(ToScopesCXX98Compat);
768 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
769 (void)JumpScopeChecker(Body, *this);