1 //===--- JumpDiagnostics.cpp - Analyze Jump Targets for VLA issues --------===//
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 VLA 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 diagnostic to emit if there is a jump into this scope.
48 /// OutDiag - The diagnostic 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 llvm::SmallVector<GotoScope, 48> Scopes;
62 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
63 llvm::SmallVector<Stmt*, 16> Jumps;
65 llvm::SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
66 llvm::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 DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
78 LabelDecl *Target, unsigned TargetScope);
79 void CheckJump(Stmt *From, Stmt *To,
80 SourceLocation DiagLoc, unsigned JumpDiag);
82 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
84 } // end anonymous namespace
87 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
88 // Add a scope entry for function scope.
89 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
91 // Build information for the top level compound statement, so that we have a
92 // defined scope record for every "goto" and label.
93 unsigned BodyParentScope = 0;
94 BuildScopeInformation(Body, BodyParentScope);
96 // Check that all jumps we saw are kosher.
98 VerifyIndirectJumps();
101 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
103 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
105 // Inner scopes are created after outer scopes and therefore have
108 assert(Scopes[B].ParentScope < B);
109 B = Scopes[B].ParentScope;
111 assert(Scopes[A].ParentScope < A);
112 A = Scopes[A].ParentScope;
118 typedef std::pair<unsigned,unsigned> ScopePair;
120 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
121 /// diagnostic that should be emitted if control goes over it. If not, return 0.
122 static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
123 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
124 unsigned InDiag = 0, OutDiag = 0;
125 if (VD->getType()->isVariablyModifiedType())
126 InDiag = diag::note_protected_by_vla;
128 if (VD->hasAttr<BlocksAttr>())
129 return ScopePair(diag::note_protected_by___block,
130 diag::note_exits___block);
132 if (VD->hasAttr<CleanupAttr>())
133 return ScopePair(diag::note_protected_by_cleanup,
134 diag::note_exits_cleanup);
136 if (Context.getLangOptions().ObjCAutoRefCount && VD->hasLocalStorage()) {
137 switch (VD->getType().getObjCLifetime()) {
138 case Qualifiers::OCL_None:
139 case Qualifiers::OCL_ExplicitNone:
140 case Qualifiers::OCL_Autoreleasing:
143 case Qualifiers::OCL_Strong:
144 case Qualifiers::OCL_Weak:
145 return ScopePair(diag::note_protected_by_objc_ownership,
146 diag::note_exits_objc_ownership);
150 if (Context.getLangOptions().CPlusPlus && VD->hasLocalStorage()) {
151 // C++0x [stmt.dcl]p3:
152 // A program that jumps from a point where a variable with automatic
153 // storage duration is not in scope to a point where it is in scope
154 // is ill-formed unless the variable has scalar type, class type with
155 // a trivial default constructor and a trivial destructor, a
156 // cv-qualified version of one of these types, or an array of one of
157 // the preceding types and is declared without an initializer.
159 // C++03 [stmt.dcl.p3:
160 // A program that jumps from a point where a local variable
161 // with automatic storage duration is not in scope to a point
162 // where it is in scope is ill-formed unless the variable has
163 // POD type and is declared without an initializer.
165 if (const Expr *init = VD->getInit()) {
166 // We actually give variables of record type (or array thereof)
167 // an initializer even if that initializer only calls a trivial
168 // ctor. Detect that case.
169 // FIXME: With generalized initializer lists, this may
170 // classify "X x{};" as having no initializer.
171 unsigned inDiagToUse = diag::note_protected_by_variable_init;
173 const CXXRecordDecl *record = 0;
175 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(init)) {
176 const CXXConstructorDecl *ctor = cce->getConstructor();
177 record = ctor->getParent();
179 if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
180 if (Context.getLangOptions().CPlusPlus0x) {
181 inDiagToUse = (record->hasTrivialDestructor() ? 0 :
182 diag::note_protected_by_variable_nontriv_destructor);
188 } else if (VD->getType()->isArrayType()) {
189 record = VD->getType()->getBaseElementTypeUnsafe()
190 ->getAsCXXRecordDecl();
194 InDiag = inDiagToUse;
196 // Also object to indirect jumps which leave scopes with dtors.
197 if (record && !record->hasTrivialDestructor())
198 OutDiag = diag::note_exits_dtor;
202 return ScopePair(InDiag, OutDiag);
205 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
206 if (TD->getUnderlyingType()->isVariablyModifiedType())
207 return ScopePair(diag::note_protected_by_vla_typedef, 0);
210 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
211 if (TD->getUnderlyingType()->isVariablyModifiedType())
212 return ScopePair(diag::note_protected_by_vla_type_alias, 0);
215 return ScopePair(0U, 0U);
218 /// \brief Build scope information for a declaration that is part of a DeclStmt.
219 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
220 // If this decl causes a new scope, push and switch to it.
221 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D);
222 if (Diags.first || Diags.second) {
223 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
225 ParentScope = Scopes.size()-1;
228 // If the decl has an initializer, walk it with the potentially new
229 // scope we just installed.
230 if (VarDecl *VD = dyn_cast<VarDecl>(D))
231 if (Expr *Init = VD->getInit())
232 BuildScopeInformation(Init, ParentScope);
235 /// \brief Build scope information for a captured block literal variables.
236 void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
237 const BlockDecl *BDecl,
238 unsigned &ParentScope) {
239 // exclude captured __block variables; there's no destructor
240 // associated with the block literal for them.
241 if (D->hasAttr<BlocksAttr>())
243 QualType T = D->getType();
244 QualType::DestructionKind destructKind = T.isDestructedType();
245 if (destructKind != QualType::DK_none) {
246 std::pair<unsigned,unsigned> Diags;
247 switch (destructKind) {
248 case QualType::DK_cxx_destructor:
249 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
250 diag::note_exits_block_captures_cxx_obj);
252 case QualType::DK_objc_strong_lifetime:
253 Diags = ScopePair(diag::note_enters_block_captures_strong,
254 diag::note_exits_block_captures_strong);
256 case QualType::DK_objc_weak_lifetime:
257 Diags = ScopePair(diag::note_enters_block_captures_weak,
258 diag::note_exits_block_captures_weak);
260 case QualType::DK_none:
261 llvm_unreachable("no-liftime captured variable");
263 SourceLocation Loc = D->getLocation();
265 Loc = BDecl->getLocation();
266 Scopes.push_back(GotoScope(ParentScope,
267 Diags.first, Diags.second, Loc));
268 ParentScope = Scopes.size()-1;
272 /// BuildScopeInformation - The statements from CI to CE are known to form a
273 /// coherent VLA scope with a specified parent node. Walk through the
274 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
275 /// walking the AST as needed.
276 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
277 // If this is a statement, rather than an expression, scopes within it don't
278 // propagate out into the enclosing scope. Otherwise we have to worry
279 // about block literals, which have the lifetime of their enclosing statement.
280 unsigned independentParentScope = origParentScope;
281 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
282 ? origParentScope : independentParentScope);
284 bool SkipFirstSubStmt = false;
286 // If we found a label, remember that it is in ParentScope scope.
287 switch (S->getStmtClass()) {
288 case Stmt::AddrLabelExprClass:
289 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
292 case Stmt::IndirectGotoStmtClass:
293 // "goto *&&lbl;" is a special case which we treat as equivalent
294 // to a normal goto. In addition, we don't calculate scope in the
295 // operand (to avoid recording the address-of-label use), which
296 // works only because of the restricted set of expressions which
297 // we detect as constant targets.
298 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
299 LabelAndGotoScopes[S] = ParentScope;
304 LabelAndGotoScopes[S] = ParentScope;
305 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
308 case Stmt::SwitchStmtClass:
309 // Evaluate the condition variable before entering the scope of the switch
311 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
312 BuildScopeInformation(Var, ParentScope);
313 SkipFirstSubStmt = true;
317 case Stmt::GotoStmtClass:
318 // Remember both what scope a goto is in as well as the fact that we have
319 // it. This makes the second scan not have to walk the AST again.
320 LabelAndGotoScopes[S] = ParentScope;
328 for (Stmt::child_range CI = S->children(); CI; ++CI) {
329 if (SkipFirstSubStmt) {
330 SkipFirstSubStmt = false;
335 if (SubStmt == 0) continue;
337 // Cases, labels, and defaults aren't "scope parents". It's also
338 // important to handle these iteratively instead of recursively in
339 // order to avoid blowing out the stack.
342 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
343 Next = CS->getSubStmt();
344 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
345 Next = DS->getSubStmt();
346 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
347 Next = LS->getSubStmt();
351 LabelAndGotoScopes[SubStmt] = ParentScope;
355 // If this is a declstmt with a VLA definition, it defines a scope from here
356 // to the end of the containing context.
357 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
358 // The decl statement creates a scope if any of the decls in it are VLAs
359 // or have the cleanup attribute.
360 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
362 BuildScopeInformation(*I, ParentScope);
365 // Disallow jumps into any part of an @try statement by pushing a scope and
366 // walking all sub-stmts in that scope.
367 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
368 unsigned newParentScope;
369 // Recursively walk the AST for the @try part.
370 Scopes.push_back(GotoScope(ParentScope,
371 diag::note_protected_by_objc_try,
372 diag::note_exits_objc_try,
374 if (Stmt *TryPart = AT->getTryBody())
375 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
377 // Jump from the catch to the finally or try is not valid.
378 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
379 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
380 Scopes.push_back(GotoScope(ParentScope,
381 diag::note_protected_by_objc_catch,
382 diag::note_exits_objc_catch,
383 AC->getAtCatchLoc()));
384 // @catches are nested and it isn't
385 BuildScopeInformation(AC->getCatchBody(),
386 (newParentScope = Scopes.size()-1));
389 // Jump from the finally to the try or catch is not valid.
390 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
391 Scopes.push_back(GotoScope(ParentScope,
392 diag::note_protected_by_objc_finally,
393 diag::note_exits_objc_finally,
394 AF->getAtFinallyLoc()));
395 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
401 unsigned newParentScope;
402 // Disallow jumps into the protected statement of an @synchronized, but
403 // allow jumps into the object expression it protects.
404 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
405 // Recursively walk the AST for the @synchronized object expr, it is
406 // evaluated in the normal scope.
407 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
409 // Recursively walk the AST for the @synchronized part, protected by a new
411 Scopes.push_back(GotoScope(ParentScope,
412 diag::note_protected_by_objc_synchronized,
413 diag::note_exits_objc_synchronized,
414 AS->getAtSynchronizedLoc()));
415 BuildScopeInformation(AS->getSynchBody(),
416 (newParentScope = Scopes.size()-1));
420 // Disallow jumps into any part of a C++ try statement. This is pretty
421 // much the same as for Obj-C.
422 if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
423 Scopes.push_back(GotoScope(ParentScope,
424 diag::note_protected_by_cxx_try,
425 diag::note_exits_cxx_try,
426 TS->getSourceRange().getBegin()));
427 if (Stmt *TryBlock = TS->getTryBlock())
428 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
430 // Jump from the catch into the try is not allowed either.
431 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
432 CXXCatchStmt *CS = TS->getHandler(I);
433 Scopes.push_back(GotoScope(ParentScope,
434 diag::note_protected_by_cxx_catch,
435 diag::note_exits_cxx_catch,
436 CS->getSourceRange().getBegin()));
437 BuildScopeInformation(CS->getHandlerBlock(),
438 (newParentScope = Scopes.size()-1));
444 // Disallow jumps into the protected statement of an @autoreleasepool.
445 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
446 // Recursively walk the AST for the @autoreleasepool part, protected by a new
448 Scopes.push_back(GotoScope(ParentScope,
449 diag::note_protected_by_objc_autoreleasepool,
450 diag::note_exits_objc_autoreleasepool,
452 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
456 if (const BlockExpr *BE = dyn_cast<BlockExpr>(SubStmt)) {
457 const BlockDecl *BDecl = BE->getBlockDecl();
458 for (BlockDecl::capture_const_iterator ci = BDecl->capture_begin(),
459 ce = BDecl->capture_end(); ci != ce; ++ci) {
460 VarDecl *variable = ci->getVariable();
461 BuildScopeInformation(variable, BDecl, ParentScope);
465 // Recursively walk the AST.
466 BuildScopeInformation(SubStmt, ParentScope);
470 /// VerifyJumps - Verify each element of the Jumps array to see if they are
471 /// valid, emitting diagnostics if not.
472 void JumpScopeChecker::VerifyJumps() {
473 while (!Jumps.empty()) {
474 Stmt *Jump = Jumps.pop_back_val();
477 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
478 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
479 diag::err_goto_into_protected_scope);
483 // We only get indirect gotos here when they have a constant target.
484 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
485 LabelDecl *Target = IGS->getConstantTarget();
486 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
487 diag::err_goto_into_protected_scope);
491 SwitchStmt *SS = cast<SwitchStmt>(Jump);
492 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
493 SC = SC->getNextSwitchCase()) {
494 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
495 CheckJump(SS, SC, SC->getLocStart(),
496 diag::err_switch_into_protected_scope);
501 /// VerifyIndirectJumps - Verify whether any possible indirect jump
502 /// might cross a protection boundary. Unlike direct jumps, indirect
503 /// jumps count cleanups as protection boundaries: since there's no
504 /// way to know where the jump is going, we can't implicitly run the
505 /// right cleanups the way we can with direct jumps.
507 /// Thus, an indirect jump is "trivial" if it bypasses no
508 /// initializations and no teardowns. More formally, an indirect jump
509 /// from A to B is trivial if the path out from A to DCA(A,B) is
510 /// trivial and the path in from DCA(A,B) to B is trivial, where
511 /// DCA(A,B) is the deepest common ancestor of A and B.
512 /// Jump-triviality is transitive but asymmetric.
514 /// A path in is trivial if none of the entered scopes have an InDiag.
515 /// A path out is trivial is none of the exited scopes have an OutDiag.
517 /// Under these definitions, this function checks that the indirect
518 /// jump between A and B is trivial for every indirect goto statement A
519 /// and every label B whose address was taken in the function.
520 void JumpScopeChecker::VerifyIndirectJumps() {
521 if (IndirectJumps.empty()) return;
523 // If there aren't any address-of-label expressions in this function,
524 // complain about the first indirect goto.
525 if (IndirectJumpTargets.empty()) {
526 S.Diag(IndirectJumps[0]->getGotoLoc(),
527 diag::err_indirect_goto_without_addrlabel);
531 // Collect a single representative of every scope containing an
532 // indirect goto. For most code bases, this substantially cuts
533 // down on the number of jump sites we'll have to consider later.
534 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
535 llvm::SmallVector<JumpScope, 32> JumpScopes;
537 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
538 for (llvm::SmallVectorImpl<IndirectGotoStmt*>::iterator
539 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
540 IndirectGotoStmt *IG = *I;
541 assert(LabelAndGotoScopes.count(IG) &&
542 "indirect jump didn't get added to scopes?");
543 unsigned IGScope = LabelAndGotoScopes[IG];
544 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
545 if (!Entry) Entry = IG;
547 JumpScopes.reserve(JumpScopesMap.size());
548 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
549 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
550 JumpScopes.push_back(*I);
553 // Collect a single representative of every scope containing a
554 // label whose address was taken somewhere in the function.
555 // For most code bases, there will be only one such scope.
556 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
557 for (llvm::SmallVectorImpl<LabelDecl*>::iterator
558 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
560 LabelDecl *TheLabel = *I;
561 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
562 "Referenced label didn't get added to scopes?");
563 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
564 LabelDecl *&Target = TargetScopes[LabelScope];
565 if (!Target) Target = TheLabel;
568 // For each target scope, make sure it's trivially reachable from
569 // every scope containing a jump site.
571 // A path between scopes always consists of exitting zero or more
572 // scopes, then entering zero or more scopes. We build a set of
573 // of scopes S from which the target scope can be trivially
574 // entered, then verify that every jump scope can be trivially
575 // exitted to reach a scope in S.
576 llvm::BitVector Reachable(Scopes.size(), false);
577 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
578 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
579 unsigned TargetScope = TI->first;
580 LabelDecl *TargetLabel = TI->second;
584 // Mark all the enclosing scopes from which you can safely jump
585 // into the target scope. 'Min' will end up being the index of
586 // the shallowest such scope.
587 unsigned Min = TargetScope;
591 // Don't go beyond the outermost scope.
594 // Stop if we can't trivially enter the current scope.
595 if (Scopes[Min].InDiag) break;
597 Min = Scopes[Min].ParentScope;
600 // Walk through all the jump sites, checking that they can trivially
601 // reach this label scope.
602 for (llvm::SmallVectorImpl<JumpScope>::iterator
603 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
604 unsigned Scope = I->first;
606 // Walk out the "scope chain" for this scope, looking for a scope
607 // we've marked reachable. For well-formed code this amortizes
608 // to O(JumpScopes.size() / Scopes.size()): we only iterate
609 // when we see something unmarked, and in well-formed code we
610 // mark everything we iterate past.
611 bool IsReachable = false;
613 if (Reachable.test(Scope)) {
614 // If we find something reachable, mark all the scopes we just
615 // walked through as reachable.
616 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
622 // Don't walk out if we've reached the top-level scope or we've
623 // gotten shallower than the shallowest reachable scope.
624 if (Scope == 0 || Scope < Min) break;
626 // Don't walk out through an out-diagnostic.
627 if (Scopes[Scope].OutDiag) break;
629 Scope = Scopes[Scope].ParentScope;
632 // Only diagnose if we didn't find something.
633 if (IsReachable) continue;
635 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
640 /// Diagnose an indirect jump which is known to cross scopes.
641 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
644 unsigned TargetScope) {
645 assert(JumpScope != TargetScope);
647 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
648 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
650 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
652 // Walk out the scope chain until we reach the common ancestor.
653 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
654 if (Scopes[I].OutDiag)
655 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
657 // Now walk into the scopes containing the label whose address was taken.
658 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
659 if (Scopes[I].InDiag)
660 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
663 /// CheckJump - Validate that the specified jump statement is valid: that it is
664 /// jumping within or out of its current scope, not into a deeper one.
665 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
666 SourceLocation DiagLoc, unsigned JumpDiag) {
667 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
668 unsigned FromScope = LabelAndGotoScopes[From];
670 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
671 unsigned ToScope = LabelAndGotoScopes[To];
673 // Common case: exactly the same scope, which is fine.
674 if (FromScope == ToScope) return;
676 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
678 // It's okay to jump out from a nested scope.
679 if (CommonScope == ToScope) return;
681 // Pull out (and reverse) any scopes we might need to diagnose skipping.
682 llvm::SmallVector<unsigned, 10> ToScopes;
683 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope)
684 if (Scopes[I].InDiag)
685 ToScopes.push_back(I);
687 // If the only scopes present are cleanup scopes, we're okay.
688 if (ToScopes.empty()) return;
690 S.Diag(DiagLoc, JumpDiag);
692 // Emit diagnostics for whatever is left in ToScopes.
693 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
694 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].InDiag);
697 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
698 (void)JumpScopeChecker(Body, *this);