1//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the JumpScopeChecker class, which is used to diagnose
11// jumps that enter a protected scope in an invalid way.
12//
13//===----------------------------------------------------------------------===//
14
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"
22using namespace clang;
23
24namespace {
25
26/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
27/// into VLA and other protected scopes.  For example, this rejects:
28///    goto L;
29///    int a[n];
30///  L:
31///
32class JumpScopeChecker {
33  Sema &S;
34
35  /// Permissive - True when recovering from errors, in which case precautions
36  /// are taken to handle incomplete scope information.
37  const bool Permissive;
38
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.
44  struct GotoScope {
45    /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
46    /// the parent scope is the function body.
47    unsigned ParentScope;
48
49    /// InDiag - The note to emit if there is a jump into this scope.
50    unsigned InDiag;
51
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.
55    unsigned OutDiag;
56
57    /// Loc - Location to emit the diagnostic.
58    SourceLocation Loc;
59
60    GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
61              SourceLocation L)
62      : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
63  };
64
65  SmallVector<GotoScope, 48> Scopes;
66  llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
67  SmallVector<Stmt*, 16> Jumps;
68
69  SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
70  SmallVector<LabelDecl*, 4> IndirectJumpTargets;
71public:
72  JumpScopeChecker(Stmt *Body, Sema &S);
73private:
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);
78
79  void VerifyJumps();
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
88  unsigned GetDeepestCommonScope(unsigned A, unsigned B);
89};
90} // end anonymous namespace
91
92#define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
93
94JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
95    : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
96  // Add a scope entry for function scope.
97  Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
98
99  // Build information for the top level compound statement, so that we have a
100  // defined scope record for every "goto" and label.
101  unsigned BodyParentScope = 0;
102  BuildScopeInformation(Body, BodyParentScope);
103
104  // Check that all jumps we saw are kosher.
105  VerifyJumps();
106  VerifyIndirectJumps();
107}
108
109/// GetDeepestCommonScope - Finds the innermost scope enclosing the
110/// two scopes.
111unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
112  while (A != B) {
113    // Inner scopes are created after outer scopes and therefore have
114    // higher indices.
115    if (A < B) {
116      assert(Scopes[B].ParentScope < B);
117      B = Scopes[B].ParentScope;
118    } else {
119      assert(Scopes[A].ParentScope < A);
120      A = Scopes[A].ParentScope;
121    }
122  }
123  return A;
124}
125
126typedef std::pair<unsigned,unsigned> ScopePair;
127
128/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
129/// diagnostic that should be emitted if control goes over it. If not, return 0.
130static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
131  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
132    unsigned InDiag = 0;
133    unsigned OutDiag = 0;
134
135    if (VD->getType()->isVariablyModifiedType())
136      InDiag = diag::note_protected_by_vla;
137
138    if (VD->hasAttr<BlocksAttr>())
139      return ScopePair(diag::note_protected_by___block,
140                       diag::note_exits___block);
141
142    if (VD->hasAttr<CleanupAttr>())
143      return ScopePair(diag::note_protected_by_cleanup,
144                       diag::note_exits_cleanup);
145
146    if (VD->hasLocalStorage()) {
147      switch (VD->getType().isDestructedType()) {
148      case QualType::DK_objc_strong_lifetime:
149      case QualType::DK_objc_weak_lifetime:
150        return ScopePair(diag::note_protected_by_objc_ownership,
151                         diag::note_exits_objc_ownership);
152
153      case QualType::DK_cxx_destructor:
154        OutDiag = diag::note_exits_dtor;
155        break;
156
157      case QualType::DK_none:
158        break;
159      }
160    }
161
162    const Expr *Init = VD->getInit();
163    if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
164      // C++11 [stmt.dcl]p3:
165      //   A program that jumps from a point where a variable with automatic
166      //   storage duration is not in scope to a point where it is in scope
167      //   is ill-formed unless the variable has scalar type, class type with
168      //   a trivial default constructor and a trivial destructor, a
169      //   cv-qualified version of one of these types, or an array of one of
170      //   the preceding types and is declared without an initializer.
171
172      // C++03 [stmt.dcl.p3:
173      //   A program that jumps from a point where a local variable
174      //   with automatic storage duration is not in scope to a point
175      //   where it is in scope is ill-formed unless the variable has
176      //   POD type and is declared without an initializer.
177
178      InDiag = diag::note_protected_by_variable_init;
179
180      // For a variable of (array of) class type declared without an
181      // initializer, we will have call-style initialization and the initializer
182      // will be the CXXConstructExpr with no intervening nodes.
183      if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
184        const CXXConstructorDecl *Ctor = CCE->getConstructor();
185        if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
186            VD->getInitStyle() == VarDecl::CallInit) {
187          if (OutDiag)
188            InDiag = diag::note_protected_by_variable_nontriv_destructor;
189          else if (!Ctor->getParent()->isPOD())
190            InDiag = diag::note_protected_by_variable_non_pod;
191          else
192            InDiag = 0;
193        }
194      }
195    }
196
197    return ScopePair(InDiag, OutDiag);
198  }
199
200  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
201    if (TD->getUnderlyingType()->isVariablyModifiedType())
202      return ScopePair(isa<TypedefDecl>(TD)
203                           ? diag::note_protected_by_vla_typedef
204                           : diag::note_protected_by_vla_type_alias,
205                       0);
206  }
207
208  return ScopePair(0U, 0U);
209}
210
211/// \brief Build scope information for a declaration that is part of a DeclStmt.
212void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
213  // If this decl causes a new scope, push and switch to it.
214  std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
215  if (Diags.first || Diags.second) {
216    Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
217                               D->getLocation()));
218    ParentScope = Scopes.size()-1;
219  }
220
221  // If the decl has an initializer, walk it with the potentially new
222  // scope we just installed.
223  if (VarDecl *VD = dyn_cast<VarDecl>(D))
224    if (Expr *Init = VD->getInit())
225      BuildScopeInformation(Init, ParentScope);
226}
227
228/// \brief Build scope information for a captured block literal variables.
229void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
230                                             const BlockDecl *BDecl,
231                                             unsigned &ParentScope) {
232  // exclude captured __block variables; there's no destructor
233  // associated with the block literal for them.
234  if (D->hasAttr<BlocksAttr>())
235    return;
236  QualType T = D->getType();
237  QualType::DestructionKind destructKind = T.isDestructedType();
238  if (destructKind != QualType::DK_none) {
239    std::pair<unsigned,unsigned> Diags;
240    switch (destructKind) {
241      case QualType::DK_cxx_destructor:
242        Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
243                          diag::note_exits_block_captures_cxx_obj);
244        break;
245      case QualType::DK_objc_strong_lifetime:
246        Diags = ScopePair(diag::note_enters_block_captures_strong,
247                          diag::note_exits_block_captures_strong);
248        break;
249      case QualType::DK_objc_weak_lifetime:
250        Diags = ScopePair(diag::note_enters_block_captures_weak,
251                          diag::note_exits_block_captures_weak);
252        break;
253      case QualType::DK_none:
254        llvm_unreachable("non-lifetime captured variable");
255    }
256    SourceLocation Loc = D->getLocation();
257    if (Loc.isInvalid())
258      Loc = BDecl->getLocation();
259    Scopes.push_back(GotoScope(ParentScope,
260                               Diags.first, Diags.second, Loc));
261    ParentScope = Scopes.size()-1;
262  }
263}
264
265/// BuildScopeInformation - The statements from CI to CE are known to form a
266/// coherent VLA scope with a specified parent node.  Walk through the
267/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
268/// walking the AST as needed.
269void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
270  // If this is a statement, rather than an expression, scopes within it don't
271  // propagate out into the enclosing scope.  Otherwise we have to worry
272  // about block literals, which have the lifetime of their enclosing statement.
273  unsigned independentParentScope = origParentScope;
274  unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
275                            ? origParentScope : independentParentScope);
276
277  bool SkipFirstSubStmt = false;
278
279  // If we found a label, remember that it is in ParentScope scope.
280  switch (S->getStmtClass()) {
281  case Stmt::AddrLabelExprClass:
282    IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
283    break;
284
285  case Stmt::IndirectGotoStmtClass:
286    // "goto *&&lbl;" is a special case which we treat as equivalent
287    // to a normal goto.  In addition, we don't calculate scope in the
288    // operand (to avoid recording the address-of-label use), which
289    // works only because of the restricted set of expressions which
290    // we detect as constant targets.
291    if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
292      LabelAndGotoScopes[S] = ParentScope;
293      Jumps.push_back(S);
294      return;
295    }
296
297    LabelAndGotoScopes[S] = ParentScope;
298    IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
299    break;
300
301  case Stmt::SwitchStmtClass:
302    // Evaluate the condition variable before entering the scope of the switch
303    // statement.
304    if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
305      BuildScopeInformation(Var, ParentScope);
306      SkipFirstSubStmt = true;
307    }
308    // Fall through
309
310  case Stmt::GotoStmtClass:
311    // Remember both what scope a goto is in as well as the fact that we have
312    // it.  This makes the second scan not have to walk the AST again.
313    LabelAndGotoScopes[S] = ParentScope;
314    Jumps.push_back(S);
315    break;
316
317  case Stmt::CXXTryStmtClass: {
318    CXXTryStmt *TS = cast<CXXTryStmt>(S);
319    unsigned newParentScope;
320    Scopes.push_back(GotoScope(ParentScope,
321                               diag::note_protected_by_cxx_try,
322                               diag::note_exits_cxx_try,
323                               TS->getSourceRange().getBegin()));
324    if (Stmt *TryBlock = TS->getTryBlock())
325      BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
326
327    // Jump from the catch into the try is not allowed either.
328    for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
329      CXXCatchStmt *CS = TS->getHandler(I);
330      Scopes.push_back(GotoScope(ParentScope,
331                                 diag::note_protected_by_cxx_catch,
332                                 diag::note_exits_cxx_catch,
333                                 CS->getSourceRange().getBegin()));
334      BuildScopeInformation(CS->getHandlerBlock(),
335                            (newParentScope = Scopes.size()-1));
336    }
337    return;
338  }
339
340  default:
341    break;
342  }
343
344  for (Stmt::child_range CI = S->children(); CI; ++CI) {
345    if (SkipFirstSubStmt) {
346      SkipFirstSubStmt = false;
347      continue;
348    }
349
350    Stmt *SubStmt = *CI;
351    if (!SubStmt) continue;
352
353    // Cases, labels, and defaults aren't "scope parents".  It's also
354    // important to handle these iteratively instead of recursively in
355    // order to avoid blowing out the stack.
356    while (true) {
357      Stmt *Next;
358      if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
359        Next = CS->getSubStmt();
360      else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
361        Next = DS->getSubStmt();
362      else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
363        Next = LS->getSubStmt();
364      else
365        break;
366
367      LabelAndGotoScopes[SubStmt] = ParentScope;
368      SubStmt = Next;
369    }
370
371    // If this is a declstmt with a VLA definition, it defines a scope from here
372    // to the end of the containing context.
373    if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
374      // The decl statement creates a scope if any of the decls in it are VLAs
375      // or have the cleanup attribute.
376      for (auto *I : DS->decls())
377        BuildScopeInformation(I, ParentScope);
378      continue;
379    }
380    // Disallow jumps into any part of an @try statement by pushing a scope and
381    // walking all sub-stmts in that scope.
382    if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
383      unsigned newParentScope;
384      // Recursively walk the AST for the @try part.
385      Scopes.push_back(GotoScope(ParentScope,
386                                 diag::note_protected_by_objc_try,
387                                 diag::note_exits_objc_try,
388                                 AT->getAtTryLoc()));
389      if (Stmt *TryPart = AT->getTryBody())
390        BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
391
392      // Jump from the catch to the finally or try is not valid.
393      for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
394        ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
395        Scopes.push_back(GotoScope(ParentScope,
396                                   diag::note_protected_by_objc_catch,
397                                   diag::note_exits_objc_catch,
398                                   AC->getAtCatchLoc()));
399        // @catches are nested and it isn't
400        BuildScopeInformation(AC->getCatchBody(),
401                              (newParentScope = Scopes.size()-1));
402      }
403
404      // Jump from the finally to the try or catch is not valid.
405      if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
406        Scopes.push_back(GotoScope(ParentScope,
407                                   diag::note_protected_by_objc_finally,
408                                   diag::note_exits_objc_finally,
409                                   AF->getAtFinallyLoc()));
410        BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
411      }
412
413      continue;
414    }
415
416    unsigned newParentScope;
417    // Disallow jumps into the protected statement of an @synchronized, but
418    // allow jumps into the object expression it protects.
419    if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
420      // Recursively walk the AST for the @synchronized object expr, it is
421      // evaluated in the normal scope.
422      BuildScopeInformation(AS->getSynchExpr(), ParentScope);
423
424      // Recursively walk the AST for the @synchronized part, protected by a new
425      // scope.
426      Scopes.push_back(GotoScope(ParentScope,
427                                 diag::note_protected_by_objc_synchronized,
428                                 diag::note_exits_objc_synchronized,
429                                 AS->getAtSynchronizedLoc()));
430      BuildScopeInformation(AS->getSynchBody(),
431                            (newParentScope = Scopes.size()-1));
432      continue;
433    }
434
435    // Disallow jumps into the protected statement of an @autoreleasepool.
436    if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
437      // Recursively walk the AST for the @autoreleasepool part, protected by a new
438      // scope.
439      Scopes.push_back(GotoScope(ParentScope,
440                                 diag::note_protected_by_objc_autoreleasepool,
441                                 diag::note_exits_objc_autoreleasepool,
442                                 AS->getAtLoc()));
443      BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
444      continue;
445    }
446
447    // Disallow jumps past full-expressions that use blocks with
448    // non-trivial cleanups of their captures.  This is theoretically
449    // implementable but a lot of work which we haven't felt up to doing.
450    if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) {
451      for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
452        const BlockDecl *BDecl = EWC->getObject(i);
453        for (const auto &CI : BDecl->captures()) {
454          VarDecl *variable = CI.getVariable();
455          BuildScopeInformation(variable, BDecl, ParentScope);
456        }
457      }
458    }
459
460    // Disallow jumps out of scopes containing temporaries lifetime-extended to
461    // automatic storage duration.
462    if (MaterializeTemporaryExpr *MTE =
463            dyn_cast<MaterializeTemporaryExpr>(SubStmt)) {
464      if (MTE->getStorageDuration() == SD_Automatic) {
465        SmallVector<const Expr *, 4> CommaLHS;
466        SmallVector<SubobjectAdjustment, 4> Adjustments;
467        const Expr *ExtendedObject =
468            MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
469                CommaLHS, Adjustments);
470        if (ExtendedObject->getType().isDestructedType()) {
471          Scopes.push_back(GotoScope(ParentScope, 0,
472                                     diag::note_exits_temporary_dtor,
473                                     ExtendedObject->getExprLoc()));
474          ParentScope = Scopes.size()-1;
475        }
476      }
477    }
478
479    // Recursively walk the AST.
480    BuildScopeInformation(SubStmt, ParentScope);
481  }
482}
483
484/// VerifyJumps - Verify each element of the Jumps array to see if they are
485/// valid, emitting diagnostics if not.
486void JumpScopeChecker::VerifyJumps() {
487  while (!Jumps.empty()) {
488    Stmt *Jump = Jumps.pop_back_val();
489
490    // With a goto,
491    if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
492      CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
493                diag::err_goto_into_protected_scope,
494                diag::warn_goto_into_protected_scope,
495                diag::warn_cxx98_compat_goto_into_protected_scope);
496      continue;
497    }
498
499    // We only get indirect gotos here when they have a constant target.
500    if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
501      LabelDecl *Target = IGS->getConstantTarget();
502      CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
503                diag::err_goto_into_protected_scope,
504                diag::warn_goto_into_protected_scope,
505                diag::warn_cxx98_compat_goto_into_protected_scope);
506      continue;
507    }
508
509    SwitchStmt *SS = cast<SwitchStmt>(Jump);
510    for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
511         SC = SC->getNextSwitchCase()) {
512      if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
513        continue;
514      SourceLocation Loc;
515      if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
516        Loc = CS->getLocStart();
517      else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
518        Loc = DS->getLocStart();
519      else
520        Loc = SC->getLocStart();
521      CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
522                diag::warn_cxx98_compat_switch_into_protected_scope);
523    }
524  }
525}
526
527/// VerifyIndirectJumps - Verify whether any possible indirect jump
528/// might cross a protection boundary.  Unlike direct jumps, indirect
529/// jumps count cleanups as protection boundaries:  since there's no
530/// way to know where the jump is going, we can't implicitly run the
531/// right cleanups the way we can with direct jumps.
532///
533/// Thus, an indirect jump is "trivial" if it bypasses no
534/// initializations and no teardowns.  More formally, an indirect jump
535/// from A to B is trivial if the path out from A to DCA(A,B) is
536/// trivial and the path in from DCA(A,B) to B is trivial, where
537/// DCA(A,B) is the deepest common ancestor of A and B.
538/// Jump-triviality is transitive but asymmetric.
539///
540/// A path in is trivial if none of the entered scopes have an InDiag.
541/// A path out is trivial is none of the exited scopes have an OutDiag.
542///
543/// Under these definitions, this function checks that the indirect
544/// jump between A and B is trivial for every indirect goto statement A
545/// and every label B whose address was taken in the function.
546void JumpScopeChecker::VerifyIndirectJumps() {
547  if (IndirectJumps.empty()) return;
548
549  // If there aren't any address-of-label expressions in this function,
550  // complain about the first indirect goto.
551  if (IndirectJumpTargets.empty()) {
552    S.Diag(IndirectJumps[0]->getGotoLoc(),
553           diag::err_indirect_goto_without_addrlabel);
554    return;
555  }
556
557  // Collect a single representative of every scope containing an
558  // indirect goto.  For most code bases, this substantially cuts
559  // down on the number of jump sites we'll have to consider later.
560  typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
561  SmallVector<JumpScope, 32> JumpScopes;
562  {
563    llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
564    for (SmallVectorImpl<IndirectGotoStmt*>::iterator
565           I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
566      IndirectGotoStmt *IG = *I;
567      if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
568        continue;
569      unsigned IGScope = LabelAndGotoScopes[IG];
570      IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
571      if (!Entry) Entry = IG;
572    }
573    JumpScopes.reserve(JumpScopesMap.size());
574    for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
575           I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
576      JumpScopes.push_back(*I);
577  }
578
579  // Collect a single representative of every scope containing a
580  // label whose address was taken somewhere in the function.
581  // For most code bases, there will be only one such scope.
582  llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
583  for (SmallVectorImpl<LabelDecl*>::iterator
584         I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
585       I != E; ++I) {
586    LabelDecl *TheLabel = *I;
587    if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
588      continue;
589    unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
590    LabelDecl *&Target = TargetScopes[LabelScope];
591    if (!Target) Target = TheLabel;
592  }
593
594  // For each target scope, make sure it's trivially reachable from
595  // every scope containing a jump site.
596  //
597  // A path between scopes always consists of exitting zero or more
598  // scopes, then entering zero or more scopes.  We build a set of
599  // of scopes S from which the target scope can be trivially
600  // entered, then verify that every jump scope can be trivially
601  // exitted to reach a scope in S.
602  llvm::BitVector Reachable(Scopes.size(), false);
603  for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
604         TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
605    unsigned TargetScope = TI->first;
606    LabelDecl *TargetLabel = TI->second;
607
608    Reachable.reset();
609
610    // Mark all the enclosing scopes from which you can safely jump
611    // into the target scope.  'Min' will end up being the index of
612    // the shallowest such scope.
613    unsigned Min = TargetScope;
614    while (true) {
615      Reachable.set(Min);
616
617      // Don't go beyond the outermost scope.
618      if (Min == 0) break;
619
620      // Stop if we can't trivially enter the current scope.
621      if (Scopes[Min].InDiag) break;
622
623      Min = Scopes[Min].ParentScope;
624    }
625
626    // Walk through all the jump sites, checking that they can trivially
627    // reach this label scope.
628    for (SmallVectorImpl<JumpScope>::iterator
629           I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
630      unsigned Scope = I->first;
631
632      // Walk out the "scope chain" for this scope, looking for a scope
633      // we've marked reachable.  For well-formed code this amortizes
634      // to O(JumpScopes.size() / Scopes.size()):  we only iterate
635      // when we see something unmarked, and in well-formed code we
636      // mark everything we iterate past.
637      bool IsReachable = false;
638      while (true) {
639        if (Reachable.test(Scope)) {
640          // If we find something reachable, mark all the scopes we just
641          // walked through as reachable.
642          for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
643            Reachable.set(S);
644          IsReachable = true;
645          break;
646        }
647
648        // Don't walk out if we've reached the top-level scope or we've
649        // gotten shallower than the shallowest reachable scope.
650        if (Scope == 0 || Scope < Min) break;
651
652        // Don't walk out through an out-diagnostic.
653        if (Scopes[Scope].OutDiag) break;
654
655        Scope = Scopes[Scope].ParentScope;
656      }
657
658      // Only diagnose if we didn't find something.
659      if (IsReachable) continue;
660
661      DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
662    }
663  }
664}
665
666/// Return true if a particular error+note combination must be downgraded to a
667/// warning in Microsoft mode.
668static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
669  return (JumpDiag == diag::err_goto_into_protected_scope &&
670         (InDiagNote == diag::note_protected_by_variable_init ||
671          InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
672}
673
674/// Return true if a particular note should be downgraded to a compatibility
675/// warning in C++11 mode.
676static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
677  return S.getLangOpts().CPlusPlus11 &&
678         InDiagNote == diag::note_protected_by_variable_non_pod;
679}
680
681/// Produce primary diagnostic for an indirect jump statement.
682static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
683                                     LabelDecl *Target, bool &Diagnosed) {
684  if (Diagnosed)
685    return;
686  S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
687  S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
688  Diagnosed = true;
689}
690
691/// Produce note diagnostics for a jump into a protected scope.
692void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
693  if (CHECK_PERMISSIVE(ToScopes.empty()))
694    return;
695  for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
696    if (Scopes[ToScopes[I]].InDiag)
697      S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
698}
699
700/// Diagnose an indirect jump which is known to cross scopes.
701void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
702                                            unsigned JumpScope,
703                                            LabelDecl *Target,
704                                            unsigned TargetScope) {
705  if (CHECK_PERMISSIVE(JumpScope == TargetScope))
706    return;
707
708  unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
709  bool Diagnosed = false;
710
711  // Walk out the scope chain until we reach the common ancestor.
712  for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
713    if (Scopes[I].OutDiag) {
714      DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
715      S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
716    }
717
718  SmallVector<unsigned, 10> ToScopesCXX98Compat;
719
720  // Now walk into the scopes containing the label whose address was taken.
721  for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
722    if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
723      ToScopesCXX98Compat.push_back(I);
724    else if (Scopes[I].InDiag) {
725      DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
726      S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
727    }
728
729  // Diagnose this jump if it would be ill-formed in C++98.
730  if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
731    S.Diag(Jump->getGotoLoc(),
732           diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
733    S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
734    NoteJumpIntoScopes(ToScopesCXX98Compat);
735  }
736}
737
738/// CheckJump - Validate that the specified jump statement is valid: that it is
739/// jumping within or out of its current scope, not into a deeper one.
740void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
741                               unsigned JumpDiagError, unsigned JumpDiagWarning,
742                                 unsigned JumpDiagCXX98Compat) {
743  if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
744    return;
745  if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
746    return;
747
748  unsigned FromScope = LabelAndGotoScopes[From];
749  unsigned ToScope = LabelAndGotoScopes[To];
750
751  // Common case: exactly the same scope, which is fine.
752  if (FromScope == ToScope) return;
753
754  unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
755
756  // It's okay to jump out from a nested scope.
757  if (CommonScope == ToScope) return;
758
759  // Pull out (and reverse) any scopes we might need to diagnose skipping.
760  SmallVector<unsigned, 10> ToScopesCXX98Compat;
761  SmallVector<unsigned, 10> ToScopesError;
762  SmallVector<unsigned, 10> ToScopesWarning;
763  for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
764    if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
765        IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
766      ToScopesWarning.push_back(I);
767    else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
768      ToScopesCXX98Compat.push_back(I);
769    else if (Scopes[I].InDiag)
770      ToScopesError.push_back(I);
771  }
772
773  // Handle warnings.
774  if (!ToScopesWarning.empty()) {
775    S.Diag(DiagLoc, JumpDiagWarning);
776    NoteJumpIntoScopes(ToScopesWarning);
777  }
778
779  // Handle errors.
780  if (!ToScopesError.empty()) {
781    S.Diag(DiagLoc, JumpDiagError);
782    NoteJumpIntoScopes(ToScopesError);
783  }
784
785  // Handle -Wc++98-compat warnings if the jump is well-formed.
786  if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
787    S.Diag(DiagLoc, JumpDiagCXX98Compat);
788    NoteJumpIntoScopes(ToScopesCXX98Compat);
789  }
790}
791
792void Sema::DiagnoseInvalidJumps(Stmt *Body) {
793  (void)JumpScopeChecker(Body, *this);
794}
795