blob: 82db0bbd2c3c89ae0888c1a44973bbd57ddba17c [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
15#include "Sema.h"
16#include "clang/AST/Expr.h"
17using namespace clang;
18
19namespace {
20
21/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
22/// into VLA and other protected scopes. For example, this rejects:
23/// goto L;
24/// int a[n];
25/// L:
26///
27class JumpScopeChecker {
28 Sema &S;
29
30 /// GotoScope - This is a record that we use to keep track of all of the
31 /// scopes that are introduced by VLAs and other things that scope jumps like
32 /// gotos. This scope tree has nothing to do with the source scope tree,
33 /// because you can have multiple VLA scopes per compound statement, and most
34 /// compound statements don't introduce any scopes.
35 struct GotoScope {
36 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
37 /// the parent scope is the function body.
38 unsigned ParentScope;
39
40 /// Diag - The diagnostic to emit if there is a jump into this scope.
41 unsigned Diag;
42
43 /// Loc - Location to emit the diagnostic.
44 SourceLocation Loc;
45
46 GotoScope(unsigned parentScope, unsigned diag, SourceLocation L)
47 : ParentScope(parentScope), Diag(diag), Loc(L) {}
48 };
49
50 llvm::SmallVector<GotoScope, 48> Scopes;
51 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
52 llvm::SmallVector<Stmt*, 16> Jumps;
53public:
54 JumpScopeChecker(Stmt *Body, Sema &S);
55private:
56 void BuildScopeInformation(Stmt *S, unsigned ParentScope);
57 void VerifyJumps();
58 void CheckJump(Stmt *From, Stmt *To,
59 SourceLocation DiagLoc, unsigned JumpDiag);
60};
61} // end anonymous namespace
62
63
64JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
65 // Add a scope entry for function scope.
66 Scopes.push_back(GotoScope(~0U, ~0U, SourceLocation()));
67
68 // Build information for the top level compound statement, so that we have a
69 // defined scope record for every "goto" and label.
70 BuildScopeInformation(Body, 0);
71
72 // Check that all jumps we saw are kosher.
73 VerifyJumps();
74}
75
76/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
77/// diagnostic that should be emitted if control goes over it. If not, return 0.
78static unsigned GetDiagForGotoScopeDecl(const Decl *D) {
79 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
80 if (VD->getType()->isVariablyModifiedType())
81 return diag::note_protected_by_vla;
82 if (VD->hasAttr<CleanupAttr>())
83 return diag::note_protected_by_cleanup;
84 } else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
85 if (TD->getUnderlyingType()->isVariablyModifiedType())
86 return diag::note_protected_by_vla_typedef;
87 }
88
89 return 0;
90}
91
92
93/// BuildScopeInformation - The statements from CI to CE are known to form a
94/// coherent VLA scope with a specified parent node. Walk through the
95/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
96/// walking the AST as needed.
97void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
98
99 // If we found a label, remember that it is in ParentScope scope.
100 if (isa<LabelStmt>(S) || isa<DefaultStmt>(S) || isa<CaseStmt>(S)) {
101 LabelAndGotoScopes[S] = ParentScope;
102 } else if (isa<GotoStmt>(S) || isa<SwitchStmt>(S) ||
103 isa<IndirectGotoStmt>(S) || isa<AddrLabelExpr>(S)) {
104 // Remember both what scope a goto is in as well as the fact that we have
105 // it. This makes the second scan not have to walk the AST again.
106 LabelAndGotoScopes[S] = ParentScope;
107 Jumps.push_back(S);
108 }
109
110 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
111 ++CI) {
112 Stmt *SubStmt = *CI;
113 if (SubStmt == 0) continue;
114
115 // FIXME: diagnose jumps past initialization: required in C++, warning in C.
116 // goto L; int X = 4; L: ;
117 // FIXME: what about jumps into C++ catch blocks, what are the rules?
118
119 // If this is a declstmt with a VLA definition, it defines a scope from here
120 // to the end of the containing context.
121 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
122 // The decl statement creates a scope if any of the decls in it are VLAs or
123 // have the cleanup attribute.
124 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
125 I != E; ++I) {
126 // If this decl causes a new scope, push and switch to it.
127 if (unsigned Diag = GetDiagForGotoScopeDecl(*I)) {
128 Scopes.push_back(GotoScope(ParentScope, Diag, (*I)->getLocation()));
129 ParentScope = Scopes.size()-1;
130 }
131
132 // If the decl has an initializer, walk it with the potentially new
133 // scope we just installed.
134 if (VarDecl *VD = dyn_cast<VarDecl>(*I))
135 if (Expr *Init = VD->getInit())
136 BuildScopeInformation(Init, ParentScope);
137 }
138 continue;
139 }
140
141 // Disallow jumps into any part of an @try statement by pushing a scope and
142 // walking all sub-stmts in that scope.
143 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
144 // Recursively walk the AST for the @try part.
145 Scopes.push_back(GotoScope(ParentScope,diag::note_protected_by_objc_try,
146 AT->getAtTryLoc()));
147 if (Stmt *TryPart = AT->getTryBody())
148 BuildScopeInformation(TryPart, Scopes.size()-1);
149
150 // Jump from the catch to the finally or try is not valid.
151 for (ObjCAtCatchStmt *AC = AT->getCatchStmts(); AC;
152 AC = AC->getNextCatchStmt()) {
153 Scopes.push_back(GotoScope(ParentScope,
154 diag::note_protected_by_objc_catch,
155 AC->getAtCatchLoc()));
156 // @catches are nested and it isn't
157 BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
158 }
159
160 // Jump from the finally to the try or catch is not valid.
161 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
162 Scopes.push_back(GotoScope(ParentScope,
163 diag::note_protected_by_objc_finally,
164 AF->getAtFinallyLoc()));
165 BuildScopeInformation(AF, Scopes.size()-1);
166 }
167
168 continue;
169 }
170
171 // Recursively walk the AST.
172 BuildScopeInformation(SubStmt, ParentScope);
173 }
174}
175
176/// VerifyJumps - Verify each element of the Jumps array to see if they are
177/// valid, emitting diagnostics if not.
178void JumpScopeChecker::VerifyJumps() {
179 while (!Jumps.empty()) {
180 Stmt *Jump = Jumps.pop_back_val();
181
182 // With a goto,
183 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
184 CheckJump(GS, GS->getLabel(), GS->getGotoLoc(),
185 diag::err_goto_into_protected_scope);
186 continue;
187 }
188
189 if (SwitchStmt *SS = dyn_cast<SwitchStmt>(Jump)) {
190 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
191 SC = SC->getNextSwitchCase()) {
192 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
193 CheckJump(SS, SC, SC->getLocStart(),
194 diag::err_switch_into_protected_scope);
195 }
196 continue;
197 }
198
199 unsigned DiagnosticScope;
200
201 // We don't know where an indirect goto goes, require that it be at the
202 // top level of scoping.
203 if (IndirectGotoStmt *IG = dyn_cast<IndirectGotoStmt>(Jump)) {
204 assert(LabelAndGotoScopes.count(Jump) &&
205 "Jump didn't get added to scopes?");
206 unsigned GotoScope = LabelAndGotoScopes[IG];
207 if (GotoScope == 0) continue; // indirect jump is ok.
208 S.Diag(IG->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
209 DiagnosticScope = GotoScope;
210 } else {
211 // We model &&Label as a jump for purposes of scope tracking. We actually
212 // don't care *where* the address of label is, but we require the *label
213 // itself* to be in scope 0. If it is nested inside of a VLA scope, then
214 // it is possible for an indirect goto to illegally enter the VLA scope by
215 // indirectly jumping to the label.
216 assert(isa<AddrLabelExpr>(Jump) && "Unknown jump type");
217 LabelStmt *TheLabel = cast<AddrLabelExpr>(Jump)->getLabel();
218
219 assert(LabelAndGotoScopes.count(TheLabel) &&
220 "Referenced label didn't get added to scopes?");
221 unsigned LabelScope = LabelAndGotoScopes[TheLabel];
222 if (LabelScope == 0) continue; // Addr of label is ok.
223
224 S.Diag(Jump->getLocStart(), diag::err_addr_of_label_in_protected_scope);
225 DiagnosticScope = LabelScope;
226 }
227
228 // Report all the things that would be skipped over by this &&label or
229 // indirect goto.
230 while (DiagnosticScope != 0) {
231 S.Diag(Scopes[DiagnosticScope].Loc, Scopes[DiagnosticScope].Diag);
232 DiagnosticScope = Scopes[DiagnosticScope].ParentScope;
233 }
234 }
235}
236
237/// CheckJump - Validate that the specified jump statement is valid: that it is
238/// jumping within or out of its current scope, not into a deeper one.
239void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
240 SourceLocation DiagLoc, unsigned JumpDiag) {
241 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
242 unsigned FromScope = LabelAndGotoScopes[From];
243
244 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
245 unsigned ToScope = LabelAndGotoScopes[To];
246
247 // Common case: exactly the same scope, which is fine.
248 if (FromScope == ToScope) return;
249
250 // The only valid mismatch jump case happens when the jump is more deeply
251 // nested inside the jump target. Do a quick scan to see if the jump is valid
252 // because valid code is more common than invalid code.
253 unsigned TestScope = Scopes[FromScope].ParentScope;
254 while (TestScope != ~0U) {
255 // If we found the jump target, then we're jumping out of our current scope,
256 // which is perfectly fine.
257 if (TestScope == ToScope) return;
258
259 // Otherwise, scan up the hierarchy.
260 TestScope = Scopes[TestScope].ParentScope;
261 }
262
263 // If we get here, then we know we have invalid code. Diagnose the bad jump,
264 // and then emit a note at each VLA being jumped out of.
265 S.Diag(DiagLoc, JumpDiag);
266
267 // Eliminate the common prefix of the jump and the target. Start by
268 // linearizing both scopes, reversing them as we go.
269 std::vector<unsigned> FromScopes, ToScopes;
270 for (TestScope = FromScope; TestScope != ~0U;
271 TestScope = Scopes[TestScope].ParentScope)
272 FromScopes.push_back(TestScope);
273 for (TestScope = ToScope; TestScope != ~0U;
274 TestScope = Scopes[TestScope].ParentScope)
275 ToScopes.push_back(TestScope);
276
277 // Remove any common entries (such as the top-level function scope).
278 while (!FromScopes.empty() && FromScopes.back() == ToScopes.back()) {
279 FromScopes.pop_back();
280 ToScopes.pop_back();
281 }
282
283 // Emit diagnostics for whatever is left in ToScopes.
284 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
285 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].Diag);
286}
287
288void Sema::DiagnoseInvalidJumps(Stmt *Body) {
289 JumpScopeChecker(Body, *this);
290}