blob: 679f4fefa22dbadb9e4a5d80486b015113da70f4 [file] [log] [blame]
Chris Lattner5af280c2009-04-19 04:46:21 +00001//===--- JumpDiagnostics.cpp - Analyze Jump Targets for VLA issues --------===//
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 VLA scope in an invalid way.
12//
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 Lattner5af280c2009-04-19 04:46:21 +000061 llvm::SmallVector<GotoScope, 48> Scopes;
62 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
63 llvm::SmallVector<Stmt*, 16> Jumps;
John McCallddb0b4d2010-05-12 00:58:13 +000064
65 llvm::SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
Chris Lattnerad8dcf42011-02-17 07:39:24 +000066 llvm::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);
Chris Lattner5af280c2009-04-19 04:46:21 +000071 void BuildScopeInformation(Stmt *S, unsigned ParentScope);
72 void VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000073 void VerifyIndirectJumps();
74 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +000075 LabelDecl *Target, unsigned TargetScope);
Chris Lattner5af280c2009-04-19 04:46:21 +000076 void CheckJump(Stmt *From, Stmt *To,
77 SourceLocation DiagLoc, unsigned JumpDiag);
John McCall5e2a7ac2010-05-12 02:37:54 +000078
79 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
Chris Lattner5af280c2009-04-19 04:46:21 +000080};
81} // end anonymous namespace
82
83
84JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
85 // Add a scope entry for function scope.
John McCallddb0b4d2010-05-12 00:58:13 +000086 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +000087
Chris Lattner5af280c2009-04-19 04:46:21 +000088 // Build information for the top level compound statement, so that we have a
89 // defined scope record for every "goto" and label.
90 BuildScopeInformation(Body, 0);
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattner5af280c2009-04-19 04:46:21 +000092 // Check that all jumps we saw are kosher.
93 VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000094 VerifyIndirectJumps();
Chris Lattner5af280c2009-04-19 04:46:21 +000095}
Mike Stump1eb44332009-09-09 15:08:12 +000096
John McCall5e2a7ac2010-05-12 02:37:54 +000097/// GetDeepestCommonScope - Finds the innermost scope enclosing the
98/// two scopes.
99unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
100 while (A != B) {
101 // Inner scopes are created after outer scopes and therefore have
102 // higher indices.
103 if (A < B) {
104 assert(Scopes[B].ParentScope < B);
105 B = Scopes[B].ParentScope;
106 } else {
107 assert(Scopes[A].ParentScope < A);
108 A = Scopes[A].ParentScope;
109 }
110 }
111 return A;
112}
113
Chris Lattner5af280c2009-04-19 04:46:21 +0000114/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
115/// diagnostic that should be emitted if control goes over it. If not, return 0.
John McCallddb0b4d2010-05-12 00:58:13 +0000116static std::pair<unsigned,unsigned>
117 GetDiagForGotoScopeDecl(const Decl *D, bool isCPlusPlus) {
Chris Lattner5af280c2009-04-19 04:46:21 +0000118 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000119 unsigned InDiag = 0, OutDiag = 0;
Chris Lattner5af280c2009-04-19 04:46:21 +0000120 if (VD->getType()->isVariablyModifiedType())
John McCallddb0b4d2010-05-12 00:58:13 +0000121 InDiag = diag::note_protected_by_vla;
122
123 if (VD->hasAttr<BlocksAttr>()) {
124 InDiag = diag::note_protected_by___block;
125 OutDiag = diag::note_exits___block;
126 } else if (VD->hasAttr<CleanupAttr>()) {
127 InDiag = diag::note_protected_by_cleanup;
128 OutDiag = diag::note_exits_cleanup;
129 } else if (isCPlusPlus) {
Douglas Gregore4135162011-05-27 16:05:29 +0000130 if (!VD->hasLocalStorage())
131 return std::make_pair(InDiag, OutDiag);
132
133 ASTContext &Context = D->getASTContext();
134 QualType T = Context.getBaseElementType(VD->getType());
Douglas Gregor025291b2010-07-01 00:21:21 +0000135 if (!T->isDependentType()) {
Douglas Gregore4135162011-05-27 16:05:29 +0000136 // C++0x [stmt.dcl]p3:
137 // A program that jumps from a point where a variable with automatic
138 // storage duration is not in scope to a point where it is in scope
139 // is ill-formed unless the variable has scalar type, class type with
140 // a trivial default constructor and a trivial destructor, a
141 // cv-qualified version of one of these types, or an array of one of
142 // the preceding types and is declared without an initializer (8.5).
Douglas Gregorf61103e2011-05-27 21:28:00 +0000143 // Check whether this is a C++ class.
144 CXXRecordDecl *Record = T->getAsCXXRecordDecl();
145
146 if (const Expr *Init = VD->getInit()) {
147 bool CallsTrivialConstructor = false;
148 if (Record) {
149 // FIXME: With generalized initializer lists, this may
150 // classify "X x{};" as having no initializer.
151 if (const CXXConstructExpr *Construct
152 = dyn_cast<CXXConstructExpr>(Init))
153 if (const CXXConstructorDecl *Constructor
154 = Construct->getConstructor())
Douglas Gregor9787f9b2011-05-27 23:15:17 +0000155 if ((Context.getLangOptions().CPlusPlus0x
156 ? Record->hasTrivialDefaultConstructor()
157 : Record->isPOD()) &&
158 Constructor->isDefaultConstructor())
Douglas Gregorf61103e2011-05-27 21:28:00 +0000159 CallsTrivialConstructor = true;
Douglas Gregor1454cb92011-06-15 03:23:34 +0000160
161 if (CallsTrivialConstructor && !Record->hasTrivialDestructor())
162 InDiag = diag::note_protected_by_variable_nontriv_destructor;
Douglas Gregore4135162011-05-27 16:05:29 +0000163 }
164
Douglas Gregorf61103e2011-05-27 21:28:00 +0000165 if (!CallsTrivialConstructor)
166 InDiag = diag::note_protected_by_variable_init;
Douglas Gregore4135162011-05-27 16:05:29 +0000167 }
Douglas Gregorf61103e2011-05-27 21:28:00 +0000168
169 // Note whether we have a class with a non-trivial destructor.
170 if (Record && !Record->hasTrivialDestructor())
171 OutDiag = diag::note_exits_dtor;
Douglas Gregor025291b2010-07-01 00:21:21 +0000172 }
John McCallddb0b4d2010-05-12 00:58:13 +0000173 }
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000174
John McCallddb0b4d2010-05-12 00:58:13 +0000175 return std::make_pair(InDiag, OutDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000176 }
Mike Stump1eb44332009-09-09 15:08:12 +0000177
John McCallddb0b4d2010-05-12 00:58:13 +0000178 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
179 if (TD->getUnderlyingType()->isVariablyModifiedType())
180 return std::make_pair((unsigned) diag::note_protected_by_vla_typedef, 0);
181 }
182
Richard Smith162e1c12011-04-15 14:24:37 +0000183 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
184 if (TD->getUnderlyingType()->isVariablyModifiedType())
185 return std::make_pair((unsigned) diag::note_protected_by_vla_type_alias, 0);
186 }
187
John McCallddb0b4d2010-05-12 00:58:13 +0000188 return std::make_pair(0U, 0U);
Chris Lattner5af280c2009-04-19 04:46:21 +0000189}
190
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000191/// \brief Build scope information for a declaration that is part of a DeclStmt.
192void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
193 bool isCPlusPlus = this->S.getLangOptions().CPlusPlus;
194
195 // If this decl causes a new scope, push and switch to it.
196 std::pair<unsigned,unsigned> Diags
197 = GetDiagForGotoScopeDecl(D, isCPlusPlus);
198 if (Diags.first || Diags.second) {
199 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
200 D->getLocation()));
201 ParentScope = Scopes.size()-1;
202 }
203
204 // If the decl has an initializer, walk it with the potentially new
205 // scope we just installed.
206 if (VarDecl *VD = dyn_cast<VarDecl>(D))
207 if (Expr *Init = VD->getInit())
208 BuildScopeInformation(Init, ParentScope);
209}
Chris Lattner5af280c2009-04-19 04:46:21 +0000210
211/// BuildScopeInformation - The statements from CI to CE are known to form a
212/// coherent VLA scope with a specified parent node. Walk through the
213/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
214/// walking the AST as needed.
215void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000216 bool SkipFirstSubStmt = false;
217
Chris Lattner5af280c2009-04-19 04:46:21 +0000218 // If we found a label, remember that it is in ParentScope scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000219 switch (S->getStmtClass()) {
John McCallddb0b4d2010-05-12 00:58:13 +0000220 case Stmt::AddrLabelExprClass:
221 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
222 break;
223
224 case Stmt::IndirectGotoStmtClass:
John McCall95c225d2010-10-28 08:53:48 +0000225 // "goto *&&lbl;" is a special case which we treat as equivalent
226 // to a normal goto. In addition, we don't calculate scope in the
227 // operand (to avoid recording the address-of-label use), which
228 // works only because of the restricted set of expressions which
229 // we detect as constant targets.
230 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
231 LabelAndGotoScopes[S] = ParentScope;
232 Jumps.push_back(S);
233 return;
234 }
235
John McCallddb0b4d2010-05-12 00:58:13 +0000236 LabelAndGotoScopes[S] = ParentScope;
237 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
238 break;
239
John McCallddb0b4d2010-05-12 00:58:13 +0000240 case Stmt::SwitchStmtClass:
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000241 // Evaluate the condition variable before entering the scope of the switch
242 // statement.
243 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
244 BuildScopeInformation(Var, ParentScope);
245 SkipFirstSubStmt = true;
246 }
247 // Fall through
248
249 case Stmt::GotoStmtClass:
Chris Lattner5af280c2009-04-19 04:46:21 +0000250 // Remember both what scope a goto is in as well as the fact that we have
251 // it. This makes the second scan not have to walk the AST again.
252 LabelAndGotoScopes[S] = ParentScope;
253 Jumps.push_back(S);
John McCallddb0b4d2010-05-12 00:58:13 +0000254 break;
255
256 default:
257 break;
Chris Lattner5af280c2009-04-19 04:46:21 +0000258 }
Mike Stump1eb44332009-09-09 15:08:12 +0000259
John McCall7502c1d2011-02-13 04:07:26 +0000260 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000261 if (SkipFirstSubStmt) {
262 SkipFirstSubStmt = false;
263 continue;
264 }
265
Chris Lattner5af280c2009-04-19 04:46:21 +0000266 Stmt *SubStmt = *CI;
267 if (SubStmt == 0) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
John McCall97ba4812010-08-02 23:33:14 +0000269 // Cases, labels, and defaults aren't "scope parents". It's also
270 // important to handle these iteratively instead of recursively in
271 // order to avoid blowing out the stack.
272 while (true) {
273 Stmt *Next;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000274 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
275 Next = CS->getSubStmt();
276 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
277 Next = DS->getSubStmt();
278 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
279 Next = LS->getSubStmt();
John McCall97ba4812010-08-02 23:33:14 +0000280 else
281 break;
282
283 LabelAndGotoScopes[SubStmt] = ParentScope;
284 SubStmt = Next;
285 }
286
Chris Lattner5af280c2009-04-19 04:46:21 +0000287 // If this is a declstmt with a VLA definition, it defines a scope from here
288 // to the end of the containing context.
289 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000290 // The decl statement creates a scope if any of the decls in it are VLAs
291 // or have the cleanup attribute.
Chris Lattner5af280c2009-04-19 04:46:21 +0000292 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000293 I != E; ++I)
294 BuildScopeInformation(*I, ParentScope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000295 continue;
296 }
297
298 // Disallow jumps into any part of an @try statement by pushing a scope and
299 // walking all sub-stmts in that scope.
300 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
301 // Recursively walk the AST for the @try part.
John McCallddb0b4d2010-05-12 00:58:13 +0000302 Scopes.push_back(GotoScope(ParentScope,
303 diag::note_protected_by_objc_try,
304 diag::note_exits_objc_try,
Chris Lattner5af280c2009-04-19 04:46:21 +0000305 AT->getAtTryLoc()));
306 if (Stmt *TryPart = AT->getTryBody())
307 BuildScopeInformation(TryPart, Scopes.size()-1);
308
309 // Jump from the catch to the finally or try is not valid.
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +0000310 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
311 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000312 Scopes.push_back(GotoScope(ParentScope,
313 diag::note_protected_by_objc_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000314 diag::note_exits_objc_catch,
Chris Lattner5af280c2009-04-19 04:46:21 +0000315 AC->getAtCatchLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +0000316 // @catches are nested and it isn't
Chris Lattner5af280c2009-04-19 04:46:21 +0000317 BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattner5af280c2009-04-19 04:46:21 +0000320 // Jump from the finally to the try or catch is not valid.
321 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
322 Scopes.push_back(GotoScope(ParentScope,
323 diag::note_protected_by_objc_finally,
John McCallddb0b4d2010-05-12 00:58:13 +0000324 diag::note_exits_objc_finally,
Chris Lattner5af280c2009-04-19 04:46:21 +0000325 AF->getAtFinallyLoc()));
326 BuildScopeInformation(AF, Scopes.size()-1);
327 }
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattner5af280c2009-04-19 04:46:21 +0000329 continue;
330 }
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000332 // Disallow jumps into the protected statement of an @synchronized, but
333 // allow jumps into the object expression it protects.
334 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
335 // Recursively walk the AST for the @synchronized object expr, it is
336 // evaluated in the normal scope.
337 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000339 // Recursively walk the AST for the @synchronized part, protected by a new
340 // scope.
341 Scopes.push_back(GotoScope(ParentScope,
342 diag::note_protected_by_objc_synchronized,
John McCallddb0b4d2010-05-12 00:58:13 +0000343 diag::note_exits_objc_synchronized,
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000344 AS->getAtSynchronizedLoc()));
345 BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1);
346 continue;
347 }
Sebastian Redl972041f2009-04-27 20:27:31 +0000348
349 // Disallow jumps into any part of a C++ try statement. This is pretty
350 // much the same as for Obj-C.
351 if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000352 Scopes.push_back(GotoScope(ParentScope,
353 diag::note_protected_by_cxx_try,
354 diag::note_exits_cxx_try,
Sebastian Redl972041f2009-04-27 20:27:31 +0000355 TS->getSourceRange().getBegin()));
356 if (Stmt *TryBlock = TS->getTryBlock())
357 BuildScopeInformation(TryBlock, Scopes.size()-1);
358
359 // Jump from the catch into the try is not allowed either.
Mike Stump1eb44332009-09-09 15:08:12 +0000360 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000361 CXXCatchStmt *CS = TS->getHandler(I);
362 Scopes.push_back(GotoScope(ParentScope,
363 diag::note_protected_by_cxx_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000364 diag::note_exits_cxx_catch,
Sebastian Redl972041f2009-04-27 20:27:31 +0000365 CS->getSourceRange().getBegin()));
366 BuildScopeInformation(CS->getHandlerBlock(), Scopes.size()-1);
367 }
368
369 continue;
370 }
371
Chris Lattner5af280c2009-04-19 04:46:21 +0000372 // Recursively walk the AST.
373 BuildScopeInformation(SubStmt, ParentScope);
374 }
375}
376
377/// VerifyJumps - Verify each element of the Jumps array to see if they are
378/// valid, emitting diagnostics if not.
379void JumpScopeChecker::VerifyJumps() {
380 while (!Jumps.empty()) {
381 Stmt *Jump = Jumps.pop_back_val();
Mike Stump1eb44332009-09-09 15:08:12 +0000382
383 // With a goto,
Chris Lattner5af280c2009-04-19 04:46:21 +0000384 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000385 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
Chris Lattner5af280c2009-04-19 04:46:21 +0000386 diag::err_goto_into_protected_scope);
387 continue;
388 }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
John McCall95c225d2010-10-28 08:53:48 +0000390 // We only get indirect gotos here when they have a constant target.
391 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000392 LabelDecl *Target = IGS->getConstantTarget();
393 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
John McCall95c225d2010-10-28 08:53:48 +0000394 diag::err_goto_into_protected_scope);
395 continue;
396 }
397
John McCallddb0b4d2010-05-12 00:58:13 +0000398 SwitchStmt *SS = cast<SwitchStmt>(Jump);
399 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
400 SC = SC->getNextSwitchCase()) {
401 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
402 CheckJump(SS, SC, SC->getLocStart(),
403 diag::err_switch_into_protected_scope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000404 }
405 }
406}
407
John McCall5e2a7ac2010-05-12 02:37:54 +0000408/// VerifyIndirectJumps - Verify whether any possible indirect jump
409/// might cross a protection boundary. Unlike direct jumps, indirect
410/// jumps count cleanups as protection boundaries: since there's no
411/// way to know where the jump is going, we can't implicitly run the
412/// right cleanups the way we can with direct jumps.
John McCallddb0b4d2010-05-12 00:58:13 +0000413///
John McCall5e2a7ac2010-05-12 02:37:54 +0000414/// Thus, an indirect jump is "trivial" if it bypasses no
415/// initializations and no teardowns. More formally, an indirect jump
416/// from A to B is trivial if the path out from A to DCA(A,B) is
417/// trivial and the path in from DCA(A,B) to B is trivial, where
418/// DCA(A,B) is the deepest common ancestor of A and B.
419/// Jump-triviality is transitive but asymmetric.
420///
John McCallddb0b4d2010-05-12 00:58:13 +0000421/// A path in is trivial if none of the entered scopes have an InDiag.
422/// A path out is trivial is none of the exited scopes have an OutDiag.
John McCall5e2a7ac2010-05-12 02:37:54 +0000423///
424/// Under these definitions, this function checks that the indirect
425/// jump between A and B is trivial for every indirect goto statement A
426/// and every label B whose address was taken in the function.
John McCallddb0b4d2010-05-12 00:58:13 +0000427void JumpScopeChecker::VerifyIndirectJumps() {
428 if (IndirectJumps.empty()) return;
429
430 // If there aren't any address-of-label expressions in this function,
431 // complain about the first indirect goto.
432 if (IndirectJumpTargets.empty()) {
433 S.Diag(IndirectJumps[0]->getGotoLoc(),
434 diag::err_indirect_goto_without_addrlabel);
435 return;
436 }
437
John McCall5e2a7ac2010-05-12 02:37:54 +0000438 // Collect a single representative of every scope containing an
439 // indirect goto. For most code bases, this substantially cuts
440 // down on the number of jump sites we'll have to consider later.
John McCallddb0b4d2010-05-12 00:58:13 +0000441 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
442 llvm::SmallVector<JumpScope, 32> JumpScopes;
443 {
444 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
445 for (llvm::SmallVectorImpl<IndirectGotoStmt*>::iterator
446 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
447 IndirectGotoStmt *IG = *I;
448 assert(LabelAndGotoScopes.count(IG) &&
449 "indirect jump didn't get added to scopes?");
450 unsigned IGScope = LabelAndGotoScopes[IG];
451 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
452 if (!Entry) Entry = IG;
453 }
454 JumpScopes.reserve(JumpScopesMap.size());
455 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
456 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
457 JumpScopes.push_back(*I);
458 }
459
John McCall5e2a7ac2010-05-12 02:37:54 +0000460 // Collect a single representative of every scope containing a
461 // label whose address was taken somewhere in the function.
462 // For most code bases, there will be only one such scope.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000463 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
464 for (llvm::SmallVectorImpl<LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000465 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
466 I != E; ++I) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000467 LabelDecl *TheLabel = *I;
468 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
John McCallddb0b4d2010-05-12 00:58:13 +0000469 "Referenced label didn't get added to scopes?");
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000470 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
471 LabelDecl *&Target = TargetScopes[LabelScope];
John McCallddb0b4d2010-05-12 00:58:13 +0000472 if (!Target) Target = TheLabel;
473 }
474
John McCall5e2a7ac2010-05-12 02:37:54 +0000475 // For each target scope, make sure it's trivially reachable from
476 // every scope containing a jump site.
477 //
478 // A path between scopes always consists of exitting zero or more
479 // scopes, then entering zero or more scopes. We build a set of
480 // of scopes S from which the target scope can be trivially
481 // entered, then verify that every jump scope can be trivially
482 // exitted to reach a scope in S.
John McCallddb0b4d2010-05-12 00:58:13 +0000483 llvm::BitVector Reachable(Scopes.size(), false);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000484 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000485 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
486 unsigned TargetScope = TI->first;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000487 LabelDecl *TargetLabel = TI->second;
John McCallddb0b4d2010-05-12 00:58:13 +0000488
489 Reachable.reset();
490
491 // Mark all the enclosing scopes from which you can safely jump
John McCall5e2a7ac2010-05-12 02:37:54 +0000492 // into the target scope. 'Min' will end up being the index of
493 // the shallowest such scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000494 unsigned Min = TargetScope;
495 while (true) {
496 Reachable.set(Min);
497
498 // Don't go beyond the outermost scope.
499 if (Min == 0) break;
500
John McCall5e2a7ac2010-05-12 02:37:54 +0000501 // Stop if we can't trivially enter the current scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000502 if (Scopes[Min].InDiag) break;
503
504 Min = Scopes[Min].ParentScope;
505 }
506
507 // Walk through all the jump sites, checking that they can trivially
508 // reach this label scope.
509 for (llvm::SmallVectorImpl<JumpScope>::iterator
510 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
511 unsigned Scope = I->first;
512
513 // Walk out the "scope chain" for this scope, looking for a scope
John McCall5e2a7ac2010-05-12 02:37:54 +0000514 // we've marked reachable. For well-formed code this amortizes
515 // to O(JumpScopes.size() / Scopes.size()): we only iterate
516 // when we see something unmarked, and in well-formed code we
517 // mark everything we iterate past.
John McCallddb0b4d2010-05-12 00:58:13 +0000518 bool IsReachable = false;
519 while (true) {
520 if (Reachable.test(Scope)) {
521 // If we find something reachable, mark all the scopes we just
522 // walked through as reachable.
523 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
524 Reachable.set(S);
525 IsReachable = true;
526 break;
527 }
528
529 // Don't walk out if we've reached the top-level scope or we've
530 // gotten shallower than the shallowest reachable scope.
531 if (Scope == 0 || Scope < Min) break;
532
533 // Don't walk out through an out-diagnostic.
534 if (Scopes[Scope].OutDiag) break;
535
536 Scope = Scopes[Scope].ParentScope;
537 }
538
539 // Only diagnose if we didn't find something.
540 if (IsReachable) continue;
541
542 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
543 }
544 }
545}
546
John McCall5e2a7ac2010-05-12 02:37:54 +0000547/// Diagnose an indirect jump which is known to cross scopes.
John McCallddb0b4d2010-05-12 00:58:13 +0000548void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
549 unsigned JumpScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000550 LabelDecl *Target,
John McCallddb0b4d2010-05-12 00:58:13 +0000551 unsigned TargetScope) {
552 assert(JumpScope != TargetScope);
553
John McCall95c225d2010-10-28 08:53:48 +0000554 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000555 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
John McCallddb0b4d2010-05-12 00:58:13 +0000556
John McCall5e2a7ac2010-05-12 02:37:54 +0000557 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
John McCallddb0b4d2010-05-12 00:58:13 +0000558
John McCall5e2a7ac2010-05-12 02:37:54 +0000559 // Walk out the scope chain until we reach the common ancestor.
560 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
561 if (Scopes[I].OutDiag)
562 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000563
564 // Now walk into the scopes containing the label whose address was taken.
John McCall5e2a7ac2010-05-12 02:37:54 +0000565 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
566 if (Scopes[I].InDiag)
567 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000568}
569
Chris Lattner5af280c2009-04-19 04:46:21 +0000570/// CheckJump - Validate that the specified jump statement is valid: that it is
571/// jumping within or out of its current scope, not into a deeper one.
572void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
573 SourceLocation DiagLoc, unsigned JumpDiag) {
574 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
575 unsigned FromScope = LabelAndGotoScopes[From];
576
577 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
578 unsigned ToScope = LabelAndGotoScopes[To];
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattner5af280c2009-04-19 04:46:21 +0000580 // Common case: exactly the same scope, which is fine.
581 if (FromScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
John McCall5e2a7ac2010-05-12 02:37:54 +0000583 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000584
John McCall5e2a7ac2010-05-12 02:37:54 +0000585 // It's okay to jump out from a nested scope.
586 if (CommonScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000587
John McCall5e2a7ac2010-05-12 02:37:54 +0000588 // Pull out (and reverse) any scopes we might need to diagnose skipping.
589 llvm::SmallVector<unsigned, 10> ToScopes;
590 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope)
591 if (Scopes[I].InDiag)
592 ToScopes.push_back(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000593
John McCall5e2a7ac2010-05-12 02:37:54 +0000594 // If the only scopes present are cleanup scopes, we're okay.
John McCallddb0b4d2010-05-12 00:58:13 +0000595 if (ToScopes.empty()) return;
596
597 S.Diag(DiagLoc, JumpDiag);
598
Chris Lattner5af280c2009-04-19 04:46:21 +0000599 // Emit diagnostics for whatever is left in ToScopes.
600 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
John McCallddb0b4d2010-05-12 00:58:13 +0000601 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].InDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000602}
603
604void Sema::DiagnoseInvalidJumps(Stmt *Body) {
Douglas Gregor6490ae52009-11-17 06:14:37 +0000605 (void)JumpScopeChecker(Body, *this);
Chris Lattner5af280c2009-04-19 04:46:21 +0000606}