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/StmtCXX.h"
20 #include "clang/AST/StmtObjC.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 /// Permissive - True when recovering from errors, in which case precautions
36 /// are taken to handle incomplete scope information.
37 const bool Permissive;
39 /// GotoScope - This is a record that we use to keep track of all of the
40 /// scopes that are introduced by VLAs and other things that scope jumps like
41 /// gotos. This scope tree has nothing to do with the source scope tree,
42 /// because you can have multiple VLA scopes per compound statement, and most
43 /// compound statements don't introduce any scopes.
45 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
46 /// the parent scope is the function body.
49 /// InDiag - The note to emit if there is a jump into this scope.
52 /// OutDiag - The note to emit if there is an indirect jump out
53 /// of this scope. Direct jumps always clean up their current scope
54 /// in an orderly way.
57 /// Loc - Location to emit the diagnostic.
60 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
62 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
65 SmallVector<GotoScope, 48> Scopes;
66 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
67 SmallVector<Stmt*, 16> Jumps;
69 SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
70 SmallVector<LabelDecl*, 4> IndirectJumpTargets;
72 JumpScopeChecker(Stmt *Body, Sema &S);
74 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
75 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
76 unsigned &ParentScope);
77 void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
80 void VerifyIndirectJumps();
81 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
82 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
83 LabelDecl *Target, unsigned TargetScope);
84 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
85 unsigned JumpDiag, unsigned JumpDiagWarning,
86 unsigned JumpDiagCXX98Compat);
87 void CheckGotoStmt(GotoStmt *GS);
89 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
91 } // end anonymous namespace
93 #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
95 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
96 : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
97 // Add a scope entry for function scope.
98 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
100 // Build information for the top level compound statement, so that we have a
101 // defined scope record for every "goto" and label.
102 unsigned BodyParentScope = 0;
103 BuildScopeInformation(Body, BodyParentScope);
105 // Check that all jumps we saw are kosher.
107 VerifyIndirectJumps();
110 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
112 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
114 // Inner scopes are created after outer scopes and therefore have
117 assert(Scopes[B].ParentScope < B);
118 B = Scopes[B].ParentScope;
120 assert(Scopes[A].ParentScope < A);
121 A = Scopes[A].ParentScope;
127 typedef std::pair<unsigned,unsigned> ScopePair;
129 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
130 /// diagnostic that should be emitted if control goes over it. If not, return 0.
131 static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
132 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
134 unsigned OutDiag = 0;
136 if (VD->getType()->isVariablyModifiedType())
137 InDiag = diag::note_protected_by_vla;
139 if (VD->hasAttr<BlocksAttr>())
140 return ScopePair(diag::note_protected_by___block,
141 diag::note_exits___block);
143 if (VD->hasAttr<CleanupAttr>())
144 return ScopePair(diag::note_protected_by_cleanup,
145 diag::note_exits_cleanup);
147 if (VD->hasLocalStorage()) {
148 switch (VD->getType().isDestructedType()) {
149 case QualType::DK_objc_strong_lifetime:
150 return ScopePair(diag::note_protected_by_objc_strong_init,
151 diag::note_exits_objc_strong);
153 case QualType::DK_objc_weak_lifetime:
154 return ScopePair(diag::note_protected_by_objc_weak_init,
155 diag::note_exits_objc_weak);
157 case QualType::DK_cxx_destructor:
158 OutDiag = diag::note_exits_dtor;
161 case QualType::DK_none:
166 const Expr *Init = VD->getInit();
167 if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
168 // C++11 [stmt.dcl]p3:
169 // A program that jumps from a point where a variable with automatic
170 // storage duration is not in scope to a point where it is in scope
171 // is ill-formed unless the variable has scalar type, class type with
172 // a trivial default constructor and a trivial destructor, a
173 // cv-qualified version of one of these types, or an array of one of
174 // the preceding types and is declared without an initializer.
176 // C++03 [stmt.dcl.p3:
177 // A program that jumps from a point where a local variable
178 // with automatic storage duration is not in scope to a point
179 // where it is in scope is ill-formed unless the variable has
180 // POD type and is declared without an initializer.
182 InDiag = diag::note_protected_by_variable_init;
184 // For a variable of (array of) class type declared without an
185 // initializer, we will have call-style initialization and the initializer
186 // will be the CXXConstructExpr with no intervening nodes.
187 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
188 const CXXConstructorDecl *Ctor = CCE->getConstructor();
189 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
190 VD->getInitStyle() == VarDecl::CallInit) {
192 InDiag = diag::note_protected_by_variable_nontriv_destructor;
193 else if (!Ctor->getParent()->isPOD())
194 InDiag = diag::note_protected_by_variable_non_pod;
201 return ScopePair(InDiag, OutDiag);
204 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
205 if (TD->getUnderlyingType()->isVariablyModifiedType())
206 return ScopePair(isa<TypedefDecl>(TD)
207 ? diag::note_protected_by_vla_typedef
208 : diag::note_protected_by_vla_type_alias,
212 return ScopePair(0U, 0U);
215 /// \brief Build scope information for a declaration that is part of a DeclStmt.
216 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
217 // If this decl causes a new scope, push and switch to it.
218 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
219 if (Diags.first || Diags.second) {
220 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
222 ParentScope = Scopes.size()-1;
225 // If the decl has an initializer, walk it with the potentially new
226 // scope we just installed.
227 if (VarDecl *VD = dyn_cast<VarDecl>(D))
228 if (Expr *Init = VD->getInit())
229 BuildScopeInformation(Init, ParentScope);
232 /// \brief Build scope information for a captured block literal variables.
233 void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
234 const BlockDecl *BDecl,
235 unsigned &ParentScope) {
236 // exclude captured __block variables; there's no destructor
237 // associated with the block literal for them.
238 if (D->hasAttr<BlocksAttr>())
240 QualType T = D->getType();
241 QualType::DestructionKind destructKind = T.isDestructedType();
242 if (destructKind != QualType::DK_none) {
243 std::pair<unsigned,unsigned> Diags;
244 switch (destructKind) {
245 case QualType::DK_cxx_destructor:
246 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
247 diag::note_exits_block_captures_cxx_obj);
249 case QualType::DK_objc_strong_lifetime:
250 Diags = ScopePair(diag::note_enters_block_captures_strong,
251 diag::note_exits_block_captures_strong);
253 case QualType::DK_objc_weak_lifetime:
254 Diags = ScopePair(diag::note_enters_block_captures_weak,
255 diag::note_exits_block_captures_weak);
257 case QualType::DK_none:
258 llvm_unreachable("non-lifetime captured variable");
260 SourceLocation Loc = D->getLocation();
262 Loc = BDecl->getLocation();
263 Scopes.push_back(GotoScope(ParentScope,
264 Diags.first, Diags.second, Loc));
265 ParentScope = Scopes.size()-1;
269 /// BuildScopeInformation - The statements from CI to CE are known to form a
270 /// coherent VLA scope with a specified parent node. Walk through the
271 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
272 /// walking the AST as needed.
273 void JumpScopeChecker::BuildScopeInformation(Stmt *S,
274 unsigned &origParentScope) {
275 // If this is a statement, rather than an expression, scopes within it don't
276 // propagate out into the enclosing scope. Otherwise we have to worry
277 // about block literals, which have the lifetime of their enclosing statement.
278 unsigned independentParentScope = origParentScope;
279 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
280 ? origParentScope : independentParentScope);
282 unsigned StmtsToSkip = 0u;
284 // If we found a label, remember that it is in ParentScope scope.
285 switch (S->getStmtClass()) {
286 case Stmt::AddrLabelExprClass:
287 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
290 case Stmt::IndirectGotoStmtClass:
291 // "goto *&&lbl;" is a special case which we treat as equivalent
292 // to a normal goto. In addition, we don't calculate scope in the
293 // operand (to avoid recording the address-of-label use), which
294 // works only because of the restricted set of expressions which
295 // we detect as constant targets.
296 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
297 LabelAndGotoScopes[S] = ParentScope;
302 LabelAndGotoScopes[S] = ParentScope;
303 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
306 case Stmt::SwitchStmtClass:
307 // Evaluate the C++17 init stmt and condition variable
308 // before entering the scope of the switch statement.
309 if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
310 BuildScopeInformation(Init, ParentScope);
313 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
314 BuildScopeInformation(Var, ParentScope);
319 case Stmt::GotoStmtClass:
320 // Remember both what scope a goto is in as well as the fact that we have
321 // it. This makes the second scan not have to walk the AST again.
322 LabelAndGotoScopes[S] = ParentScope;
326 case Stmt::IfStmtClass: {
327 IfStmt *IS = cast<IfStmt>(S);
328 if (!(IS->isConstexpr() || IS->isObjCAvailabilityCheck()))
331 unsigned Diag = IS->isConstexpr() ? diag::note_protected_by_constexpr_if
332 : diag::note_protected_by_if_available;
334 if (VarDecl *Var = IS->getConditionVariable())
335 BuildScopeInformation(Var, ParentScope);
337 // Cannot jump into the middle of the condition.
338 unsigned NewParentScope = Scopes.size();
339 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
340 BuildScopeInformation(IS->getCond(), NewParentScope);
342 // Jumps into either arm of an 'if constexpr' are not allowed.
343 NewParentScope = Scopes.size();
344 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
345 BuildScopeInformation(IS->getThen(), NewParentScope);
346 if (Stmt *Else = IS->getElse()) {
347 NewParentScope = Scopes.size();
348 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
349 BuildScopeInformation(Else, NewParentScope);
354 case Stmt::CXXTryStmtClass: {
355 CXXTryStmt *TS = cast<CXXTryStmt>(S);
357 unsigned NewParentScope = Scopes.size();
358 Scopes.push_back(GotoScope(ParentScope,
359 diag::note_protected_by_cxx_try,
360 diag::note_exits_cxx_try,
361 TS->getSourceRange().getBegin()));
362 if (Stmt *TryBlock = TS->getTryBlock())
363 BuildScopeInformation(TryBlock, NewParentScope);
366 // Jump from the catch into the try is not allowed either.
367 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
368 CXXCatchStmt *CS = TS->getHandler(I);
369 unsigned NewParentScope = Scopes.size();
370 Scopes.push_back(GotoScope(ParentScope,
371 diag::note_protected_by_cxx_catch,
372 diag::note_exits_cxx_catch,
373 CS->getSourceRange().getBegin()));
374 BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
379 case Stmt::SEHTryStmtClass: {
380 SEHTryStmt *TS = cast<SEHTryStmt>(S);
382 unsigned NewParentScope = Scopes.size();
383 Scopes.push_back(GotoScope(ParentScope,
384 diag::note_protected_by_seh_try,
385 diag::note_exits_seh_try,
386 TS->getSourceRange().getBegin()));
387 if (Stmt *TryBlock = TS->getTryBlock())
388 BuildScopeInformation(TryBlock, NewParentScope);
391 // Jump from __except or __finally into the __try are not allowed either.
392 if (SEHExceptStmt *Except = TS->getExceptHandler()) {
393 unsigned NewParentScope = Scopes.size();
394 Scopes.push_back(GotoScope(ParentScope,
395 diag::note_protected_by_seh_except,
396 diag::note_exits_seh_except,
397 Except->getSourceRange().getBegin()));
398 BuildScopeInformation(Except->getBlock(), NewParentScope);
399 } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
400 unsigned NewParentScope = Scopes.size();
401 Scopes.push_back(GotoScope(ParentScope,
402 diag::note_protected_by_seh_finally,
403 diag::note_exits_seh_finally,
404 Finally->getSourceRange().getBegin()));
405 BuildScopeInformation(Finally->getBlock(), NewParentScope);
411 case Stmt::DeclStmtClass: {
412 // If this is a declstmt with a VLA definition, it defines a scope from here
413 // to the end of the containing context.
414 DeclStmt *DS = cast<DeclStmt>(S);
415 // The decl statement creates a scope if any of the decls in it are VLAs
416 // or have the cleanup attribute.
417 for (auto *I : DS->decls())
418 BuildScopeInformation(I, origParentScope);
422 case Stmt::ObjCAtTryStmtClass: {
423 // Disallow jumps into any part of an @try statement by pushing a scope and
424 // walking all sub-stmts in that scope.
425 ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
426 // Recursively walk the AST for the @try part.
428 unsigned NewParentScope = Scopes.size();
429 Scopes.push_back(GotoScope(ParentScope,
430 diag::note_protected_by_objc_try,
431 diag::note_exits_objc_try,
433 if (Stmt *TryPart = AT->getTryBody())
434 BuildScopeInformation(TryPart, NewParentScope);
437 // Jump from the catch to the finally or try is not valid.
438 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
439 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
440 unsigned NewParentScope = Scopes.size();
441 Scopes.push_back(GotoScope(ParentScope,
442 diag::note_protected_by_objc_catch,
443 diag::note_exits_objc_catch,
444 AC->getAtCatchLoc()));
445 // @catches are nested and it isn't
446 BuildScopeInformation(AC->getCatchBody(), NewParentScope);
449 // Jump from the finally to the try or catch is not valid.
450 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
451 unsigned NewParentScope = Scopes.size();
452 Scopes.push_back(GotoScope(ParentScope,
453 diag::note_protected_by_objc_finally,
454 diag::note_exits_objc_finally,
455 AF->getAtFinallyLoc()));
456 BuildScopeInformation(AF, NewParentScope);
462 case Stmt::ObjCAtSynchronizedStmtClass: {
463 // Disallow jumps into the protected statement of an @synchronized, but
464 // allow jumps into the object expression it protects.
465 ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
466 // Recursively walk the AST for the @synchronized object expr, it is
467 // evaluated in the normal scope.
468 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
470 // Recursively walk the AST for the @synchronized part, protected by a new
472 unsigned NewParentScope = Scopes.size();
473 Scopes.push_back(GotoScope(ParentScope,
474 diag::note_protected_by_objc_synchronized,
475 diag::note_exits_objc_synchronized,
476 AS->getAtSynchronizedLoc()));
477 BuildScopeInformation(AS->getSynchBody(), NewParentScope);
481 case Stmt::ObjCAutoreleasePoolStmtClass: {
482 // Disallow jumps into the protected statement of an @autoreleasepool.
483 ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
484 // Recursively walk the AST for the @autoreleasepool part, protected by a
486 unsigned NewParentScope = Scopes.size();
487 Scopes.push_back(GotoScope(ParentScope,
488 diag::note_protected_by_objc_autoreleasepool,
489 diag::note_exits_objc_autoreleasepool,
491 BuildScopeInformation(AS->getSubStmt(), NewParentScope);
495 case Stmt::ExprWithCleanupsClass: {
496 // Disallow jumps past full-expressions that use blocks with
497 // non-trivial cleanups of their captures. This is theoretically
498 // implementable but a lot of work which we haven't felt up to doing.
499 ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
500 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
501 const BlockDecl *BDecl = EWC->getObject(i);
502 for (const auto &CI : BDecl->captures()) {
503 VarDecl *variable = CI.getVariable();
504 BuildScopeInformation(variable, BDecl, origParentScope);
510 case Stmt::MaterializeTemporaryExprClass: {
511 // Disallow jumps out of scopes containing temporaries lifetime-extended to
512 // automatic storage duration.
513 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
514 if (MTE->getStorageDuration() == SD_Automatic) {
515 SmallVector<const Expr *, 4> CommaLHS;
516 SmallVector<SubobjectAdjustment, 4> Adjustments;
517 const Expr *ExtendedObject =
518 MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
519 CommaLHS, Adjustments);
520 if (ExtendedObject->getType().isDestructedType()) {
521 Scopes.push_back(GotoScope(ParentScope, 0,
522 diag::note_exits_temporary_dtor,
523 ExtendedObject->getExprLoc()));
524 origParentScope = Scopes.size()-1;
530 case Stmt::CaseStmtClass:
531 case Stmt::DefaultStmtClass:
532 case Stmt::LabelStmtClass:
533 LabelAndGotoScopes[S] = ParentScope;
540 for (Stmt *SubStmt : S->children()) {
548 // Cases, labels, and defaults aren't "scope parents". It's also
549 // important to handle these iteratively instead of recursively in
550 // order to avoid blowing out the stack.
553 if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt))
554 Next = SC->getSubStmt();
555 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
556 Next = LS->getSubStmt();
560 LabelAndGotoScopes[SubStmt] = ParentScope;
564 // Recursively walk the AST.
565 BuildScopeInformation(SubStmt, ParentScope);
569 /// VerifyJumps - Verify each element of the Jumps array to see if they are
570 /// valid, emitting diagnostics if not.
571 void JumpScopeChecker::VerifyJumps() {
572 while (!Jumps.empty()) {
573 Stmt *Jump = Jumps.pop_back_val();
576 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
577 // The label may not have a statement if it's coming from inline MS ASM.
578 if (GS->getLabel()->getStmt()) {
579 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
580 diag::err_goto_into_protected_scope,
581 diag::ext_goto_into_protected_scope,
582 diag::warn_cxx98_compat_goto_into_protected_scope);
588 // We only get indirect gotos here when they have a constant target.
589 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
590 LabelDecl *Target = IGS->getConstantTarget();
591 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
592 diag::err_goto_into_protected_scope,
593 diag::ext_goto_into_protected_scope,
594 diag::warn_cxx98_compat_goto_into_protected_scope);
598 SwitchStmt *SS = cast<SwitchStmt>(Jump);
599 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
600 SC = SC->getNextSwitchCase()) {
601 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
604 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
605 Loc = CS->getLocStart();
606 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
607 Loc = DS->getLocStart();
609 Loc = SC->getLocStart();
610 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
611 diag::warn_cxx98_compat_switch_into_protected_scope);
616 /// VerifyIndirectJumps - Verify whether any possible indirect jump
617 /// might cross a protection boundary. Unlike direct jumps, indirect
618 /// jumps count cleanups as protection boundaries: since there's no
619 /// way to know where the jump is going, we can't implicitly run the
620 /// right cleanups the way we can with direct jumps.
622 /// Thus, an indirect jump is "trivial" if it bypasses no
623 /// initializations and no teardowns. More formally, an indirect jump
624 /// from A to B is trivial if the path out from A to DCA(A,B) is
625 /// trivial and the path in from DCA(A,B) to B is trivial, where
626 /// DCA(A,B) is the deepest common ancestor of A and B.
627 /// Jump-triviality is transitive but asymmetric.
629 /// A path in is trivial if none of the entered scopes have an InDiag.
630 /// A path out is trivial is none of the exited scopes have an OutDiag.
632 /// Under these definitions, this function checks that the indirect
633 /// jump between A and B is trivial for every indirect goto statement A
634 /// and every label B whose address was taken in the function.
635 void JumpScopeChecker::VerifyIndirectJumps() {
636 if (IndirectJumps.empty()) return;
638 // If there aren't any address-of-label expressions in this function,
639 // complain about the first indirect goto.
640 if (IndirectJumpTargets.empty()) {
641 S.Diag(IndirectJumps[0]->getGotoLoc(),
642 diag::err_indirect_goto_without_addrlabel);
646 // Collect a single representative of every scope containing an
647 // indirect goto. For most code bases, this substantially cuts
648 // down on the number of jump sites we'll have to consider later.
649 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
650 SmallVector<JumpScope, 32> JumpScopes;
652 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
653 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
654 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
655 IndirectGotoStmt *IG = *I;
656 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
658 unsigned IGScope = LabelAndGotoScopes[IG];
659 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
660 if (!Entry) Entry = IG;
662 JumpScopes.reserve(JumpScopesMap.size());
663 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
664 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
665 JumpScopes.push_back(*I);
668 // Collect a single representative of every scope containing a
669 // label whose address was taken somewhere in the function.
670 // For most code bases, there will be only one such scope.
671 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
672 for (SmallVectorImpl<LabelDecl*>::iterator
673 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
675 LabelDecl *TheLabel = *I;
676 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
678 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
679 LabelDecl *&Target = TargetScopes[LabelScope];
680 if (!Target) Target = TheLabel;
683 // For each target scope, make sure it's trivially reachable from
684 // every scope containing a jump site.
686 // A path between scopes always consists of exitting zero or more
687 // scopes, then entering zero or more scopes. We build a set of
688 // of scopes S from which the target scope can be trivially
689 // entered, then verify that every jump scope can be trivially
690 // exitted to reach a scope in S.
691 llvm::BitVector Reachable(Scopes.size(), false);
692 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
693 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
694 unsigned TargetScope = TI->first;
695 LabelDecl *TargetLabel = TI->second;
699 // Mark all the enclosing scopes from which you can safely jump
700 // into the target scope. 'Min' will end up being the index of
701 // the shallowest such scope.
702 unsigned Min = TargetScope;
706 // Don't go beyond the outermost scope.
709 // Stop if we can't trivially enter the current scope.
710 if (Scopes[Min].InDiag) break;
712 Min = Scopes[Min].ParentScope;
715 // Walk through all the jump sites, checking that they can trivially
716 // reach this label scope.
717 for (SmallVectorImpl<JumpScope>::iterator
718 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
719 unsigned Scope = I->first;
721 // Walk out the "scope chain" for this scope, looking for a scope
722 // we've marked reachable. For well-formed code this amortizes
723 // to O(JumpScopes.size() / Scopes.size()): we only iterate
724 // when we see something unmarked, and in well-formed code we
725 // mark everything we iterate past.
726 bool IsReachable = false;
728 if (Reachable.test(Scope)) {
729 // If we find something reachable, mark all the scopes we just
730 // walked through as reachable.
731 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
737 // Don't walk out if we've reached the top-level scope or we've
738 // gotten shallower than the shallowest reachable scope.
739 if (Scope == 0 || Scope < Min) break;
741 // Don't walk out through an out-diagnostic.
742 if (Scopes[Scope].OutDiag) break;
744 Scope = Scopes[Scope].ParentScope;
747 // Only diagnose if we didn't find something.
748 if (IsReachable) continue;
750 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
755 /// Return true if a particular error+note combination must be downgraded to a
756 /// warning in Microsoft mode.
757 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
758 return (JumpDiag == diag::err_goto_into_protected_scope &&
759 (InDiagNote == diag::note_protected_by_variable_init ||
760 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
763 /// Return true if a particular note should be downgraded to a compatibility
764 /// warning in C++11 mode.
765 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
766 return S.getLangOpts().CPlusPlus11 &&
767 InDiagNote == diag::note_protected_by_variable_non_pod;
770 /// Produce primary diagnostic for an indirect jump statement.
771 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
772 LabelDecl *Target, bool &Diagnosed) {
775 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
776 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
780 /// Produce note diagnostics for a jump into a protected scope.
781 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
782 if (CHECK_PERMISSIVE(ToScopes.empty()))
784 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
785 if (Scopes[ToScopes[I]].InDiag)
786 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
789 /// Diagnose an indirect jump which is known to cross scopes.
790 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
793 unsigned TargetScope) {
794 if (CHECK_PERMISSIVE(JumpScope == TargetScope))
797 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
798 bool Diagnosed = false;
800 // Walk out the scope chain until we reach the common ancestor.
801 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
802 if (Scopes[I].OutDiag) {
803 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
804 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
807 SmallVector<unsigned, 10> ToScopesCXX98Compat;
809 // Now walk into the scopes containing the label whose address was taken.
810 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
811 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
812 ToScopesCXX98Compat.push_back(I);
813 else if (Scopes[I].InDiag) {
814 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
815 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
818 // Diagnose this jump if it would be ill-formed in C++98.
819 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
820 S.Diag(Jump->getGotoLoc(),
821 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
822 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
823 NoteJumpIntoScopes(ToScopesCXX98Compat);
827 /// CheckJump - Validate that the specified jump statement is valid: that it is
828 /// jumping within or out of its current scope, not into a deeper one.
829 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
830 unsigned JumpDiagError, unsigned JumpDiagWarning,
831 unsigned JumpDiagCXX98Compat) {
832 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
834 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
837 unsigned FromScope = LabelAndGotoScopes[From];
838 unsigned ToScope = LabelAndGotoScopes[To];
840 // Common case: exactly the same scope, which is fine.
841 if (FromScope == ToScope) return;
843 // Warn on gotos out of __finally blocks.
844 if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
845 // If FromScope > ToScope, FromScope is more nested and the jump goes to a
846 // less nested scope. Check if it crosses a __finally along the way.
847 for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
848 if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
849 S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally);
855 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
857 // It's okay to jump out from a nested scope.
858 if (CommonScope == ToScope) return;
860 // Pull out (and reverse) any scopes we might need to diagnose skipping.
861 SmallVector<unsigned, 10> ToScopesCXX98Compat;
862 SmallVector<unsigned, 10> ToScopesError;
863 SmallVector<unsigned, 10> ToScopesWarning;
864 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
865 if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
866 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
867 ToScopesWarning.push_back(I);
868 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
869 ToScopesCXX98Compat.push_back(I);
870 else if (Scopes[I].InDiag)
871 ToScopesError.push_back(I);
875 if (!ToScopesWarning.empty()) {
876 S.Diag(DiagLoc, JumpDiagWarning);
877 NoteJumpIntoScopes(ToScopesWarning);
881 if (!ToScopesError.empty()) {
882 S.Diag(DiagLoc, JumpDiagError);
883 NoteJumpIntoScopes(ToScopesError);
886 // Handle -Wc++98-compat warnings if the jump is well-formed.
887 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
888 S.Diag(DiagLoc, JumpDiagCXX98Compat);
889 NoteJumpIntoScopes(ToScopesCXX98Compat);
893 void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
894 if (GS->getLabel()->isMSAsmLabel()) {
895 S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
896 << GS->getLabel()->getIdentifier();
897 S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
898 << GS->getLabel()->getIdentifier();
902 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
903 (void)JumpScopeChecker(Body, *this);