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