blob: 565a610b8c2d49a03d510a589d070fb49c91a76a [file] [log] [blame]
Francois Pichet67bc6072011-09-09 11:02:57 +00001//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
Chris Lattner5af280c2009-04-19 04:46:21 +00002//
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
Francois Pichet67bc6072011-09-09 11:02:57 +000011// jumps that enter a protected scope in an invalid way.
Chris Lattner5af280c2009-04-19 04:46:21 +000012//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
John McCall384aff82010-08-25 07:42:41 +000016#include "clang/AST/DeclCXX.h"
Chris Lattner5af280c2009-04-19 04:46:21 +000017#include "clang/AST/Expr.h"
Douglas Gregore4135162011-05-27 16:05:29 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner16f00492009-04-26 01:32:48 +000019#include "clang/AST/StmtObjC.h"
Sebastian Redl972041f2009-04-27 20:27:31 +000020#include "clang/AST/StmtCXX.h"
Douglas Gregore737f502010-08-12 20:07:10 +000021#include "llvm/ADT/BitVector.h"
Chris Lattner5af280c2009-04-19 04:46:21 +000022using 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;
Mike Stump1eb44332009-09-09 15:08:12 +000034
Chris Lattner5af280c2009-04-19 04:46:21 +000035 /// 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;
Mike Stump1eb44332009-09-09 15:08:12 +000044
John McCallddb0b4d2010-05-12 00:58:13 +000045 /// InDiag - The diagnostic to emit if there is a jump into this scope.
46 unsigned InDiag;
47
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.
51 unsigned OutDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner5af280c2009-04-19 04:46:21 +000053 /// Loc - Location to emit the diagnostic.
54 SourceLocation Loc;
Mike Stump1eb44332009-09-09 15:08:12 +000055
John McCallddb0b4d2010-05-12 00:58:13 +000056 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
57 SourceLocation L)
58 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
Chris Lattner5af280c2009-04-19 04:46:21 +000059 };
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner5f9e2722011-07-23 10:55:15 +000061 SmallVector<GotoScope, 48> Scopes;
Chris Lattner5af280c2009-04-19 04:46:21 +000062 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
Chris Lattner5f9e2722011-07-23 10:55:15 +000063 SmallVector<Stmt*, 16> Jumps;
John McCallddb0b4d2010-05-12 00:58:13 +000064
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
66 SmallVector<LabelDecl*, 4> IndirectJumpTargets;
Chris Lattner5af280c2009-04-19 04:46:21 +000067public:
68 JumpScopeChecker(Stmt *Body, Sema &S);
69private:
Douglas Gregor43dec6b2010-06-21 23:44:13 +000070 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +000071 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
72 unsigned &ParentScope);
73 void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
74
Chris Lattner5af280c2009-04-19 04:46:21 +000075 void VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000076 void VerifyIndirectJumps();
77 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +000078 LabelDecl *Target, unsigned TargetScope);
Francois Pichetc985b882011-09-13 10:26:51 +000079 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
80 unsigned JumpDiag, unsigned JumpDiagWarning);
John McCall5e2a7ac2010-05-12 02:37:54 +000081
82 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
Chris Lattner5af280c2009-04-19 04:46:21 +000083};
84} // end anonymous namespace
85
86
87JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
88 // Add a scope entry for function scope.
John McCallddb0b4d2010-05-12 00:58:13 +000089 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner5af280c2009-04-19 04:46:21 +000091 // Build information for the top level compound statement, so that we have a
92 // defined scope record for every "goto" and label.
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +000093 unsigned BodyParentScope = 0;
94 BuildScopeInformation(Body, BodyParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner5af280c2009-04-19 04:46:21 +000096 // Check that all jumps we saw are kosher.
97 VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000098 VerifyIndirectJumps();
Chris Lattner5af280c2009-04-19 04:46:21 +000099}
Mike Stump1eb44332009-09-09 15:08:12 +0000100
John McCall5e2a7ac2010-05-12 02:37:54 +0000101/// GetDeepestCommonScope - Finds the innermost scope enclosing the
102/// two scopes.
103unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
104 while (A != B) {
105 // Inner scopes are created after outer scopes and therefore have
106 // higher indices.
107 if (A < B) {
108 assert(Scopes[B].ParentScope < B);
109 B = Scopes[B].ParentScope;
110 } else {
111 assert(Scopes[A].ParentScope < A);
112 A = Scopes[A].ParentScope;
113 }
114 }
115 return A;
116}
117
John McCallf85e1932011-06-15 23:02:42 +0000118typedef std::pair<unsigned,unsigned> ScopePair;
119
Chris Lattner5af280c2009-04-19 04:46:21 +0000120/// 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.
John McCallf85e1932011-06-15 23:02:42 +0000122static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
Chris Lattner5af280c2009-04-19 04:46:21 +0000123 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000124 unsigned InDiag = 0, OutDiag = 0;
Chris Lattner5af280c2009-04-19 04:46:21 +0000125 if (VD->getType()->isVariablyModifiedType())
John McCallddb0b4d2010-05-12 00:58:13 +0000126 InDiag = diag::note_protected_by_vla;
127
John McCallf85e1932011-06-15 23:02:42 +0000128 if (VD->hasAttr<BlocksAttr>())
129 return ScopePair(diag::note_protected_by___block,
130 diag::note_exits___block);
131
132 if (VD->hasAttr<CleanupAttr>())
133 return ScopePair(diag::note_protected_by_cleanup,
134 diag::note_exits_cleanup);
135
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:
141 break;
142
143 case Qualifiers::OCL_Strong:
144 case Qualifiers::OCL_Weak:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000145 return ScopePair(diag::note_protected_by_objc_ownership,
146 diag::note_exits_objc_ownership);
John McCallf85e1932011-06-15 23:02:42 +0000147 }
148 }
149
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.
158
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.
164
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;
172
173 const CXXRecordDecl *record = 0;
174
175 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(init)) {
176 const CXXConstructorDecl *ctor = cce->getConstructor();
177 record = ctor->getParent();
178
179 if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
180 if (Context.getLangOptions().CPlusPlus0x) {
181 inDiagToUse = (record->hasTrivialDestructor() ? 0 :
182 diag::note_protected_by_variable_nontriv_destructor);
183 } else {
184 if (record->isPOD())
185 inDiagToUse = 0;
186 }
Douglas Gregore4135162011-05-27 16:05:29 +0000187 }
John McCallf85e1932011-06-15 23:02:42 +0000188 } else if (VD->getType()->isArrayType()) {
189 record = VD->getType()->getBaseElementTypeUnsafe()
190 ->getAsCXXRecordDecl();
Douglas Gregore4135162011-05-27 16:05:29 +0000191 }
John McCallf85e1932011-06-15 23:02:42 +0000192
193 if (inDiagToUse)
194 InDiag = inDiagToUse;
195
196 // Also object to indirect jumps which leave scopes with dtors.
197 if (record && !record->hasTrivialDestructor())
Douglas Gregorf61103e2011-05-27 21:28:00 +0000198 OutDiag = diag::note_exits_dtor;
Douglas Gregor025291b2010-07-01 00:21:21 +0000199 }
John McCallddb0b4d2010-05-12 00:58:13 +0000200 }
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000201
John McCallf85e1932011-06-15 23:02:42 +0000202 return ScopePair(InDiag, OutDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000203 }
Mike Stump1eb44332009-09-09 15:08:12 +0000204
John McCallddb0b4d2010-05-12 00:58:13 +0000205 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
206 if (TD->getUnderlyingType()->isVariablyModifiedType())
John McCallf85e1932011-06-15 23:02:42 +0000207 return ScopePair(diag::note_protected_by_vla_typedef, 0);
John McCallddb0b4d2010-05-12 00:58:13 +0000208 }
209
Richard Smith162e1c12011-04-15 14:24:37 +0000210 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
211 if (TD->getUnderlyingType()->isVariablyModifiedType())
John McCallf85e1932011-06-15 23:02:42 +0000212 return ScopePair(diag::note_protected_by_vla_type_alias, 0);
Richard Smith162e1c12011-04-15 14:24:37 +0000213 }
214
John McCallf85e1932011-06-15 23:02:42 +0000215 return ScopePair(0U, 0U);
Chris Lattner5af280c2009-04-19 04:46:21 +0000216}
217
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000218/// \brief Build scope information for a declaration that is part of a DeclStmt.
219void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000220 // If this decl causes a new scope, push and switch to it.
John McCallf85e1932011-06-15 23:02:42 +0000221 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D);
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000222 if (Diags.first || Diags.second) {
223 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
224 D->getLocation()));
225 ParentScope = Scopes.size()-1;
226 }
227
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);
233}
Chris Lattner5af280c2009-04-19 04:46:21 +0000234
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000235/// \brief Build scope information for a captured block literal variables.
236void 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>())
242 return;
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);
251 break;
252 case QualType::DK_objc_strong_lifetime:
253 Diags = ScopePair(diag::note_enters_block_captures_strong,
254 diag::note_exits_block_captures_strong);
255 break;
256 case QualType::DK_objc_weak_lifetime:
257 Diags = ScopePair(diag::note_enters_block_captures_weak,
258 diag::note_exits_block_captures_weak);
259 break;
260 case QualType::DK_none:
261 llvm_unreachable("no-liftime captured variable");
262 }
263 SourceLocation Loc = D->getLocation();
264 if (Loc.isInvalid())
265 Loc = BDecl->getLocation();
266 Scopes.push_back(GotoScope(ParentScope,
267 Diags.first, Diags.second, Loc));
268 ParentScope = Scopes.size()-1;
269 }
270}
271
Chris Lattner5af280c2009-04-19 04:46:21 +0000272/// 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.
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000276void 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);
283
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000284 bool SkipFirstSubStmt = false;
285
Chris Lattner5af280c2009-04-19 04:46:21 +0000286 // If we found a label, remember that it is in ParentScope scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000287 switch (S->getStmtClass()) {
John McCallddb0b4d2010-05-12 00:58:13 +0000288 case Stmt::AddrLabelExprClass:
289 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
290 break;
291
292 case Stmt::IndirectGotoStmtClass:
John McCall95c225d2010-10-28 08:53:48 +0000293 // "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;
300 Jumps.push_back(S);
301 return;
302 }
303
John McCallddb0b4d2010-05-12 00:58:13 +0000304 LabelAndGotoScopes[S] = ParentScope;
305 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
306 break;
307
John McCallddb0b4d2010-05-12 00:58:13 +0000308 case Stmt::SwitchStmtClass:
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000309 // Evaluate the condition variable before entering the scope of the switch
310 // statement.
311 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
312 BuildScopeInformation(Var, ParentScope);
313 SkipFirstSubStmt = true;
314 }
315 // Fall through
316
317 case Stmt::GotoStmtClass:
Chris Lattner5af280c2009-04-19 04:46:21 +0000318 // 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;
321 Jumps.push_back(S);
John McCallddb0b4d2010-05-12 00:58:13 +0000322 break;
323
324 default:
325 break;
Chris Lattner5af280c2009-04-19 04:46:21 +0000326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall7502c1d2011-02-13 04:07:26 +0000328 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000329 if (SkipFirstSubStmt) {
330 SkipFirstSubStmt = false;
331 continue;
332 }
333
Chris Lattner5af280c2009-04-19 04:46:21 +0000334 Stmt *SubStmt = *CI;
335 if (SubStmt == 0) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
John McCall97ba4812010-08-02 23:33:14 +0000337 // 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.
340 while (true) {
341 Stmt *Next;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000342 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();
John McCall97ba4812010-08-02 23:33:14 +0000348 else
349 break;
350
351 LabelAndGotoScopes[SubStmt] = ParentScope;
352 SubStmt = Next;
353 }
354
Chris Lattner5af280c2009-04-19 04:46:21 +0000355 // 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)) {
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000358 // The decl statement creates a scope if any of the decls in it are VLAs
359 // or have the cleanup attribute.
Chris Lattner5af280c2009-04-19 04:46:21 +0000360 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000361 I != E; ++I)
362 BuildScopeInformation(*I, ParentScope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000363 continue;
364 }
Chris Lattner5af280c2009-04-19 04:46:21 +0000365 // 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)) {
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000368 unsigned newParentScope;
Chris Lattner5af280c2009-04-19 04:46:21 +0000369 // Recursively walk the AST for the @try part.
John McCallddb0b4d2010-05-12 00:58:13 +0000370 Scopes.push_back(GotoScope(ParentScope,
371 diag::note_protected_by_objc_try,
372 diag::note_exits_objc_try,
Chris Lattner5af280c2009-04-19 04:46:21 +0000373 AT->getAtTryLoc()));
374 if (Stmt *TryPart = AT->getTryBody())
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000375 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
Chris Lattner5af280c2009-04-19 04:46:21 +0000376
377 // Jump from the catch to the finally or try is not valid.
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +0000378 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
379 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000380 Scopes.push_back(GotoScope(ParentScope,
381 diag::note_protected_by_objc_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000382 diag::note_exits_objc_catch,
Chris Lattner5af280c2009-04-19 04:46:21 +0000383 AC->getAtCatchLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +0000384 // @catches are nested and it isn't
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000385 BuildScopeInformation(AC->getCatchBody(),
386 (newParentScope = Scopes.size()-1));
Chris Lattner5af280c2009-04-19 04:46:21 +0000387 }
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner5af280c2009-04-19 04:46:21 +0000389 // 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,
John McCallddb0b4d2010-05-12 00:58:13 +0000393 diag::note_exits_objc_finally,
Chris Lattner5af280c2009-04-19 04:46:21 +0000394 AF->getAtFinallyLoc()));
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000395 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
Chris Lattner5af280c2009-04-19 04:46:21 +0000396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner5af280c2009-04-19 04:46:21 +0000398 continue;
399 }
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000400
401 unsigned newParentScope;
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000402 // 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);
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000409 // Recursively walk the AST for the @synchronized part, protected by a new
410 // scope.
411 Scopes.push_back(GotoScope(ParentScope,
412 diag::note_protected_by_objc_synchronized,
John McCallddb0b4d2010-05-12 00:58:13 +0000413 diag::note_exits_objc_synchronized,
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000414 AS->getAtSynchronizedLoc()));
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000415 BuildScopeInformation(AS->getSynchBody(),
416 (newParentScope = Scopes.size()-1));
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000417 continue;
418 }
Sebastian Redl972041f2009-04-27 20:27:31 +0000419
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)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000423 Scopes.push_back(GotoScope(ParentScope,
424 diag::note_protected_by_cxx_try,
425 diag::note_exits_cxx_try,
Sebastian Redl972041f2009-04-27 20:27:31 +0000426 TS->getSourceRange().getBegin()));
427 if (Stmt *TryBlock = TS->getTryBlock())
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000428 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
Sebastian Redl972041f2009-04-27 20:27:31 +0000429
430 // Jump from the catch into the try is not allowed either.
Mike Stump1eb44332009-09-09 15:08:12 +0000431 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000432 CXXCatchStmt *CS = TS->getHandler(I);
433 Scopes.push_back(GotoScope(ParentScope,
434 diag::note_protected_by_cxx_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000435 diag::note_exits_cxx_catch,
Sebastian Redl972041f2009-04-27 20:27:31 +0000436 CS->getSourceRange().getBegin()));
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000437 BuildScopeInformation(CS->getHandlerBlock(),
438 (newParentScope = Scopes.size()-1));
Sebastian Redl972041f2009-04-27 20:27:31 +0000439 }
440
441 continue;
442 }
443
John McCallf85e1932011-06-15 23:02:42 +0000444 // 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
447 // scope.
448 Scopes.push_back(GotoScope(ParentScope,
449 diag::note_protected_by_objc_autoreleasepool,
450 diag::note_exits_objc_autoreleasepool,
451 AS->getAtLoc()));
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000452 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
John McCallf85e1932011-06-15 23:02:42 +0000453 continue;
454 }
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +0000455
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);
462 }
463 }
464
Chris Lattner5af280c2009-04-19 04:46:21 +0000465 // Recursively walk the AST.
466 BuildScopeInformation(SubStmt, ParentScope);
467 }
468}
469
470/// VerifyJumps - Verify each element of the Jumps array to see if they are
471/// valid, emitting diagnostics if not.
472void JumpScopeChecker::VerifyJumps() {
473 while (!Jumps.empty()) {
474 Stmt *Jump = Jumps.pop_back_val();
Mike Stump1eb44332009-09-09 15:08:12 +0000475
476 // With a goto,
Chris Lattner5af280c2009-04-19 04:46:21 +0000477 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000478 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
Francois Pichetc985b882011-09-13 10:26:51 +0000479 diag::err_goto_into_protected_scope,
480 diag::warn_goto_into_protected_scope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000481 continue;
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
John McCall95c225d2010-10-28 08:53:48 +0000484 // We only get indirect gotos here when they have a constant target.
485 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000486 LabelDecl *Target = IGS->getConstantTarget();
487 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
Francois Pichetc985b882011-09-13 10:26:51 +0000488 diag::err_goto_into_protected_scope, 0);
John McCall95c225d2010-10-28 08:53:48 +0000489 continue;
490 }
491
John McCallddb0b4d2010-05-12 00:58:13 +0000492 SwitchStmt *SS = cast<SwitchStmt>(Jump);
493 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
494 SC = SC->getNextSwitchCase()) {
495 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
496 CheckJump(SS, SC, SC->getLocStart(),
Francois Pichetc985b882011-09-13 10:26:51 +0000497 diag::err_switch_into_protected_scope, 0);
Chris Lattner5af280c2009-04-19 04:46:21 +0000498 }
499 }
500}
501
John McCall5e2a7ac2010-05-12 02:37:54 +0000502/// VerifyIndirectJumps - Verify whether any possible indirect jump
503/// might cross a protection boundary. Unlike direct jumps, indirect
504/// jumps count cleanups as protection boundaries: since there's no
505/// way to know where the jump is going, we can't implicitly run the
506/// right cleanups the way we can with direct jumps.
John McCallddb0b4d2010-05-12 00:58:13 +0000507///
John McCall5e2a7ac2010-05-12 02:37:54 +0000508/// Thus, an indirect jump is "trivial" if it bypasses no
509/// initializations and no teardowns. More formally, an indirect jump
510/// from A to B is trivial if the path out from A to DCA(A,B) is
511/// trivial and the path in from DCA(A,B) to B is trivial, where
512/// DCA(A,B) is the deepest common ancestor of A and B.
513/// Jump-triviality is transitive but asymmetric.
514///
John McCallddb0b4d2010-05-12 00:58:13 +0000515/// A path in is trivial if none of the entered scopes have an InDiag.
516/// A path out is trivial is none of the exited scopes have an OutDiag.
John McCall5e2a7ac2010-05-12 02:37:54 +0000517///
518/// Under these definitions, this function checks that the indirect
519/// jump between A and B is trivial for every indirect goto statement A
520/// and every label B whose address was taken in the function.
John McCallddb0b4d2010-05-12 00:58:13 +0000521void JumpScopeChecker::VerifyIndirectJumps() {
522 if (IndirectJumps.empty()) return;
523
524 // If there aren't any address-of-label expressions in this function,
525 // complain about the first indirect goto.
526 if (IndirectJumpTargets.empty()) {
527 S.Diag(IndirectJumps[0]->getGotoLoc(),
528 diag::err_indirect_goto_without_addrlabel);
529 return;
530 }
531
John McCall5e2a7ac2010-05-12 02:37:54 +0000532 // Collect a single representative of every scope containing an
533 // indirect goto. For most code bases, this substantially cuts
534 // down on the number of jump sites we'll have to consider later.
John McCallddb0b4d2010-05-12 00:58:13 +0000535 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000536 SmallVector<JumpScope, 32> JumpScopes;
John McCallddb0b4d2010-05-12 00:58:13 +0000537 {
538 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000539 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000540 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
541 IndirectGotoStmt *IG = *I;
542 assert(LabelAndGotoScopes.count(IG) &&
543 "indirect jump didn't get added to scopes?");
544 unsigned IGScope = LabelAndGotoScopes[IG];
545 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
546 if (!Entry) Entry = IG;
547 }
548 JumpScopes.reserve(JumpScopesMap.size());
549 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
550 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
551 JumpScopes.push_back(*I);
552 }
553
John McCall5e2a7ac2010-05-12 02:37:54 +0000554 // Collect a single representative of every scope containing a
555 // label whose address was taken somewhere in the function.
556 // For most code bases, there will be only one such scope.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000557 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000558 for (SmallVectorImpl<LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000559 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
560 I != E; ++I) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000561 LabelDecl *TheLabel = *I;
562 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
John McCallddb0b4d2010-05-12 00:58:13 +0000563 "Referenced label didn't get added to scopes?");
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000564 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
565 LabelDecl *&Target = TargetScopes[LabelScope];
John McCallddb0b4d2010-05-12 00:58:13 +0000566 if (!Target) Target = TheLabel;
567 }
568
John McCall5e2a7ac2010-05-12 02:37:54 +0000569 // For each target scope, make sure it's trivially reachable from
570 // every scope containing a jump site.
571 //
572 // A path between scopes always consists of exitting zero or more
573 // scopes, then entering zero or more scopes. We build a set of
574 // of scopes S from which the target scope can be trivially
575 // entered, then verify that every jump scope can be trivially
576 // exitted to reach a scope in S.
John McCallddb0b4d2010-05-12 00:58:13 +0000577 llvm::BitVector Reachable(Scopes.size(), false);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000578 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000579 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
580 unsigned TargetScope = TI->first;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000581 LabelDecl *TargetLabel = TI->second;
John McCallddb0b4d2010-05-12 00:58:13 +0000582
583 Reachable.reset();
584
585 // Mark all the enclosing scopes from which you can safely jump
John McCall5e2a7ac2010-05-12 02:37:54 +0000586 // into the target scope. 'Min' will end up being the index of
587 // the shallowest such scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000588 unsigned Min = TargetScope;
589 while (true) {
590 Reachable.set(Min);
591
592 // Don't go beyond the outermost scope.
593 if (Min == 0) break;
594
John McCall5e2a7ac2010-05-12 02:37:54 +0000595 // Stop if we can't trivially enter the current scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000596 if (Scopes[Min].InDiag) break;
597
598 Min = Scopes[Min].ParentScope;
599 }
600
601 // Walk through all the jump sites, checking that they can trivially
602 // reach this label scope.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000603 for (SmallVectorImpl<JumpScope>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000604 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
605 unsigned Scope = I->first;
606
607 // Walk out the "scope chain" for this scope, looking for a scope
John McCall5e2a7ac2010-05-12 02:37:54 +0000608 // we've marked reachable. For well-formed code this amortizes
609 // to O(JumpScopes.size() / Scopes.size()): we only iterate
610 // when we see something unmarked, and in well-formed code we
611 // mark everything we iterate past.
John McCallddb0b4d2010-05-12 00:58:13 +0000612 bool IsReachable = false;
613 while (true) {
614 if (Reachable.test(Scope)) {
615 // If we find something reachable, mark all the scopes we just
616 // walked through as reachable.
617 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
618 Reachable.set(S);
619 IsReachable = true;
620 break;
621 }
622
623 // Don't walk out if we've reached the top-level scope or we've
624 // gotten shallower than the shallowest reachable scope.
625 if (Scope == 0 || Scope < Min) break;
626
627 // Don't walk out through an out-diagnostic.
628 if (Scopes[Scope].OutDiag) break;
629
630 Scope = Scopes[Scope].ParentScope;
631 }
632
633 // Only diagnose if we didn't find something.
634 if (IsReachable) continue;
635
636 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
637 }
638 }
639}
640
John McCall5e2a7ac2010-05-12 02:37:54 +0000641/// Diagnose an indirect jump which is known to cross scopes.
John McCallddb0b4d2010-05-12 00:58:13 +0000642void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
643 unsigned JumpScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000644 LabelDecl *Target,
John McCallddb0b4d2010-05-12 00:58:13 +0000645 unsigned TargetScope) {
646 assert(JumpScope != TargetScope);
647
John McCall95c225d2010-10-28 08:53:48 +0000648 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000649 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
John McCallddb0b4d2010-05-12 00:58:13 +0000650
John McCall5e2a7ac2010-05-12 02:37:54 +0000651 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
John McCallddb0b4d2010-05-12 00:58:13 +0000652
John McCall5e2a7ac2010-05-12 02:37:54 +0000653 // Walk out the scope chain until we reach the common ancestor.
654 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
655 if (Scopes[I].OutDiag)
656 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000657
658 // Now walk into the scopes containing the label whose address was taken.
John McCall5e2a7ac2010-05-12 02:37:54 +0000659 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
660 if (Scopes[I].InDiag)
661 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000662}
663
Francois Pichetc985b882011-09-13 10:26:51 +0000664/// Return true if a particular error+note combination must be downgraded
665/// to a warning in Microsoft mode.
666static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote)
667{
668 return (JumpDiag == diag::err_goto_into_protected_scope &&
669 (InDiagNote == diag::note_protected_by_variable_init ||
670 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
671}
672
673
Chris Lattner5af280c2009-04-19 04:46:21 +0000674/// CheckJump - Validate that the specified jump statement is valid: that it is
675/// jumping within or out of its current scope, not into a deeper one.
Francois Pichetc985b882011-09-13 10:26:51 +0000676void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
677 unsigned JumpDiagError, unsigned JumpDiagWarning) {
Chris Lattner5af280c2009-04-19 04:46:21 +0000678 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
679 unsigned FromScope = LabelAndGotoScopes[From];
680
681 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
682 unsigned ToScope = LabelAndGotoScopes[To];
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner5af280c2009-04-19 04:46:21 +0000684 // Common case: exactly the same scope, which is fine.
685 if (FromScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
John McCall5e2a7ac2010-05-12 02:37:54 +0000687 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000688
John McCall5e2a7ac2010-05-12 02:37:54 +0000689 // It's okay to jump out from a nested scope.
690 if (CommonScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
John McCall5e2a7ac2010-05-12 02:37:54 +0000692 // Pull out (and reverse) any scopes we might need to diagnose skipping.
Francois Pichetc985b882011-09-13 10:26:51 +0000693 SmallVector<unsigned, 10> ToScopesError;
694 SmallVector<unsigned, 10> ToScopesWarning;
695 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
696 if (S.getLangOptions().Microsoft &&
697 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
698 ToScopesWarning.push_back(I);
699 else if (Scopes[I].InDiag)
700 ToScopesError.push_back(I);
701 }
Chris Lattner5af280c2009-04-19 04:46:21 +0000702
Francois Pichetc985b882011-09-13 10:26:51 +0000703 // Handle warnings.
704 if (!ToScopesWarning.empty()) {
705 S.Diag(DiagLoc, JumpDiagWarning);
706 for (unsigned i = 0, e = ToScopesWarning.size(); i != e; ++i)
707 S.Diag(Scopes[ToScopesWarning[i]].Loc, Scopes[ToScopesWarning[i]].InDiag);
708 }
John McCallddb0b4d2010-05-12 00:58:13 +0000709
Francois Pichetc985b882011-09-13 10:26:51 +0000710 // Handle errors.
711 if (!ToScopesError.empty()) {
712 S.Diag(DiagLoc, JumpDiagError);
713 // Emit diagnostics note for whatever is left in ToScopesError.
714 for (unsigned i = 0, e = ToScopesError.size(); i != e; ++i)
715 S.Diag(Scopes[ToScopesError[i]].Loc, Scopes[ToScopesError[i]].InDiag);
716 }
Chris Lattner5af280c2009-04-19 04:46:21 +0000717}
718
719void Sema::DiagnoseInvalidJumps(Stmt *Body) {
Douglas Gregor6490ae52009-11-17 06:14:37 +0000720 (void)JumpScopeChecker(Body, *this);
Chris Lattner5af280c2009-04-19 04:46:21 +0000721}