1//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the JumpScopeChecker class, which is used to diagnose
10// jumps that enter a protected scope in an invalid way.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/AST/StmtObjC.h"
19#include "clang/AST/StmtOpenACC.h"
20#include "clang/AST/StmtOpenMP.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Sema/SemaAMDGPU.h"
23#include "clang/Sema/SemaInternal.h"
24#include "llvm/ADT/BitVector.h"
25using namespace clang;
26
27namespace {
28
29/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
30/// into VLA and other protected scopes. For example, this rejects:
31/// goto L;
32/// int a[n];
33/// L:
34///
35/// We also detect jumps out of protected scopes when it's not possible to do
36/// cleanups properly. Indirect jumps and ASM jumps can't do cleanups because
37/// the target is unknown. Return statements with \c [[clang::musttail]] cannot
38/// handle any cleanups due to the nature of a tail call.
39class JumpScopeChecker {
40 Sema &S;
41
42 /// Permissive - True when recovering from errors, in which case precautions
43 /// are taken to handle incomplete scope information.
44 const bool Permissive;
45
46 /// GotoScope - This is a record that we use to keep track of all of the
47 /// scopes that are introduced by VLAs and other things that scope jumps like
48 /// gotos. This scope tree has nothing to do with the source scope tree,
49 /// because you can have multiple VLA scopes per compound statement, and most
50 /// compound statements don't introduce any scopes.
51 struct GotoScope {
52 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
53 /// the parent scope is the function body.
54 unsigned ParentScope;
55
56 /// InDiag - The note to emit if there is a jump into this scope.
57 unsigned InDiag;
58
59 /// OutDiag - The note to emit if there is an indirect jump out
60 /// of this scope. Direct jumps always clean up their current scope
61 /// in an orderly way.
62 unsigned OutDiag;
63
64 /// Loc - Location to emit the diagnostic.
65 SourceLocation Loc;
66
67 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
68 SourceLocation L)
69 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
70 };
71
72 SmallVector<GotoScope, 48> Scopes;
73 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
74 SmallVector<Stmt*, 16> Jumps;
75
76 SmallVector<Stmt*, 4> IndirectJumps;
77 SmallVector<LabelDecl *, 4> IndirectJumpTargets;
78 SmallVector<AttributedStmt *, 4> MustTailStmts;
79
80public:
81 JumpScopeChecker(Stmt *Body, Sema &S);
82private:
83 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
84 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
85 unsigned &ParentScope);
86 void BuildScopeInformation(CompoundLiteralExpr *CLE, unsigned &ParentScope);
87 void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
88
89 void VerifyJumps();
90 void VerifyIndirectJumps();
91 void VerifyMustTailStmts();
92 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
93 void DiagnoseIndirectOrAsmJump(Stmt *IG, unsigned IGScope, LabelDecl *Target,
94 unsigned TargetScope);
95 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
96 unsigned JumpDiag, unsigned JumpDiagWarning,
97 unsigned JumpDiagCompat);
98 void CheckGotoStmt(GotoStmt *GS);
99 const Attr *GetMustTailAttr(AttributedStmt *AS);
100
101 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
102};
103} // end anonymous namespace
104
105#define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
106
107JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
108 : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
109 // Add a scope entry for function scope.
110 Scopes.push_back(Elt: GotoScope(~0U, ~0U, ~0U, SourceLocation()));
111
112 // Build information for the top level compound statement, so that we have a
113 // defined scope record for every "goto" and label.
114 unsigned BodyParentScope = 0;
115 BuildScopeInformation(S: Body, origParentScope&: BodyParentScope);
116
117 // Check that all jumps we saw are kosher.
118 VerifyJumps();
119 VerifyIndirectJumps();
120 VerifyMustTailStmts();
121}
122
123/// GetDeepestCommonScope - Finds the innermost scope enclosing the
124/// two scopes.
125unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
126 while (A != B) {
127 // Inner scopes are created after outer scopes and therefore have
128 // higher indices.
129 if (A < B) {
130 assert(Scopes[B].ParentScope < B);
131 B = Scopes[B].ParentScope;
132 } else {
133 assert(Scopes[A].ParentScope < A);
134 A = Scopes[A].ParentScope;
135 }
136 }
137 return A;
138}
139
140typedef std::pair<unsigned,unsigned> ScopePair;
141
142/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
143/// diagnostic that should be emitted if control goes over it. If not, return 0.
144static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
145 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
146 unsigned InDiag = 0;
147 unsigned OutDiag = 0;
148
149 if (VD->getType()->isVariablyModifiedType())
150 InDiag = diag::note_protected_by_vla;
151
152 if (VD->hasAttr<BlocksAttr>())
153 return ScopePair(diag::note_protected_by___block,
154 diag::note_exits___block);
155
156 if (VD->hasAttr<CleanupAttr>())
157 return ScopePair(diag::note_protected_by_cleanup,
158 diag::note_exits_cleanup);
159
160 // Allocated at the declaration and freed at scope exit, like cleanup.
161 if (VD->hasLocalStorage() && VD->hasAttr<OMPAllocateDeclAttr>())
162 return ScopePair(diag::note_protected_by_omp_allocate,
163 diag::note_exits_omp_allocate);
164
165 if (VD->hasLocalStorage()) {
166 switch (VD->getType().isDestructedType()) {
167 case QualType::DK_objc_strong_lifetime:
168 return ScopePair(diag::note_protected_by_objc_strong_init,
169 diag::note_exits_objc_strong);
170
171 case QualType::DK_objc_weak_lifetime:
172 return ScopePair(diag::note_protected_by_objc_weak_init,
173 diag::note_exits_objc_weak);
174
175 case QualType::DK_nontrivial_c_struct:
176 return ScopePair(diag::note_protected_by_non_trivial_c_struct_init,
177 diag::note_exits_dtor);
178
179 case QualType::DK_cxx_destructor:
180 OutDiag = diag::note_exits_dtor;
181 break;
182
183 case QualType::DK_none:
184 break;
185 }
186 }
187
188 // An earlier diag::note_protected_by_vla is more severe, so don't overwrite
189 // it here.
190 if (const Expr *Init = VD->getInit();
191 !InDiag && VD->hasLocalStorage() && Init && !Init->containsErrors()) {
192 // C++11 [stmt.dcl]p3:
193 // A program that jumps from a point where a variable with automatic
194 // storage duration is not in scope to a point where it is in scope
195 // is ill-formed unless the variable has scalar type, class type with
196 // a trivial default constructor and a trivial destructor, a
197 // cv-qualified version of one of these types, or an array of one of
198 // the preceding types and is declared without an initializer.
199
200 // C++03 [stmt.dcl.p3:
201 // A program that jumps from a point where a local variable
202 // with automatic storage duration is not in scope to a point
203 // where it is in scope is ill-formed unless the variable has
204 // POD type and is declared without an initializer.
205
206 InDiag = diag::note_protected_by_variable_init;
207
208 // For a variable of (array of) class type declared without an
209 // initializer, we will have call-style initialization and the initializer
210 // will be the CXXConstructExpr with no intervening nodes.
211 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) {
212 const CXXConstructorDecl *Ctor = CCE->getConstructor();
213 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
214 VD->getInitStyle() == VarDecl::CallInit) {
215 if (OutDiag)
216 InDiag = diag::note_protected_by_variable_nontriv_destructor;
217 else if (!Ctor->getParent()->isPOD())
218 InDiag = diag::note_protected_by_variable_non_pod;
219 else
220 InDiag = 0;
221 }
222 }
223 }
224
225 return ScopePair(InDiag, OutDiag);
226 }
227
228 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
229 if (TD->getUnderlyingType()->isVariablyModifiedType())
230 return ScopePair(isa<TypedefDecl>(Val: TD)
231 ? diag::note_protected_by_vla_typedef
232 : diag::note_protected_by_vla_type_alias,
233 0);
234 }
235
236 return ScopePair(0U, 0U);
237}
238
239/// Build scope information for a declaration that is part of a DeclStmt.
240void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
241 // If this decl causes a new scope, push and switch to it.
242 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
243 if (Diags.first || Diags.second) {
244 Scopes.push_back(Elt: GotoScope(ParentScope, Diags.first, Diags.second,
245 D->getLocation()));
246 ParentScope = Scopes.size()-1;
247 }
248
249 // If the decl has an initializer, walk it with the potentially new
250 // scope we just installed.
251 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
252 if (Expr *Init = VD->getInit())
253 BuildScopeInformation(S: Init, origParentScope&: ParentScope);
254}
255
256/// Build scope information for a captured block literal variables.
257void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
258 const BlockDecl *BDecl,
259 unsigned &ParentScope) {
260 // exclude captured __block variables; there's no destructor
261 // associated with the block literal for them.
262 if (D->hasAttr<BlocksAttr>())
263 return;
264 QualType T = D->getType();
265 QualType::DestructionKind destructKind = T.isDestructedType();
266 if (destructKind != QualType::DK_none) {
267 std::pair<unsigned,unsigned> Diags;
268 switch (destructKind) {
269 case QualType::DK_cxx_destructor:
270 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
271 diag::note_exits_block_captures_cxx_obj);
272 break;
273 case QualType::DK_objc_strong_lifetime:
274 Diags = ScopePair(diag::note_enters_block_captures_strong,
275 diag::note_exits_block_captures_strong);
276 break;
277 case QualType::DK_objc_weak_lifetime:
278 Diags = ScopePair(diag::note_enters_block_captures_weak,
279 diag::note_exits_block_captures_weak);
280 break;
281 case QualType::DK_nontrivial_c_struct:
282 Diags = ScopePair(diag::note_enters_block_captures_non_trivial_c_struct,
283 diag::note_exits_block_captures_non_trivial_c_struct);
284 break;
285 case QualType::DK_none:
286 llvm_unreachable("non-lifetime captured variable");
287 }
288 SourceLocation Loc = D->getLocation();
289 if (Loc.isInvalid())
290 Loc = BDecl->getLocation();
291 Scopes.push_back(Elt: GotoScope(ParentScope,
292 Diags.first, Diags.second, Loc));
293 ParentScope = Scopes.size()-1;
294 }
295}
296
297/// Build scope information for compound literals of C struct types that are
298/// non-trivial to destruct.
299void JumpScopeChecker::BuildScopeInformation(CompoundLiteralExpr *CLE,
300 unsigned &ParentScope) {
301 if (!CLE->getType().isDestructedType())
302 return;
303 unsigned InDiag = diag::note_enters_compound_literal_scope;
304 unsigned OutDiag = diag::note_exits_compound_literal_scope;
305 Scopes.push_back(Elt: GotoScope(ParentScope, InDiag, OutDiag, CLE->getExprLoc()));
306 ParentScope = Scopes.size() - 1;
307}
308
309/// BuildScopeInformation - The statements from CI to CE are known to form a
310/// coherent VLA scope with a specified parent node. Walk through the
311/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
312/// walking the AST as needed.
313void JumpScopeChecker::BuildScopeInformation(Stmt *S,
314 unsigned &origParentScope) {
315 // If this is a statement, rather than an expression, scopes within it don't
316 // propagate out into the enclosing scope. Otherwise we have to worry
317 // about block literals, which have the lifetime of their enclosing statement.
318 unsigned independentParentScope = origParentScope;
319 unsigned &ParentScope = ((isa<Expr>(Val: S) && !isa<StmtExpr>(Val: S))
320 ? origParentScope : independentParentScope);
321
322 unsigned StmtsToSkip = 0u;
323
324 // If we found a label, remember that it is in ParentScope scope.
325 switch (S->getStmtClass()) {
326 case Stmt::AddrLabelExprClass:
327 IndirectJumpTargets.push_back(Elt: cast<AddrLabelExpr>(Val: S)->getLabel());
328 break;
329
330 case Stmt::ObjCForCollectionStmtClass: {
331 auto *CS = cast<ObjCForCollectionStmt>(Val: S);
332 unsigned Diag = diag::note_protected_by_objc_fast_enumeration;
333 unsigned NewParentScope = Scopes.size();
334 Scopes.push_back(Elt: GotoScope(ParentScope, Diag, 0, S->getBeginLoc()));
335 BuildScopeInformation(S: CS->getBody(), origParentScope&: NewParentScope);
336 return;
337 }
338
339 case Stmt::IndirectGotoStmtClass:
340 // "goto *&&lbl;" is a special case which we treat as equivalent
341 // to a normal goto. In addition, we don't calculate scope in the
342 // operand (to avoid recording the address-of-label use), which
343 // works only because of the restricted set of expressions which
344 // we detect as constant targets.
345 if (cast<IndirectGotoStmt>(Val: S)->getConstantTarget())
346 goto RecordJumpScope;
347
348 LabelAndGotoScopes[S] = ParentScope;
349 IndirectJumps.push_back(Elt: S);
350 break;
351
352 case Stmt::SwitchStmtClass:
353 // Evaluate the C++17 init stmt and condition variable
354 // before entering the scope of the switch statement.
355 if (Stmt *Init = cast<SwitchStmt>(Val: S)->getInit()) {
356 BuildScopeInformation(S: Init, origParentScope&: ParentScope);
357 ++StmtsToSkip;
358 }
359 if (VarDecl *Var = cast<SwitchStmt>(Val: S)->getConditionVariable()) {
360 BuildScopeInformation(D: Var, ParentScope);
361 ++StmtsToSkip;
362 }
363 goto RecordJumpScope;
364
365 case Stmt::GCCAsmStmtClass:
366 if (!cast<GCCAsmStmt>(Val: S)->isAsmGoto())
367 break;
368 [[fallthrough]];
369
370 case Stmt::GotoStmtClass:
371 RecordJumpScope:
372 // Remember both what scope a goto is in as well as the fact that we have
373 // it. This makes the second scan not have to walk the AST again.
374 LabelAndGotoScopes[S] = ParentScope;
375 Jumps.push_back(Elt: S);
376 break;
377
378 case Stmt::IfStmtClass: {
379 IfStmt *IS = cast<IfStmt>(Val: S);
380 bool AMDGPUPredicate = false;
381 if (!(IS->isConstexpr() || IS->isConsteval() ||
382 IS->isObjCAvailabilityCheck() ||
383 (AMDGPUPredicate = this->S.AMDGPU().IsPredicate(E: IS->getCond()))))
384 break;
385
386 unsigned Diag = diag::note_protected_by_if_available;
387 if (IS->isConstexpr())
388 Diag = diag::note_protected_by_constexpr_if;
389 else if (IS->isConsteval())
390 Diag = diag::note_protected_by_consteval_if;
391 else if (AMDGPUPredicate)
392 Diag = diag::note_amdgcn_protected_by_predicate;
393
394 if (VarDecl *Var = IS->getConditionVariable())
395 BuildScopeInformation(D: Var, ParentScope);
396
397 // Cannot jump into the middle of the condition.
398 unsigned NewParentScope = Scopes.size();
399 Scopes.push_back(Elt: GotoScope(ParentScope, Diag, 0, IS->getBeginLoc()));
400
401 if (!IS->isConsteval())
402 BuildScopeInformation(S: IS->getCond(), origParentScope&: NewParentScope);
403
404 // Jumps into either arm of an 'if constexpr' are not allowed.
405 NewParentScope = Scopes.size();
406 Scopes.push_back(Elt: GotoScope(ParentScope, Diag, 0, IS->getBeginLoc()));
407 BuildScopeInformation(S: IS->getThen(), origParentScope&: NewParentScope);
408 if (Stmt *Else = IS->getElse()) {
409 NewParentScope = Scopes.size();
410 Scopes.push_back(Elt: GotoScope(ParentScope, Diag, 0, IS->getBeginLoc()));
411 BuildScopeInformation(S: Else, origParentScope&: NewParentScope);
412 }
413 return;
414 }
415
416 case Stmt::CXXTryStmtClass: {
417 CXXTryStmt *TS = cast<CXXTryStmt>(Val: S);
418 {
419 unsigned NewParentScope = Scopes.size();
420 Scopes.push_back(Elt: GotoScope(ParentScope,
421 diag::note_protected_by_cxx_try,
422 diag::note_exits_cxx_try,
423 TS->getSourceRange().getBegin()));
424 if (Stmt *TryBlock = TS->getTryBlock())
425 BuildScopeInformation(S: TryBlock, origParentScope&: NewParentScope);
426 }
427
428 // Jump from the catch into the try is not allowed either.
429 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
430 CXXCatchStmt *CS = TS->getHandler(i: I);
431 unsigned NewParentScope = Scopes.size();
432 Scopes.push_back(Elt: GotoScope(ParentScope,
433 diag::note_protected_by_cxx_catch,
434 diag::note_exits_cxx_catch,
435 CS->getSourceRange().getBegin()));
436 BuildScopeInformation(S: CS->getHandlerBlock(), origParentScope&: NewParentScope);
437 }
438 return;
439 }
440
441 case Stmt::SEHTryStmtClass: {
442 SEHTryStmt *TS = cast<SEHTryStmt>(Val: S);
443 {
444 unsigned NewParentScope = Scopes.size();
445 Scopes.push_back(Elt: GotoScope(ParentScope,
446 diag::note_protected_by_seh_try,
447 diag::note_exits_seh_try,
448 TS->getSourceRange().getBegin()));
449 if (Stmt *TryBlock = TS->getTryBlock())
450 BuildScopeInformation(S: TryBlock, origParentScope&: NewParentScope);
451 }
452
453 // Jump from __except or __finally into the __try are not allowed either.
454 if (SEHExceptStmt *Except = TS->getExceptHandler()) {
455 unsigned NewParentScope = Scopes.size();
456 Scopes.push_back(Elt: GotoScope(ParentScope,
457 diag::note_protected_by_seh_except,
458 diag::note_exits_seh_except,
459 Except->getSourceRange().getBegin()));
460 BuildScopeInformation(S: Except->getBlock(), origParentScope&: NewParentScope);
461 } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
462 unsigned NewParentScope = Scopes.size();
463 Scopes.push_back(Elt: GotoScope(ParentScope,
464 diag::note_protected_by_seh_finally,
465 diag::note_exits_seh_finally,
466 Finally->getSourceRange().getBegin()));
467 BuildScopeInformation(S: Finally->getBlock(), origParentScope&: NewParentScope);
468 }
469
470 return;
471 }
472
473 case Stmt::DeclStmtClass: {
474 // If this is a declstmt with a VLA definition, it defines a scope from here
475 // to the end of the containing context.
476 DeclStmt *DS = cast<DeclStmt>(Val: S);
477 // The decl statement creates a scope if any of the decls in it are VLAs
478 // or have the cleanup attribute.
479 for (auto *I : DS->decls())
480 BuildScopeInformation(D: I, ParentScope&: origParentScope);
481 return;
482 }
483
484 case Stmt::StmtExprClass: {
485 // [GNU]
486 // Jumping into a statement expression with goto or using
487 // a switch statement outside the statement expression with
488 // a case or default label inside the statement expression is not permitted.
489 // Jumping out of a statement expression is permitted.
490 StmtExpr *SE = cast<StmtExpr>(Val: S);
491 unsigned NewParentScope = Scopes.size();
492 Scopes.push_back(Elt: GotoScope(ParentScope,
493 diag::note_enters_statement_expression,
494 /*OutDiag=*/0, SE->getBeginLoc()));
495 BuildScopeInformation(S: SE->getSubStmt(), origParentScope&: NewParentScope);
496 return;
497 }
498
499 case Stmt::ObjCAtTryStmtClass: {
500 // Disallow jumps into any part of an @try statement by pushing a scope and
501 // walking all sub-stmts in that scope.
502 ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(Val: S);
503 // Recursively walk the AST for the @try part.
504 {
505 unsigned NewParentScope = Scopes.size();
506 Scopes.push_back(Elt: GotoScope(ParentScope,
507 diag::note_protected_by_objc_try,
508 diag::note_exits_objc_try,
509 AT->getAtTryLoc()));
510 if (Stmt *TryPart = AT->getTryBody())
511 BuildScopeInformation(S: TryPart, origParentScope&: NewParentScope);
512 }
513
514 // Jump from the catch to the finally or try is not valid.
515 for (ObjCAtCatchStmt *AC : AT->catch_stmts()) {
516 unsigned NewParentScope = Scopes.size();
517 Scopes.push_back(Elt: GotoScope(ParentScope,
518 diag::note_protected_by_objc_catch,
519 diag::note_exits_objc_catch,
520 AC->getAtCatchLoc()));
521 // @catches are nested and it isn't
522 BuildScopeInformation(S: AC->getCatchBody(), origParentScope&: NewParentScope);
523 }
524
525 // Jump from the finally to the try or catch is not valid.
526 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
527 unsigned NewParentScope = Scopes.size();
528 Scopes.push_back(Elt: GotoScope(ParentScope,
529 diag::note_protected_by_objc_finally,
530 diag::note_exits_objc_finally,
531 AF->getAtFinallyLoc()));
532 BuildScopeInformation(S: AF, origParentScope&: NewParentScope);
533 }
534
535 return;
536 }
537
538 case Stmt::ObjCAtSynchronizedStmtClass: {
539 // Disallow jumps into the protected statement of an @synchronized, but
540 // allow jumps into the object expression it protects.
541 ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(Val: S);
542 // Recursively walk the AST for the @synchronized object expr, it is
543 // evaluated in the normal scope.
544 BuildScopeInformation(S: AS->getSynchExpr(), origParentScope&: ParentScope);
545
546 // Recursively walk the AST for the @synchronized part, protected by a new
547 // scope.
548 unsigned NewParentScope = Scopes.size();
549 Scopes.push_back(Elt: GotoScope(ParentScope,
550 diag::note_protected_by_objc_synchronized,
551 diag::note_exits_objc_synchronized,
552 AS->getAtSynchronizedLoc()));
553 BuildScopeInformation(S: AS->getSynchBody(), origParentScope&: NewParentScope);
554 return;
555 }
556
557 case Stmt::ObjCAutoreleasePoolStmtClass: {
558 // Disallow jumps into the protected statement of an @autoreleasepool.
559 ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(Val: S);
560 // Recursively walk the AST for the @autoreleasepool part, protected by a
561 // new scope.
562 unsigned NewParentScope = Scopes.size();
563 Scopes.push_back(Elt: GotoScope(ParentScope,
564 diag::note_protected_by_objc_autoreleasepool,
565 diag::note_exits_objc_autoreleasepool,
566 AS->getAtLoc()));
567 BuildScopeInformation(S: AS->getSubStmt(), origParentScope&: NewParentScope);
568 return;
569 }
570
571 case Stmt::ExprWithCleanupsClass: {
572 // Disallow jumps past full-expressions that use blocks with
573 // non-trivial cleanups of their captures. This is theoretically
574 // implementable but a lot of work which we haven't felt up to doing.
575 ExprWithCleanups *EWC = cast<ExprWithCleanups>(Val: S);
576 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
577 if (auto *BDecl = dyn_cast<BlockDecl *>(Val: EWC->getObject(i)))
578 for (const auto &CI : BDecl->captures()) {
579 VarDecl *variable = CI.getVariable();
580 BuildScopeInformation(D: variable, BDecl, ParentScope&: origParentScope);
581 }
582 else if (auto *CLE = dyn_cast<CompoundLiteralExpr *>(Val: EWC->getObject(i)))
583 BuildScopeInformation(CLE, ParentScope&: origParentScope);
584 else
585 llvm_unreachable("unexpected cleanup object type");
586 }
587 break;
588 }
589
590 case Stmt::MaterializeTemporaryExprClass: {
591 // Disallow jumps out of scopes containing temporaries lifetime-extended to
592 // automatic storage duration.
593 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(Val: S);
594 if (MTE->getStorageDuration() == SD_Automatic) {
595 const Expr *ExtendedObject =
596 MTE->getSubExpr()->skipRValueSubobjectAdjustments();
597 if (ExtendedObject->getType().isDestructedType()) {
598 Scopes.push_back(Elt: GotoScope(ParentScope, 0,
599 diag::note_exits_temporary_dtor,
600 ExtendedObject->getExprLoc()));
601 origParentScope = Scopes.size()-1;
602 }
603 }
604 break;
605 }
606
607 case Stmt::DeferStmtClass: {
608 auto *D = cast<DeferStmt>(Val: S);
609
610 {
611 // Disallow jumps over defer statements.
612 unsigned NewParentScope = Scopes.size();
613 Scopes.emplace_back(Args&: ParentScope, Args: diag::note_protected_by_defer_stmt, Args: 0,
614 Args: D->getDeferLoc());
615 origParentScope = NewParentScope;
616 }
617
618 // Disallow jumps into or out of defer statements.
619 {
620 unsigned NewParentScope = Scopes.size();
621 Scopes.emplace_back(Args&: ParentScope, Args: diag::note_enters_defer_stmt,
622 Args: diag::note_exits_defer_stmt, Args: D->getDeferLoc());
623 BuildScopeInformation(S: D->getBody(), origParentScope&: NewParentScope);
624 }
625 return;
626 }
627
628 case Stmt::CaseStmtClass:
629 case Stmt::DefaultStmtClass:
630 case Stmt::LabelStmtClass:
631 LabelAndGotoScopes[S] = ParentScope;
632 break;
633
634 case Stmt::OpenACCComputeConstructClass: {
635 unsigned NewParentScope = Scopes.size();
636 OpenACCComputeConstruct *CC = cast<OpenACCComputeConstruct>(Val: S);
637 Scopes.push_back(Elt: GotoScope(
638 ParentScope, diag::note_acc_branch_into_compute_construct,
639 diag::note_acc_branch_out_of_compute_construct, CC->getBeginLoc()));
640 // This can be 'null' if the 'body' is a break that we diagnosed, so no
641 // reason to put the scope into place.
642 if (CC->getStructuredBlock())
643 BuildScopeInformation(S: CC->getStructuredBlock(), origParentScope&: NewParentScope);
644 return;
645 }
646
647 case Stmt::OpenACCCombinedConstructClass: {
648 unsigned NewParentScope = Scopes.size();
649 OpenACCCombinedConstruct *CC = cast<OpenACCCombinedConstruct>(Val: S);
650 Scopes.push_back(Elt: GotoScope(
651 ParentScope, diag::note_acc_branch_into_compute_construct,
652 diag::note_acc_branch_out_of_compute_construct, CC->getBeginLoc()));
653 // This can be 'null' if the 'body' is a break that we diagnosed, so no
654 // reason to put the scope into place.
655 if (CC->getLoop())
656 BuildScopeInformation(S: CC->getLoop(), origParentScope&: NewParentScope);
657 return;
658 }
659
660 default:
661 if (auto *ED = dyn_cast<OMPExecutableDirective>(Val: S)) {
662 if (!ED->isStandaloneDirective()) {
663 unsigned NewParentScope = Scopes.size();
664 Scopes.emplace_back(Args&: ParentScope,
665 Args: diag::note_omp_protected_structured_block,
666 Args: diag::note_omp_exits_structured_block,
667 Args: ED->getStructuredBlock()->getBeginLoc());
668 BuildScopeInformation(S: ED->getStructuredBlock(), origParentScope&: NewParentScope);
669 return;
670 }
671 }
672 break;
673 }
674
675 for (Stmt *SubStmt : S->children()) {
676 if (!SubStmt)
677 continue;
678 if (StmtsToSkip) {
679 --StmtsToSkip;
680 continue;
681 }
682
683 // Cases, labels, attributes, and defaults aren't "scope parents". It's also
684 // important to handle these iteratively instead of recursively in
685 // order to avoid blowing out the stack.
686 while (true) {
687 Stmt *Next;
688 if (SwitchCase *SC = dyn_cast<SwitchCase>(Val: SubStmt))
689 Next = SC->getSubStmt();
690 else if (LabelStmt *LS = dyn_cast<LabelStmt>(Val: SubStmt))
691 Next = LS->getSubStmt();
692 else if (AttributedStmt *AS = dyn_cast<AttributedStmt>(Val: SubStmt)) {
693 if (GetMustTailAttr(AS)) {
694 LabelAndGotoScopes[AS] = ParentScope;
695 MustTailStmts.push_back(Elt: AS);
696 }
697 Next = AS->getSubStmt();
698 } else
699 break;
700
701 LabelAndGotoScopes[SubStmt] = ParentScope;
702 SubStmt = Next;
703 }
704
705 // Recursively walk the AST.
706 BuildScopeInformation(S: SubStmt, origParentScope&: ParentScope);
707 }
708}
709
710/// VerifyJumps - Verify each element of the Jumps array to see if they are
711/// valid, emitting diagnostics if not.
712void JumpScopeChecker::VerifyJumps() {
713 while (!Jumps.empty()) {
714 Stmt *Jump = Jumps.pop_back_val();
715
716 // With a goto,
717 if (GotoStmt *GS = dyn_cast<GotoStmt>(Val: Jump)) {
718 // The label may not have a statement if it's coming from inline MS ASM.
719 if (GS->getLabel()->getStmt()) {
720 CheckJump(From: GS, To: GS->getLabel()->getStmt(), DiagLoc: GS->getGotoLoc(),
721 JumpDiag: diag::err_goto_into_protected_scope,
722 JumpDiagWarning: diag::ext_goto_into_protected_scope,
723 JumpDiagCompat: S.getLangOpts().CPlusPlus
724 ? diag::warn_cxx98_compat_goto_into_protected_scope
725 : diag::warn_cpp_compat_goto_into_protected_scope);
726 }
727 CheckGotoStmt(GS);
728 continue;
729 }
730
731 // If an asm goto jumps to a different scope, things like destructors or
732 // initializers might not be run which may be suprising to users. Perhaps
733 // this behavior can be changed in the future, but today Clang will not
734 // generate such code. Produce a diagnostic instead. See also the
735 // discussion here: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110728.
736 if (auto *G = dyn_cast<GCCAsmStmt>(Val: Jump)) {
737 for (AddrLabelExpr *L : G->labels()) {
738 LabelDecl *LD = L->getLabel();
739 unsigned JumpScope = LabelAndGotoScopes[G];
740 unsigned TargetScope = LabelAndGotoScopes[LD->getStmt()];
741 if (JumpScope != TargetScope)
742 DiagnoseIndirectOrAsmJump(IG: G, IGScope: JumpScope, Target: LD, TargetScope);
743 }
744 continue;
745 }
746
747 // We only get indirect gotos here when they have a constant target.
748 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Val: Jump)) {
749 LabelDecl *Target = IGS->getConstantTarget();
750 CheckJump(From: IGS, To: Target->getStmt(), DiagLoc: IGS->getGotoLoc(),
751 JumpDiag: diag::err_goto_into_protected_scope,
752 JumpDiagWarning: diag::ext_goto_into_protected_scope,
753 JumpDiagCompat: S.getLangOpts().CPlusPlus
754 ? diag::warn_cxx98_compat_goto_into_protected_scope
755 : diag::warn_cpp_compat_goto_into_protected_scope);
756 continue;
757 }
758
759 SwitchStmt *SS = cast<SwitchStmt>(Val: Jump);
760 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
761 SC = SC->getNextSwitchCase()) {
762 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
763 continue;
764 SourceLocation Loc;
765 if (CaseStmt *CS = dyn_cast<CaseStmt>(Val: SC))
766 Loc = CS->getBeginLoc();
767 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(Val: SC))
768 Loc = DS->getBeginLoc();
769 else
770 Loc = SC->getBeginLoc();
771 CheckJump(From: SS, To: SC, DiagLoc: Loc, JumpDiag: diag::err_switch_into_protected_scope, JumpDiagWarning: 0,
772 JumpDiagCompat: S.getLangOpts().CPlusPlus
773 ? diag::warn_cxx98_compat_switch_into_protected_scope
774 : diag::warn_cpp_compat_switch_into_protected_scope);
775 }
776 }
777}
778
779/// VerifyIndirectJumps - Verify whether any possible indirect goto jump might
780/// cross a protection boundary. Unlike direct jumps, indirect goto jumps
781/// count cleanups as protection boundaries: since there's no way to know where
782/// the jump is going, we can't implicitly run the right cleanups the way we
783/// can with direct jumps. Thus, an indirect/asm jump is "trivial" if it
784/// bypasses no initializations and no teardowns. More formally, an
785/// indirect/asm jump from A to B is trivial if the path out from A to DCA(A,B)
786/// is trivial and the path in from DCA(A,B) to B is trivial, where DCA(A,B) is
787/// the deepest common ancestor of A and B. Jump-triviality is transitive but
788/// asymmetric.
789///
790/// A path in is trivial if none of the entered scopes have an InDiag.
791/// A path out is trivial is none of the exited scopes have an OutDiag.
792///
793/// Under these definitions, this function checks that the indirect
794/// jump between A and B is trivial for every indirect goto statement A
795/// and every label B whose address was taken in the function.
796void JumpScopeChecker::VerifyIndirectJumps() {
797 if (IndirectJumps.empty())
798 return;
799 // If there aren't any address-of-label expressions in this function,
800 // complain about the first indirect goto.
801 if (IndirectJumpTargets.empty()) {
802 S.Diag(Loc: IndirectJumps[0]->getBeginLoc(),
803 DiagID: diag::err_indirect_goto_without_addrlabel);
804 return;
805 }
806 // Collect a single representative of every scope containing an indirect
807 // goto. For most code bases, this substantially cuts down on the number of
808 // jump sites we'll have to consider later.
809 using JumpScope = std::pair<unsigned, Stmt *>;
810 SmallVector<JumpScope, 32> JumpScopes;
811 {
812 llvm::DenseMap<unsigned, Stmt*> JumpScopesMap;
813 for (Stmt *IG : IndirectJumps) {
814 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
815 continue;
816 unsigned IGScope = LabelAndGotoScopes[IG];
817 JumpScopesMap.try_emplace(Key: IGScope, Args&: IG);
818 }
819 JumpScopes.reserve(N: JumpScopesMap.size());
820 for (auto &Pair : JumpScopesMap)
821 JumpScopes.emplace_back(Args&: Pair);
822 }
823
824 // Collect a single representative of every scope containing a
825 // label whose address was taken somewhere in the function.
826 // For most code bases, there will be only one such scope.
827 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
828 for (LabelDecl *TheLabel : IndirectJumpTargets) {
829 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
830 continue;
831 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
832 TargetScopes.try_emplace(Key: LabelScope, Args&: TheLabel);
833 }
834
835 // For each target scope, make sure it's trivially reachable from
836 // every scope containing a jump site.
837 //
838 // A path between scopes always consists of exitting zero or more
839 // scopes, then entering zero or more scopes. We build a set of
840 // of scopes S from which the target scope can be trivially
841 // entered, then verify that every jump scope can be trivially
842 // exitted to reach a scope in S.
843 llvm::BitVector Reachable(Scopes.size(), false);
844 for (auto [TargetScope, TargetLabel] : TargetScopes) {
845 Reachable.reset();
846
847 // Mark all the enclosing scopes from which you can safely jump
848 // into the target scope. 'Min' will end up being the index of
849 // the shallowest such scope.
850 unsigned Min = TargetScope;
851 while (true) {
852 Reachable.set(Min);
853
854 // Don't go beyond the outermost scope.
855 if (Min == 0) break;
856
857 // Stop if we can't trivially enter the current scope.
858 if (Scopes[Min].InDiag) break;
859
860 Min = Scopes[Min].ParentScope;
861 }
862
863 // Walk through all the jump sites, checking that they can trivially
864 // reach this label scope.
865 for (auto [JumpScope, JumpStmt] : JumpScopes) {
866 unsigned Scope = JumpScope;
867 // Walk out the "scope chain" for this scope, looking for a scope
868 // we've marked reachable. For well-formed code this amortizes
869 // to O(JumpScopes.size() / Scopes.size()): we only iterate
870 // when we see something unmarked, and in well-formed code we
871 // mark everything we iterate past.
872 bool IsReachable = false;
873 while (true) {
874 if (Reachable.test(Idx: Scope)) {
875 // If we find something reachable, mark all the scopes we just
876 // walked through as reachable.
877 for (unsigned S = JumpScope; S != Scope; S = Scopes[S].ParentScope)
878 Reachable.set(S);
879 IsReachable = true;
880 break;
881 }
882
883 // Don't walk out if we've reached the top-level scope or we've
884 // gotten shallower than the shallowest reachable scope.
885 if (Scope == 0 || Scope < Min) break;
886
887 // Don't walk out through an out-diagnostic.
888 if (Scopes[Scope].OutDiag) break;
889
890 Scope = Scopes[Scope].ParentScope;
891 }
892
893 // Only diagnose if we didn't find something.
894 if (IsReachable) continue;
895
896 DiagnoseIndirectOrAsmJump(IG: JumpStmt, IGScope: JumpScope, Target: TargetLabel, TargetScope);
897 }
898 }
899}
900
901/// Return true if a particular error+note combination must be downgraded to a
902/// warning in Microsoft mode.
903static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
904 return (JumpDiag == diag::err_goto_into_protected_scope &&
905 (InDiagNote == diag::note_protected_by_variable_init ||
906 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
907}
908
909/// Return true if a particular note should be downgraded to a compatibility
910/// warning in C++11 mode.
911static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
912 return S.getLangOpts().CPlusPlus11 &&
913 InDiagNote == diag::note_protected_by_variable_non_pod;
914}
915
916/// Returns true if a particular note should be a C++ compatibility warning in
917/// C mode with -Wc++-compat.
918static bool IsCppCompatWarning(Sema &S, unsigned InDiagNote) {
919 return !S.getLangOpts().CPlusPlus &&
920 InDiagNote == diag::note_protected_by_variable_init;
921}
922
923/// Produce primary diagnostic for an indirect jump statement.
924static void DiagnoseIndirectOrAsmJumpStmt(Sema &S, Stmt *Jump,
925 LabelDecl *Target, bool &Diagnosed) {
926 if (Diagnosed)
927 return;
928 bool IsAsmGoto = isa<GCCAsmStmt>(Val: Jump);
929 S.Diag(Loc: Jump->getBeginLoc(), DiagID: diag::err_indirect_goto_in_protected_scope)
930 << IsAsmGoto;
931 S.Diag(Loc: Target->getStmt()->getIdentLoc(), DiagID: diag::note_indirect_goto_target)
932 << IsAsmGoto;
933 Diagnosed = true;
934}
935
936/// Produce note diagnostics for a jump into a protected scope.
937void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
938 if (CHECK_PERMISSIVE(ToScopes.empty()))
939 return;
940 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
941 if (Scopes[ToScopes[I]].InDiag)
942 S.Diag(Loc: Scopes[ToScopes[I]].Loc, DiagID: Scopes[ToScopes[I]].InDiag);
943}
944
945/// Diagnose an indirect jump which is known to cross scopes.
946void JumpScopeChecker::DiagnoseIndirectOrAsmJump(Stmt *Jump, unsigned JumpScope,
947 LabelDecl *Target,
948 unsigned TargetScope) {
949 if (CHECK_PERMISSIVE(JumpScope == TargetScope))
950 return;
951
952 unsigned Common = GetDeepestCommonScope(A: JumpScope, B: TargetScope);
953 bool Diagnosed = false;
954
955 // Walk out the scope chain until we reach the common ancestor.
956 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
957 if (Scopes[I].OutDiag) {
958 DiagnoseIndirectOrAsmJumpStmt(S, Jump, Target, Diagnosed);
959 S.Diag(Loc: Scopes[I].Loc, DiagID: Scopes[I].OutDiag);
960 }
961
962 SmallVector<unsigned, 10> ToScopesCXX98Compat, ToScopesCppCompat;
963
964 // Now walk into the scopes containing the label whose address was taken.
965 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
966 if (IsCXX98CompatWarning(S, InDiagNote: Scopes[I].InDiag))
967 ToScopesCXX98Compat.push_back(Elt: I);
968 else if (IsCppCompatWarning(S, InDiagNote: Scopes[I].InDiag))
969 ToScopesCppCompat.push_back(Elt: I);
970 else if (Scopes[I].InDiag) {
971 DiagnoseIndirectOrAsmJumpStmt(S, Jump, Target, Diagnosed);
972 S.Diag(Loc: Scopes[I].Loc, DiagID: Scopes[I].InDiag);
973 }
974
975 // Diagnose this jump if it would be ill-formed in C++[98].
976 if (!Diagnosed) {
977 bool IsAsmGoto = isa<GCCAsmStmt>(Val: Jump);
978 auto Diag = [&](unsigned DiagId, const SmallVectorImpl<unsigned> &Notes) {
979 S.Diag(Loc: Jump->getBeginLoc(), DiagID: DiagId) << IsAsmGoto;
980 S.Diag(Loc: Target->getStmt()->getIdentLoc(), DiagID: diag::note_indirect_goto_target)
981 << IsAsmGoto;
982 NoteJumpIntoScopes(ToScopes: Notes);
983 };
984 if (!ToScopesCXX98Compat.empty())
985 Diag(diag::warn_cxx98_compat_indirect_goto_in_protected_scope,
986 ToScopesCXX98Compat);
987 else if (!ToScopesCppCompat.empty())
988 Diag(diag::warn_cpp_compat_indirect_goto_in_protected_scope,
989 ToScopesCppCompat);
990 }
991}
992
993/// CheckJump - Validate that the specified jump statement is valid: that it is
994/// jumping within or out of its current scope, not into a deeper one.
995void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
996 unsigned JumpDiagError,
997 unsigned JumpDiagWarning,
998 unsigned JumpDiagCompat) {
999 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
1000 return;
1001 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
1002 return;
1003
1004 unsigned FromScope = LabelAndGotoScopes[From];
1005 unsigned ToScope = LabelAndGotoScopes[To];
1006
1007 // Common case: exactly the same scope, which is fine.
1008 if (FromScope == ToScope) return;
1009
1010 // Warn on gotos out of __finally blocks and defer statements.
1011 if (isa<GotoStmt>(Val: From) || isa<IndirectGotoStmt>(Val: From)) {
1012 // If FromScope > ToScope, FromScope is more nested and the jump goes to a
1013 // less nested scope. Check if it crosses a __finally along the way.
1014 for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
1015 if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
1016 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_jump_out_of_seh_finally);
1017 break;
1018 } else if (Scopes[I].InDiag ==
1019 diag::note_omp_protected_structured_block) {
1020 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::err_goto_into_protected_scope);
1021 S.Diag(Loc: To->getBeginLoc(), DiagID: diag::note_omp_exits_structured_block);
1022 break;
1023 } else if (Scopes[I].InDiag ==
1024 diag::note_acc_branch_into_compute_construct) {
1025 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::err_goto_into_protected_scope);
1026 S.Diag(Loc: Scopes[I].Loc, DiagID: diag::note_acc_branch_out_of_compute_construct);
1027 return;
1028 } else if (Scopes[I].OutDiag == diag::note_exits_defer_stmt) {
1029 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::err_goto_into_protected_scope);
1030 S.Diag(Loc: Scopes[I].Loc, DiagID: diag::note_exits_defer_stmt);
1031 return;
1032 }
1033 }
1034 }
1035
1036 unsigned CommonScope = GetDeepestCommonScope(A: FromScope, B: ToScope);
1037
1038 // It's okay to jump out from a nested scope.
1039 if (CommonScope == ToScope) return;
1040
1041 // Pull out (and reverse) any scopes we might need to diagnose skipping.
1042 SmallVector<unsigned, 10> ToScopesCompat;
1043 SmallVector<unsigned, 10> ToScopesError;
1044 SmallVector<unsigned, 10> ToScopesWarning;
1045 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
1046 if (S.getLangOpts().MSVCCompat && S.getLangOpts().CPlusPlus &&
1047 JumpDiagWarning != 0 &&
1048 IsMicrosoftJumpWarning(JumpDiag: JumpDiagError, InDiagNote: Scopes[I].InDiag))
1049 ToScopesWarning.push_back(Elt: I);
1050 else if (IsCXX98CompatWarning(S, InDiagNote: Scopes[I].InDiag) ||
1051 IsCppCompatWarning(S, InDiagNote: Scopes[I].InDiag))
1052 ToScopesCompat.push_back(Elt: I);
1053 else if (Scopes[I].InDiag)
1054 ToScopesError.push_back(Elt: I);
1055 }
1056
1057 // Handle warnings.
1058 if (!ToScopesWarning.empty()) {
1059 S.Diag(Loc: DiagLoc, DiagID: JumpDiagWarning);
1060 NoteJumpIntoScopes(ToScopes: ToScopesWarning);
1061 assert(isa<LabelStmt>(To));
1062 LabelStmt *Label = cast<LabelStmt>(Val: To);
1063 Label->setSideEntry(true);
1064 }
1065
1066 // Handle errors.
1067 if (!ToScopesError.empty()) {
1068 S.Diag(Loc: DiagLoc, DiagID: JumpDiagError);
1069 NoteJumpIntoScopes(ToScopes: ToScopesError);
1070 }
1071
1072 // Handle -Wc++98-compat or -Wc++-compat warnings if the jump is well-formed.
1073 if (ToScopesError.empty() && !ToScopesCompat.empty()) {
1074 S.Diag(Loc: DiagLoc, DiagID: JumpDiagCompat);
1075 NoteJumpIntoScopes(ToScopes: ToScopesCompat);
1076 }
1077}
1078
1079void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
1080 if (GS->getLabel()->isMSAsmLabel()) {
1081 S.Diag(Loc: GS->getGotoLoc(), DiagID: diag::err_goto_ms_asm_label)
1082 << GS->getLabel()->getIdentifier();
1083 S.Diag(Loc: GS->getLabel()->getLocation(), DiagID: diag::note_goto_ms_asm_label)
1084 << GS->getLabel()->getIdentifier();
1085 }
1086}
1087
1088void JumpScopeChecker::VerifyMustTailStmts() {
1089 for (AttributedStmt *AS : MustTailStmts) {
1090 for (unsigned I = LabelAndGotoScopes[AS]; I; I = Scopes[I].ParentScope) {
1091 if (Scopes[I].OutDiag) {
1092 S.Diag(Loc: AS->getBeginLoc(), DiagID: diag::err_musttail_scope);
1093 S.Diag(Loc: Scopes[I].Loc, DiagID: Scopes[I].OutDiag);
1094 }
1095 }
1096 }
1097}
1098
1099const Attr *JumpScopeChecker::GetMustTailAttr(AttributedStmt *AS) {
1100 ArrayRef<const Attr *> Attrs = AS->getAttrs();
1101 const auto *Iter =
1102 llvm::find_if(Range&: Attrs, P: [](const Attr *A) { return isa<MustTailAttr>(Val: A); });
1103 return Iter != Attrs.end() ? *Iter : nullptr;
1104}
1105
1106void Sema::DiagnoseInvalidJumps(Stmt *Body) {
1107 (void)JumpScopeChecker(Body, *this);
1108}
1109