Coverage Report

Created: 2024-10-22 16:19

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