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_nontrivial_c_struct:
158 return ScopePair(diag::note_protected_by_non_trivial_c_struct_init,
159 diag::note_exits_dtor);
161 case QualType::DK_cxx_destructor:
162 OutDiag = diag::note_exits_dtor;
165 case QualType::DK_none:
170 const Expr *Init = VD->getInit();
171 if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
172 // C++11 [stmt.dcl]p3:
173 // A program that jumps from a point where a variable with automatic
174 // storage duration is not in scope to a point where it is in scope
175 // is ill-formed unless the variable has scalar type, class type with
176 // a trivial default constructor and a trivial destructor, a
177 // cv-qualified version of one of these types, or an array of one of
178 // the preceding types and is declared without an initializer.
180 // C++03 [stmt.dcl.p3:
181 // A program that jumps from a point where a local variable
182 // with automatic storage duration is not in scope to a point
183 // where it is in scope is ill-formed unless the variable has
184 // POD type and is declared without an initializer.
186 InDiag = diag::note_protected_by_variable_init;
188 // For a variable of (array of) class type declared without an
189 // initializer, we will have call-style initialization and the initializer
190 // will be the CXXConstructExpr with no intervening nodes.
191 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
192 const CXXConstructorDecl *Ctor = CCE->getConstructor();
193 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
194 VD->getInitStyle() == VarDecl::CallInit) {
196 InDiag = diag::note_protected_by_variable_nontriv_destructor;
197 else if (!Ctor->getParent()->isPOD())
198 InDiag = diag::note_protected_by_variable_non_pod;
205 return ScopePair(InDiag, OutDiag);
208 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
209 if (TD->getUnderlyingType()->isVariablyModifiedType())
210 return ScopePair(isa<TypedefDecl>(TD)
211 ? diag::note_protected_by_vla_typedef
212 : diag::note_protected_by_vla_type_alias,
216 return ScopePair(0U, 0U);
219 /// 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, 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 /// 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_nontrivial_c_struct:
262 Diags = ScopePair(diag::note_enters_block_captures_non_trivial_c_struct,
263 diag::note_exits_block_captures_non_trivial_c_struct);
265 case QualType::DK_none:
266 llvm_unreachable("non-lifetime captured variable");
268 SourceLocation Loc = D->getLocation();
270 Loc = BDecl->getLocation();
271 Scopes.push_back(GotoScope(ParentScope,
272 Diags.first, Diags.second, Loc));
273 ParentScope = Scopes.size()-1;
277 /// BuildScopeInformation - The statements from CI to CE are known to form a
278 /// coherent VLA scope with a specified parent node. Walk through the
279 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
280 /// walking the AST as needed.
281 void JumpScopeChecker::BuildScopeInformation(Stmt *S,
282 unsigned &origParentScope) {
283 // If this is a statement, rather than an expression, scopes within it don't
284 // propagate out into the enclosing scope. Otherwise we have to worry
285 // about block literals, which have the lifetime of their enclosing statement.
286 unsigned independentParentScope = origParentScope;
287 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
288 ? origParentScope : independentParentScope);
290 unsigned StmtsToSkip = 0u;
292 // If we found a label, remember that it is in ParentScope scope.
293 switch (S->getStmtClass()) {
294 case Stmt::AddrLabelExprClass:
295 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
298 case Stmt::ObjCForCollectionStmtClass: {
299 auto *CS = cast<ObjCForCollectionStmt>(S);
300 unsigned Diag = diag::note_protected_by_objc_fast_enumeration;
301 unsigned NewParentScope = Scopes.size();
302 Scopes.push_back(GotoScope(ParentScope, Diag, 0, S->getLocStart()));
303 BuildScopeInformation(CS->getBody(), NewParentScope);
307 case Stmt::IndirectGotoStmtClass:
308 // "goto *&&lbl;" is a special case which we treat as equivalent
309 // to a normal goto. In addition, we don't calculate scope in the
310 // operand (to avoid recording the address-of-label use), which
311 // works only because of the restricted set of expressions which
312 // we detect as constant targets.
313 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
314 LabelAndGotoScopes[S] = ParentScope;
319 LabelAndGotoScopes[S] = ParentScope;
320 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
323 case Stmt::SwitchStmtClass:
324 // Evaluate the C++17 init stmt and condition variable
325 // before entering the scope of the switch statement.
326 if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
327 BuildScopeInformation(Init, ParentScope);
330 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
331 BuildScopeInformation(Var, ParentScope);
336 case Stmt::GotoStmtClass:
337 // Remember both what scope a goto is in as well as the fact that we have
338 // it. This makes the second scan not have to walk the AST again.
339 LabelAndGotoScopes[S] = ParentScope;
343 case Stmt::IfStmtClass: {
344 IfStmt *IS = cast<IfStmt>(S);
345 if (!(IS->isConstexpr() || IS->isObjCAvailabilityCheck()))
348 unsigned Diag = IS->isConstexpr() ? diag::note_protected_by_constexpr_if
349 : diag::note_protected_by_if_available;
351 if (VarDecl *Var = IS->getConditionVariable())
352 BuildScopeInformation(Var, ParentScope);
354 // Cannot jump into the middle of the condition.
355 unsigned NewParentScope = Scopes.size();
356 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
357 BuildScopeInformation(IS->getCond(), NewParentScope);
359 // Jumps into either arm of an 'if constexpr' are not allowed.
360 NewParentScope = Scopes.size();
361 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
362 BuildScopeInformation(IS->getThen(), NewParentScope);
363 if (Stmt *Else = IS->getElse()) {
364 NewParentScope = Scopes.size();
365 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
366 BuildScopeInformation(Else, NewParentScope);
371 case Stmt::CXXTryStmtClass: {
372 CXXTryStmt *TS = cast<CXXTryStmt>(S);
374 unsigned NewParentScope = Scopes.size();
375 Scopes.push_back(GotoScope(ParentScope,
376 diag::note_protected_by_cxx_try,
377 diag::note_exits_cxx_try,
378 TS->getSourceRange().getBegin()));
379 if (Stmt *TryBlock = TS->getTryBlock())
380 BuildScopeInformation(TryBlock, NewParentScope);
383 // Jump from the catch into the try is not allowed either.
384 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
385 CXXCatchStmt *CS = TS->getHandler(I);
386 unsigned NewParentScope = Scopes.size();
387 Scopes.push_back(GotoScope(ParentScope,
388 diag::note_protected_by_cxx_catch,
389 diag::note_exits_cxx_catch,
390 CS->getSourceRange().getBegin()));
391 BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
396 case Stmt::SEHTryStmtClass: {
397 SEHTryStmt *TS = cast<SEHTryStmt>(S);
399 unsigned NewParentScope = Scopes.size();
400 Scopes.push_back(GotoScope(ParentScope,
401 diag::note_protected_by_seh_try,
402 diag::note_exits_seh_try,
403 TS->getSourceRange().getBegin()));
404 if (Stmt *TryBlock = TS->getTryBlock())
405 BuildScopeInformation(TryBlock, NewParentScope);
408 // Jump from __except or __finally into the __try are not allowed either.
409 if (SEHExceptStmt *Except = TS->getExceptHandler()) {
410 unsigned NewParentScope = Scopes.size();
411 Scopes.push_back(GotoScope(ParentScope,
412 diag::note_protected_by_seh_except,
413 diag::note_exits_seh_except,
414 Except->getSourceRange().getBegin()));
415 BuildScopeInformation(Except->getBlock(), NewParentScope);
416 } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
417 unsigned NewParentScope = Scopes.size();
418 Scopes.push_back(GotoScope(ParentScope,
419 diag::note_protected_by_seh_finally,
420 diag::note_exits_seh_finally,
421 Finally->getSourceRange().getBegin()));
422 BuildScopeInformation(Finally->getBlock(), NewParentScope);
428 case Stmt::DeclStmtClass: {
429 // If this is a declstmt with a VLA definition, it defines a scope from here
430 // to the end of the containing context.
431 DeclStmt *DS = cast<DeclStmt>(S);
432 // The decl statement creates a scope if any of the decls in it are VLAs
433 // or have the cleanup attribute.
434 for (auto *I : DS->decls())
435 BuildScopeInformation(I, origParentScope);
439 case Stmt::ObjCAtTryStmtClass: {
440 // Disallow jumps into any part of an @try statement by pushing a scope and
441 // walking all sub-stmts in that scope.
442 ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
443 // Recursively walk the AST for the @try part.
445 unsigned NewParentScope = Scopes.size();
446 Scopes.push_back(GotoScope(ParentScope,
447 diag::note_protected_by_objc_try,
448 diag::note_exits_objc_try,
450 if (Stmt *TryPart = AT->getTryBody())
451 BuildScopeInformation(TryPart, NewParentScope);
454 // Jump from the catch to the finally or try is not valid.
455 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
456 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
457 unsigned NewParentScope = Scopes.size();
458 Scopes.push_back(GotoScope(ParentScope,
459 diag::note_protected_by_objc_catch,
460 diag::note_exits_objc_catch,
461 AC->getAtCatchLoc()));
462 // @catches are nested and it isn't
463 BuildScopeInformation(AC->getCatchBody(), NewParentScope);
466 // Jump from the finally to the try or catch is not valid.
467 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
468 unsigned NewParentScope = Scopes.size();
469 Scopes.push_back(GotoScope(ParentScope,
470 diag::note_protected_by_objc_finally,
471 diag::note_exits_objc_finally,
472 AF->getAtFinallyLoc()));
473 BuildScopeInformation(AF, NewParentScope);
479 case Stmt::ObjCAtSynchronizedStmtClass: {
480 // Disallow jumps into the protected statement of an @synchronized, but
481 // allow jumps into the object expression it protects.
482 ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
483 // Recursively walk the AST for the @synchronized object expr, it is
484 // evaluated in the normal scope.
485 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
487 // Recursively walk the AST for the @synchronized part, protected by a new
489 unsigned NewParentScope = Scopes.size();
490 Scopes.push_back(GotoScope(ParentScope,
491 diag::note_protected_by_objc_synchronized,
492 diag::note_exits_objc_synchronized,
493 AS->getAtSynchronizedLoc()));
494 BuildScopeInformation(AS->getSynchBody(), NewParentScope);
498 case Stmt::ObjCAutoreleasePoolStmtClass: {
499 // Disallow jumps into the protected statement of an @autoreleasepool.
500 ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
501 // Recursively walk the AST for the @autoreleasepool part, protected by a
503 unsigned NewParentScope = Scopes.size();
504 Scopes.push_back(GotoScope(ParentScope,
505 diag::note_protected_by_objc_autoreleasepool,
506 diag::note_exits_objc_autoreleasepool,
508 BuildScopeInformation(AS->getSubStmt(), NewParentScope);
512 case Stmt::ExprWithCleanupsClass: {
513 // Disallow jumps past full-expressions that use blocks with
514 // non-trivial cleanups of their captures. This is theoretically
515 // implementable but a lot of work which we haven't felt up to doing.
516 ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
517 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
518 const BlockDecl *BDecl = EWC->getObject(i);
519 for (const auto &CI : BDecl->captures()) {
520 VarDecl *variable = CI.getVariable();
521 BuildScopeInformation(variable, BDecl, origParentScope);
527 case Stmt::MaterializeTemporaryExprClass: {
528 // Disallow jumps out of scopes containing temporaries lifetime-extended to
529 // automatic storage duration.
530 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
531 if (MTE->getStorageDuration() == SD_Automatic) {
532 SmallVector<const Expr *, 4> CommaLHS;
533 SmallVector<SubobjectAdjustment, 4> Adjustments;
534 const Expr *ExtendedObject =
535 MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
536 CommaLHS, Adjustments);
537 if (ExtendedObject->getType().isDestructedType()) {
538 Scopes.push_back(GotoScope(ParentScope, 0,
539 diag::note_exits_temporary_dtor,
540 ExtendedObject->getExprLoc()));
541 origParentScope = Scopes.size()-1;
547 case Stmt::CaseStmtClass:
548 case Stmt::DefaultStmtClass:
549 case Stmt::LabelStmtClass:
550 LabelAndGotoScopes[S] = ParentScope;
557 for (Stmt *SubStmt : S->children()) {
565 // Cases, labels, and defaults aren't "scope parents". It's also
566 // important to handle these iteratively instead of recursively in
567 // order to avoid blowing out the stack.
570 if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt))
571 Next = SC->getSubStmt();
572 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
573 Next = LS->getSubStmt();
577 LabelAndGotoScopes[SubStmt] = ParentScope;
581 // Recursively walk the AST.
582 BuildScopeInformation(SubStmt, ParentScope);
586 /// VerifyJumps - Verify each element of the Jumps array to see if they are
587 /// valid, emitting diagnostics if not.
588 void JumpScopeChecker::VerifyJumps() {
589 while (!Jumps.empty()) {
590 Stmt *Jump = Jumps.pop_back_val();
593 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
594 // The label may not have a statement if it's coming from inline MS ASM.
595 if (GS->getLabel()->getStmt()) {
596 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
597 diag::err_goto_into_protected_scope,
598 diag::ext_goto_into_protected_scope,
599 diag::warn_cxx98_compat_goto_into_protected_scope);
605 // We only get indirect gotos here when they have a constant target.
606 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
607 LabelDecl *Target = IGS->getConstantTarget();
608 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
609 diag::err_goto_into_protected_scope,
610 diag::ext_goto_into_protected_scope,
611 diag::warn_cxx98_compat_goto_into_protected_scope);
615 SwitchStmt *SS = cast<SwitchStmt>(Jump);
616 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
617 SC = SC->getNextSwitchCase()) {
618 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
621 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
622 Loc = CS->getLocStart();
623 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
624 Loc = DS->getLocStart();
626 Loc = SC->getLocStart();
627 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
628 diag::warn_cxx98_compat_switch_into_protected_scope);
633 /// VerifyIndirectJumps - Verify whether any possible indirect jump
634 /// might cross a protection boundary. Unlike direct jumps, indirect
635 /// jumps count cleanups as protection boundaries: since there's no
636 /// way to know where the jump is going, we can't implicitly run the
637 /// right cleanups the way we can with direct jumps.
639 /// Thus, an indirect jump is "trivial" if it bypasses no
640 /// initializations and no teardowns. More formally, an indirect jump
641 /// from A to B is trivial if the path out from A to DCA(A,B) is
642 /// trivial and the path in from DCA(A,B) to B is trivial, where
643 /// DCA(A,B) is the deepest common ancestor of A and B.
644 /// Jump-triviality is transitive but asymmetric.
646 /// A path in is trivial if none of the entered scopes have an InDiag.
647 /// A path out is trivial is none of the exited scopes have an OutDiag.
649 /// Under these definitions, this function checks that the indirect
650 /// jump between A and B is trivial for every indirect goto statement A
651 /// and every label B whose address was taken in the function.
652 void JumpScopeChecker::VerifyIndirectJumps() {
653 if (IndirectJumps.empty()) return;
655 // If there aren't any address-of-label expressions in this function,
656 // complain about the first indirect goto.
657 if (IndirectJumpTargets.empty()) {
658 S.Diag(IndirectJumps[0]->getGotoLoc(),
659 diag::err_indirect_goto_without_addrlabel);
663 // Collect a single representative of every scope containing an
664 // indirect goto. For most code bases, this substantially cuts
665 // down on the number of jump sites we'll have to consider later.
666 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
667 SmallVector<JumpScope, 32> JumpScopes;
669 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
670 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
671 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
672 IndirectGotoStmt *IG = *I;
673 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
675 unsigned IGScope = LabelAndGotoScopes[IG];
676 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
677 if (!Entry) Entry = IG;
679 JumpScopes.reserve(JumpScopesMap.size());
680 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
681 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
682 JumpScopes.push_back(*I);
685 // Collect a single representative of every scope containing a
686 // label whose address was taken somewhere in the function.
687 // For most code bases, there will be only one such scope.
688 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
689 for (SmallVectorImpl<LabelDecl*>::iterator
690 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
692 LabelDecl *TheLabel = *I;
693 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
695 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
696 LabelDecl *&Target = TargetScopes[LabelScope];
697 if (!Target) Target = TheLabel;
700 // For each target scope, make sure it's trivially reachable from
701 // every scope containing a jump site.
703 // A path between scopes always consists of exitting zero or more
704 // scopes, then entering zero or more scopes. We build a set of
705 // of scopes S from which the target scope can be trivially
706 // entered, then verify that every jump scope can be trivially
707 // exitted to reach a scope in S.
708 llvm::BitVector Reachable(Scopes.size(), false);
709 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
710 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
711 unsigned TargetScope = TI->first;
712 LabelDecl *TargetLabel = TI->second;
716 // Mark all the enclosing scopes from which you can safely jump
717 // into the target scope. 'Min' will end up being the index of
718 // the shallowest such scope.
719 unsigned Min = TargetScope;
723 // Don't go beyond the outermost scope.
726 // Stop if we can't trivially enter the current scope.
727 if (Scopes[Min].InDiag) break;
729 Min = Scopes[Min].ParentScope;
732 // Walk through all the jump sites, checking that they can trivially
733 // reach this label scope.
734 for (SmallVectorImpl<JumpScope>::iterator
735 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
736 unsigned Scope = I->first;
738 // Walk out the "scope chain" for this scope, looking for a scope
739 // we've marked reachable. For well-formed code this amortizes
740 // to O(JumpScopes.size() / Scopes.size()): we only iterate
741 // when we see something unmarked, and in well-formed code we
742 // mark everything we iterate past.
743 bool IsReachable = false;
745 if (Reachable.test(Scope)) {
746 // If we find something reachable, mark all the scopes we just
747 // walked through as reachable.
748 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
754 // Don't walk out if we've reached the top-level scope or we've
755 // gotten shallower than the shallowest reachable scope.
756 if (Scope == 0 || Scope < Min) break;
758 // Don't walk out through an out-diagnostic.
759 if (Scopes[Scope].OutDiag) break;
761 Scope = Scopes[Scope].ParentScope;
764 // Only diagnose if we didn't find something.
765 if (IsReachable) continue;
767 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
772 /// Return true if a particular error+note combination must be downgraded to a
773 /// warning in Microsoft mode.
774 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
775 return (JumpDiag == diag::err_goto_into_protected_scope &&
776 (InDiagNote == diag::note_protected_by_variable_init ||
777 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
780 /// Return true if a particular note should be downgraded to a compatibility
781 /// warning in C++11 mode.
782 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
783 return S.getLangOpts().CPlusPlus11 &&
784 InDiagNote == diag::note_protected_by_variable_non_pod;
787 /// Produce primary diagnostic for an indirect jump statement.
788 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
789 LabelDecl *Target, bool &Diagnosed) {
792 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
793 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
797 /// Produce note diagnostics for a jump into a protected scope.
798 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
799 if (CHECK_PERMISSIVE(ToScopes.empty()))
801 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
802 if (Scopes[ToScopes[I]].InDiag)
803 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
806 /// Diagnose an indirect jump which is known to cross scopes.
807 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
810 unsigned TargetScope) {
811 if (CHECK_PERMISSIVE(JumpScope == TargetScope))
814 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
815 bool Diagnosed = false;
817 // Walk out the scope chain until we reach the common ancestor.
818 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
819 if (Scopes[I].OutDiag) {
820 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
821 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
824 SmallVector<unsigned, 10> ToScopesCXX98Compat;
826 // Now walk into the scopes containing the label whose address was taken.
827 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
828 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
829 ToScopesCXX98Compat.push_back(I);
830 else if (Scopes[I].InDiag) {
831 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
832 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
835 // Diagnose this jump if it would be ill-formed in C++98.
836 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
837 S.Diag(Jump->getGotoLoc(),
838 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
839 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
840 NoteJumpIntoScopes(ToScopesCXX98Compat);
844 /// CheckJump - Validate that the specified jump statement is valid: that it is
845 /// jumping within or out of its current scope, not into a deeper one.
846 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
847 unsigned JumpDiagError, unsigned JumpDiagWarning,
848 unsigned JumpDiagCXX98Compat) {
849 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
851 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
854 unsigned FromScope = LabelAndGotoScopes[From];
855 unsigned ToScope = LabelAndGotoScopes[To];
857 // Common case: exactly the same scope, which is fine.
858 if (FromScope == ToScope) return;
860 // Warn on gotos out of __finally blocks.
861 if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
862 // If FromScope > ToScope, FromScope is more nested and the jump goes to a
863 // less nested scope. Check if it crosses a __finally along the way.
864 for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
865 if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
866 S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally);
872 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
874 // It's okay to jump out from a nested scope.
875 if (CommonScope == ToScope) return;
877 // Pull out (and reverse) any scopes we might need to diagnose skipping.
878 SmallVector<unsigned, 10> ToScopesCXX98Compat;
879 SmallVector<unsigned, 10> ToScopesError;
880 SmallVector<unsigned, 10> ToScopesWarning;
881 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
882 if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
883 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
884 ToScopesWarning.push_back(I);
885 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
886 ToScopesCXX98Compat.push_back(I);
887 else if (Scopes[I].InDiag)
888 ToScopesError.push_back(I);
892 if (!ToScopesWarning.empty()) {
893 S.Diag(DiagLoc, JumpDiagWarning);
894 NoteJumpIntoScopes(ToScopesWarning);
898 if (!ToScopesError.empty()) {
899 S.Diag(DiagLoc, JumpDiagError);
900 NoteJumpIntoScopes(ToScopesError);
903 // Handle -Wc++98-compat warnings if the jump is well-formed.
904 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
905 S.Diag(DiagLoc, JumpDiagCXX98Compat);
906 NoteJumpIntoScopes(ToScopesCXX98Compat);
910 void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
911 if (GS->getLabel()->isMSAsmLabel()) {
912 S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
913 << GS->getLabel()->getIdentifier();
914 S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
915 << GS->getLabel()->getIdentifier();
919 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
920 (void)JumpScopeChecker(Body, *this);