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 // Disallow jumps past full-expressions that use blocks with
458 // non-trivial cleanups of their captures. This is theoretically
459 // implementable but a lot of work which we haven't felt up to doing.
460 if (ExprWithCleanups
*EWC
= dyn_cast
<ExprWithCleanups
>(SubStmt
)) {
461 for (unsigned i
= 0, e
= EWC
->getNumObjects(); i
!= e
; ++i
) {
462 const BlockDecl
*BDecl
= EWC
->getObject(i
);
463 for (BlockDecl::capture_const_iterator ci
= BDecl
->capture_begin(),
464 ce
= BDecl
->capture_end(); ci
!= ce
; ++ci
) {
465 VarDecl
*variable
= ci
->getVariable();
466 BuildScopeInformation(variable
, BDecl
, ParentScope
);
471 // Recursively walk the AST.
472 BuildScopeInformation(SubStmt
, ParentScope
);
476 /// VerifyJumps - Verify each element of the Jumps array to see if they are
477 /// valid, emitting diagnostics if not.
478 void JumpScopeChecker::VerifyJumps() {
479 while (!Jumps
.empty()) {
480 Stmt
*Jump
= Jumps
.pop_back_val();
483 if (GotoStmt
*GS
= dyn_cast
<GotoStmt
>(Jump
)) {
484 CheckJump(GS
, GS
->getLabel()->getStmt(), GS
->getGotoLoc(),
485 diag::err_goto_into_protected_scope
,
486 diag::warn_goto_into_protected_scope
,
487 diag::warn_cxx98_compat_goto_into_protected_scope
);
491 // We only get indirect gotos here when they have a constant target.
492 if (IndirectGotoStmt
*IGS
= dyn_cast
<IndirectGotoStmt
>(Jump
)) {
493 LabelDecl
*Target
= IGS
->getConstantTarget();
494 CheckJump(IGS
, Target
->getStmt(), IGS
->getGotoLoc(),
495 diag::err_goto_into_protected_scope
,
496 diag::warn_goto_into_protected_scope
,
497 diag::warn_cxx98_compat_goto_into_protected_scope
);
501 SwitchStmt
*SS
= cast
<SwitchStmt
>(Jump
);
502 for (SwitchCase
*SC
= SS
->getSwitchCaseList(); SC
;
503 SC
= SC
->getNextSwitchCase()) {
504 assert(LabelAndGotoScopes
.count(SC
) && "Case not visited?");
505 CheckJump(SS
, SC
, SC
->getLocStart(),
506 diag::err_switch_into_protected_scope
, 0,
507 diag::warn_cxx98_compat_switch_into_protected_scope
);
512 /// VerifyIndirectJumps - Verify whether any possible indirect jump
513 /// might cross a protection boundary. Unlike direct jumps, indirect
514 /// jumps count cleanups as protection boundaries: since there's no
515 /// way to know where the jump is going, we can't implicitly run the
516 /// right cleanups the way we can with direct jumps.
518 /// Thus, an indirect jump is "trivial" if it bypasses no
519 /// initializations and no teardowns. More formally, an indirect jump
520 /// from A to B is trivial if the path out from A to DCA(A,B) is
521 /// trivial and the path in from DCA(A,B) to B is trivial, where
522 /// DCA(A,B) is the deepest common ancestor of A and B.
523 /// Jump-triviality is transitive but asymmetric.
525 /// A path in is trivial if none of the entered scopes have an InDiag.
526 /// A path out is trivial is none of the exited scopes have an OutDiag.
528 /// Under these definitions, this function checks that the indirect
529 /// jump between A and B is trivial for every indirect goto statement A
530 /// and every label B whose address was taken in the function.
531 void JumpScopeChecker::VerifyIndirectJumps() {
532 if (IndirectJumps
.empty()) return;
534 // If there aren't any address-of-label expressions in this function,
535 // complain about the first indirect goto.
536 if (IndirectJumpTargets
.empty()) {
537 S
.Diag(IndirectJumps
[0]->getGotoLoc(),
538 diag::err_indirect_goto_without_addrlabel
);
542 // Collect a single representative of every scope containing an
543 // indirect goto. For most code bases, this substantially cuts
544 // down on the number of jump sites we'll have to consider later.
545 typedef std::pair
<unsigned, IndirectGotoStmt
*> JumpScope
;
546 SmallVector
<JumpScope
, 32> JumpScopes
;
548 llvm::DenseMap
<unsigned, IndirectGotoStmt
*> JumpScopesMap
;
549 for (SmallVectorImpl
<IndirectGotoStmt
*>::iterator
550 I
= IndirectJumps
.begin(), E
= IndirectJumps
.end(); I
!= E
; ++I
) {
551 IndirectGotoStmt
*IG
= *I
;
552 assert(LabelAndGotoScopes
.count(IG
) &&
553 "indirect jump didn't get added to scopes?");
554 unsigned IGScope
= LabelAndGotoScopes
[IG
];
555 IndirectGotoStmt
*&Entry
= JumpScopesMap
[IGScope
];
556 if (!Entry
) Entry
= IG
;
558 JumpScopes
.reserve(JumpScopesMap
.size());
559 for (llvm::DenseMap
<unsigned, IndirectGotoStmt
*>::iterator
560 I
= JumpScopesMap
.begin(), E
= JumpScopesMap
.end(); I
!= E
; ++I
)
561 JumpScopes
.push_back(*I
);
564 // Collect a single representative of every scope containing a
565 // label whose address was taken somewhere in the function.
566 // For most code bases, there will be only one such scope.
567 llvm::DenseMap
<unsigned, LabelDecl
*> TargetScopes
;
568 for (SmallVectorImpl
<LabelDecl
*>::iterator
569 I
= IndirectJumpTargets
.begin(), E
= IndirectJumpTargets
.end();
571 LabelDecl
*TheLabel
= *I
;
572 assert(LabelAndGotoScopes
.count(TheLabel
->getStmt()) &&
573 "Referenced label didn't get added to scopes?");
574 unsigned LabelScope
= LabelAndGotoScopes
[TheLabel
->getStmt()];
575 LabelDecl
*&Target
= TargetScopes
[LabelScope
];
576 if (!Target
) Target
= TheLabel
;
579 // For each target scope, make sure it's trivially reachable from
580 // every scope containing a jump site.
582 // A path between scopes always consists of exitting zero or more
583 // scopes, then entering zero or more scopes. We build a set of
584 // of scopes S from which the target scope can be trivially
585 // entered, then verify that every jump scope can be trivially
586 // exitted to reach a scope in S.
587 llvm::BitVector
Reachable(Scopes
.size(), false);
588 for (llvm::DenseMap
<unsigned,LabelDecl
*>::iterator
589 TI
= TargetScopes
.begin(), TE
= TargetScopes
.end(); TI
!= TE
; ++TI
) {
590 unsigned TargetScope
= TI
->first
;
591 LabelDecl
*TargetLabel
= TI
->second
;
595 // Mark all the enclosing scopes from which you can safely jump
596 // into the target scope. 'Min' will end up being the index of
597 // the shallowest such scope.
598 unsigned Min
= TargetScope
;
602 // Don't go beyond the outermost scope.
605 // Stop if we can't trivially enter the current scope.
606 if (Scopes
[Min
].InDiag
) break;
608 Min
= Scopes
[Min
].ParentScope
;
611 // Walk through all the jump sites, checking that they can trivially
612 // reach this label scope.
613 for (SmallVectorImpl
<JumpScope
>::iterator
614 I
= JumpScopes
.begin(), E
= JumpScopes
.end(); I
!= E
; ++I
) {
615 unsigned Scope
= I
->first
;
617 // Walk out the "scope chain" for this scope, looking for a scope
618 // we've marked reachable. For well-formed code this amortizes
619 // to O(JumpScopes.size() / Scopes.size()): we only iterate
620 // when we see something unmarked, and in well-formed code we
621 // mark everything we iterate past.
622 bool IsReachable
= false;
624 if (Reachable
.test(Scope
)) {
625 // If we find something reachable, mark all the scopes we just
626 // walked through as reachable.
627 for (unsigned S
= I
->first
; S
!= Scope
; S
= Scopes
[S
].ParentScope
)
633 // Don't walk out if we've reached the top-level scope or we've
634 // gotten shallower than the shallowest reachable scope.
635 if (Scope
== 0 || Scope
< Min
) break;
637 // Don't walk out through an out-diagnostic.
638 if (Scopes
[Scope
].OutDiag
) break;
640 Scope
= Scopes
[Scope
].ParentScope
;
643 // Only diagnose if we didn't find something.
644 if (IsReachable
) continue;
646 DiagnoseIndirectJump(I
->second
, I
->first
, TargetLabel
, TargetScope
);
651 /// Return true if a particular error+note combination must be downgraded to a
652 /// warning in Microsoft mode.
653 static bool IsMicrosoftJumpWarning(unsigned JumpDiag
, unsigned InDiagNote
) {
654 return (JumpDiag
== diag::err_goto_into_protected_scope
&&
655 (InDiagNote
== diag::note_protected_by_variable_init
||
656 InDiagNote
== diag::note_protected_by_variable_nontriv_destructor
));
659 /// Return true if a particular note should be downgraded to a compatibility
660 /// warning in C++11 mode.
661 static bool IsCXX98CompatWarning(Sema
&S
, unsigned InDiagNote
) {
662 return S
.getLangOpts().CPlusPlus0x
&&
663 InDiagNote
== diag::note_protected_by_variable_non_pod
;
666 /// Produce primary diagnostic for an indirect jump statement.
667 static void DiagnoseIndirectJumpStmt(Sema
&S
, IndirectGotoStmt
*Jump
,
668 LabelDecl
*Target
, bool &Diagnosed
) {
671 S
.Diag(Jump
->getGotoLoc(), diag::err_indirect_goto_in_protected_scope
);
672 S
.Diag(Target
->getStmt()->getIdentLoc(), diag::note_indirect_goto_target
);
676 /// Produce note diagnostics for a jump into a protected scope.
677 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef
<unsigned> ToScopes
) {
678 assert(!ToScopes
.empty());
679 for (unsigned I
= 0, E
= ToScopes
.size(); I
!= E
; ++I
)
680 if (Scopes
[ToScopes
[I
]].InDiag
)
681 S
.Diag(Scopes
[ToScopes
[I
]].Loc
, Scopes
[ToScopes
[I
]].InDiag
);
684 /// Diagnose an indirect jump which is known to cross scopes.
685 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt
*Jump
,
688 unsigned TargetScope
) {
689 assert(JumpScope
!= TargetScope
);
691 unsigned Common
= GetDeepestCommonScope(JumpScope
, TargetScope
);
692 bool Diagnosed
= false;
694 // Walk out the scope chain until we reach the common ancestor.
695 for (unsigned I
= JumpScope
; I
!= Common
; I
= Scopes
[I
].ParentScope
)
696 if (Scopes
[I
].OutDiag
) {
697 DiagnoseIndirectJumpStmt(S
, Jump
, Target
, Diagnosed
);
698 S
.Diag(Scopes
[I
].Loc
, Scopes
[I
].OutDiag
);
701 SmallVector
<unsigned, 10> ToScopesCXX98Compat
;
703 // Now walk into the scopes containing the label whose address was taken.
704 for (unsigned I
= TargetScope
; I
!= Common
; I
= Scopes
[I
].ParentScope
)
705 if (IsCXX98CompatWarning(S
, Scopes
[I
].InDiag
))
706 ToScopesCXX98Compat
.push_back(I
);
707 else if (Scopes
[I
].InDiag
) {
708 DiagnoseIndirectJumpStmt(S
, Jump
, Target
, Diagnosed
);
709 S
.Diag(Scopes
[I
].Loc
, Scopes
[I
].InDiag
);
712 // Diagnose this jump if it would be ill-formed in C++98.
713 if (!Diagnosed
&& !ToScopesCXX98Compat
.empty()) {
714 S
.Diag(Jump
->getGotoLoc(),
715 diag::warn_cxx98_compat_indirect_goto_in_protected_scope
);
716 S
.Diag(Target
->getStmt()->getIdentLoc(), diag::note_indirect_goto_target
);
717 NoteJumpIntoScopes(ToScopesCXX98Compat
);
721 /// CheckJump - Validate that the specified jump statement is valid: that it is
722 /// jumping within or out of its current scope, not into a deeper one.
723 void JumpScopeChecker::CheckJump(Stmt
*From
, Stmt
*To
, SourceLocation DiagLoc
,
724 unsigned JumpDiagError
, unsigned JumpDiagWarning
,
725 unsigned JumpDiagCXX98Compat
) {
726 assert(LabelAndGotoScopes
.count(From
) && "Jump didn't get added to scopes?");
727 unsigned FromScope
= LabelAndGotoScopes
[From
];
729 assert(LabelAndGotoScopes
.count(To
) && "Jump didn't get added to scopes?");
730 unsigned ToScope
= LabelAndGotoScopes
[To
];
732 // Common case: exactly the same scope, which is fine.
733 if (FromScope
== ToScope
) return;
735 unsigned CommonScope
= GetDeepestCommonScope(FromScope
, ToScope
);
737 // It's okay to jump out from a nested scope.
738 if (CommonScope
== ToScope
) return;
740 // Pull out (and reverse) any scopes we might need to diagnose skipping.
741 SmallVector
<unsigned, 10> ToScopesCXX98Compat
;
742 SmallVector
<unsigned, 10> ToScopesError
;
743 SmallVector
<unsigned, 10> ToScopesWarning
;
744 for (unsigned I
= ToScope
; I
!= CommonScope
; I
= Scopes
[I
].ParentScope
) {
745 if (S
.getLangOpts().MicrosoftMode
&& JumpDiagWarning
!= 0 &&
746 IsMicrosoftJumpWarning(JumpDiagError
, Scopes
[I
].InDiag
))
747 ToScopesWarning
.push_back(I
);
748 else if (IsCXX98CompatWarning(S
, Scopes
[I
].InDiag
))
749 ToScopesCXX98Compat
.push_back(I
);
750 else if (Scopes
[I
].InDiag
)
751 ToScopesError
.push_back(I
);
755 if (!ToScopesWarning
.empty()) {
756 S
.Diag(DiagLoc
, JumpDiagWarning
);
757 NoteJumpIntoScopes(ToScopesWarning
);
761 if (!ToScopesError
.empty()) {
762 S
.Diag(DiagLoc
, JumpDiagError
);
763 NoteJumpIntoScopes(ToScopesError
);
766 // Handle -Wc++98-compat warnings if the jump is well-formed.
767 if (ToScopesError
.empty() && !ToScopesCXX98Compat
.empty()) {
768 S
.Diag(DiagLoc
, JumpDiagCXX98Compat
);
769 NoteJumpIntoScopes(ToScopesCXX98Compat
);
773 void Sema::DiagnoseInvalidJumps(Stmt
*Body
) {
774 (void)JumpScopeChecker(Body
, *this);