Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExceptionSpec.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- 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 provides Sema routines for C++ exception specification testing.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Sema/SemaInternal.h"
14
#include "clang/AST/ASTMutationListener.h"
15
#include "clang/AST/CXXInheritance.h"
16
#include "clang/AST/Expr.h"
17
#include "clang/AST/ExprCXX.h"
18
#include "clang/AST/StmtObjC.h"
19
#include "clang/AST/TypeLoc.h"
20
#include "clang/Basic/Diagnostic.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "llvm/ADT/SmallPtrSet.h"
23
#include "llvm/ADT/SmallString.h"
24
25
namespace clang {
26
27
static const FunctionProtoType *GetUnderlyingFunction(QualType T)
28
4.84M
{
29
4.84M
  if (const PointerType *PtrTy = T->getAs<PointerType>())
30
568k
    T = PtrTy->getPointeeType();
31
4.27M
  else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32
2.25k
    T = RefTy->getPointeeType();
33
4.27M
  else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34
4.09k
    T = MPTy->getPointeeType();
35
4.84M
  return T->getAs<FunctionProtoType>();
36
4.84M
}
37
38
/// HACK: 2014-11-14 libstdc++ had a bug where it shadows std::swap with a
39
/// member swap function then tries to call std::swap unqualified from the
40
/// exception specification of that function. This function detects whether
41
/// we're in such a case and turns off delay-parsing of exception
42
/// specifications. Libstdc++ 6.1 (released 2016-04-27) appears to have
43
/// resolved it as side-effect of commit ddb63209a8d (2015-06-05).
44
1.01M
bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
45
1.01M
  auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
46
47
  // All the problem cases are member functions named "swap" within class
48
  // templates declared directly within namespace std or std::__debug or
49
  // std::__profile.
50
1.01M
  if (!RD || 
!RD->getIdentifier()1.01M
||
!RD->getDescribedClassTemplate()1.01M
||
51
1.01M
      
!D.getIdentifier()523k
||
!D.getIdentifier()->isStr("swap")269k
)
52
1.01M
    return false;
53
54
5.63k
  auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
55
5.63k
  if (!ND)
56
1
    return false;
57
58
5.63k
  bool IsInStd = ND->isStdNamespace();
59
5.63k
  if (!IsInStd) {
60
    // This isn't a direct member of namespace std, but it might still be
61
    // libstdc++'s std::__debug::array or std::__profile::array.
62
22
    IdentifierInfo *II = ND->getIdentifier();
63
22
    if (!II || !(II->isStr("__debug") || 
II->isStr("__profile")21
) ||
64
22
        
!ND->isInStdNamespace()2
)
65
20
      return false;
66
22
  }
67
68
  // Only apply this hack within a system header.
69
5.61k
  if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
70
0
    return false;
71
72
5.61k
  return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
73
5.61k
      .Case("array", true)
74
5.61k
      .Case("pair", IsInStd)
75
5.61k
      .Case("priority_queue", IsInStd)
76
5.61k
      .Case("stack", IsInStd)
77
5.61k
      .Case("queue", IsInStd)
78
5.61k
      .Default(false);
79
5.61k
}
80
81
ExprResult Sema::ActOnNoexceptSpec(Expr *NoexceptExpr,
82
57.0k
                                   ExceptionSpecificationType &EST) {
83
84
57.0k
  if (NoexceptExpr->isTypeDependent() ||
85
57.0k
      
NoexceptExpr->containsUnexpandedParameterPack()15.6k
) {
86
41.3k
    EST = EST_DependentNoexcept;
87
41.3k
    return NoexceptExpr;
88
41.3k
  }
89
90
15.6k
  llvm::APSInt Result;
91
15.6k
  ExprResult Converted = CheckConvertedConstantExpression(
92
15.6k
      NoexceptExpr, Context.BoolTy, Result, CCEK_Noexcept);
93
94
15.6k
  if (Converted.isInvalid()) {
95
17
    EST = EST_NoexceptFalse;
96
    // Fill in an expression of 'false' as a fixup.
97
17
    auto *BoolExpr = new (Context)
98
17
        CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc());
99
17
    llvm::APSInt Value{1};
100
17
    Value = 0;
101
17
    return ConstantExpr::Create(Context, BoolExpr, APValue{Value});
102
17
  }
103
104
15.6k
  if (Converted.get()->isValueDependent()) {
105
9.08k
    EST = EST_DependentNoexcept;
106
9.08k
    return Converted;
107
9.08k
  }
108
109
6.55k
  if (!Converted.isInvalid())
110
6.55k
    EST = !Result ? 
EST_NoexceptFalse790
:
EST_NoexceptTrue5.76k
;
111
6.55k
  return Converted;
112
15.6k
}
113
114
/// CheckSpecifiedExceptionType - Check if the given type is valid in an
115
/// exception specification. Incomplete types, or pointers to incomplete types
116
/// other than void are not allowed.
117
///
118
/// \param[in,out] T  The exception type. This will be decayed to a pointer type
119
///                   when the input is an array or a function type.
120
773
bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
121
  // C++11 [except.spec]p2:
122
  //   A type cv T, "array of T", or "function returning T" denoted
123
  //   in an exception-specification is adjusted to type T, "pointer to T", or
124
  //   "pointer to function returning T", respectively.
125
  //
126
  // We also apply this rule in C++98.
127
773
  if (T->isArrayType())
128
14
    T = Context.getArrayDecayedType(T);
129
759
  else if (T->isFunctionType())
130
4
    T = Context.getPointerType(T);
131
132
773
  int Kind = 0;
133
773
  QualType PointeeT = T;
134
773
  if (const PointerType *PT = T->getAs<PointerType>()) {
135
96
    PointeeT = PT->getPointeeType();
136
96
    Kind = 1;
137
138
    // cv void* is explicitly permitted, despite being a pointer to an
139
    // incomplete type.
140
96
    if (PointeeT->isVoidType())
141
5
      return false;
142
677
  } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
143
56
    PointeeT = RT->getPointeeType();
144
56
    Kind = 2;
145
146
56
    if (RT->isRValueReferenceType()) {
147
      // C++11 [except.spec]p2:
148
      //   A type denoted in an exception-specification shall not denote [...]
149
      //   an rvalue reference type.
150
3
      Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
151
3
        << T << Range;
152
3
      return true;
153
3
    }
154
56
  }
155
156
  // C++11 [except.spec]p2:
157
  //   A type denoted in an exception-specification shall not denote an
158
  //   incomplete type other than a class currently being defined [...].
159
  //   A type denoted in an exception-specification shall not denote a
160
  //   pointer or reference to an incomplete type, other than (cv) void* or a
161
  //   pointer or reference to a class currently being defined.
162
  // In Microsoft mode, downgrade this to a warning.
163
765
  unsigned DiagID = diag::err_incomplete_in_exception_spec;
164
765
  bool ReturnValueOnError = true;
165
765
  if (getLangOpts().MSVCCompat) {
166
27
    DiagID = diag::ext_incomplete_in_exception_spec;
167
27
    ReturnValueOnError = false;
168
27
  }
169
765
  if (!(PointeeT->isRecordType() &&
170
765
        
PointeeT->castAs<RecordType>()->isBeingDefined()247
) &&
171
765
      
RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range)762
)
172
17
    return ReturnValueOnError;
173
174
  // The MSVC compatibility mode doesn't extend to sizeless types,
175
  // so diagnose them separately.
176
748
  if (PointeeT->isSizelessType() && 
Kind != 16
) {
177
4
    Diag(Range.getBegin(), diag::err_sizeless_in_exception_spec)
178
4
        << (Kind == 2 ? 
12
:
02
) << PointeeT << Range;
179
4
    return true;
180
4
  }
181
182
744
  return false;
183
748
}
184
185
/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
186
/// to member to a function with an exception specification. This means that
187
/// it is invalid to add another level of indirection.
188
4.47M
bool Sema::CheckDistantExceptionSpec(QualType T) {
189
  // C++17 removes this rule in favor of putting exception specifications into
190
  // the type system.
191
4.47M
  if (getLangOpts().CPlusPlus17)
192
88.3k
    return false;
193
194
4.38M
  if (const PointerType *PT = T->getAs<PointerType>())
195
83.9k
    T = PT->getPointeeType();
196
4.29M
  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
197
187
    T = PT->getPointeeType();
198
4.29M
  else
199
4.29M
    return false;
200
201
84.1k
  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
202
84.1k
  if (!FnT)
203
83.6k
    return false;
204
205
534
  return FnT->hasExceptionSpec();
206
84.1k
}
207
208
const FunctionProtoType *
209
4.37M
Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
210
4.37M
  if (FPT->getExceptionSpecType() == EST_Unparsed) {
211
1
    Diag(Loc, diag::err_exception_spec_not_parsed);
212
1
    return nullptr;
213
1
  }
214
215
4.37M
  if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
216
4.17M
    return FPT;
217
218
200k
  FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
219
200k
  const FunctionProtoType *SourceFPT =
220
200k
      SourceDecl->getType()->castAs<FunctionProtoType>();
221
222
  // If the exception specification has already been resolved, just return it.
223
200k
  if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
224
7.81k
    return SourceFPT;
225
226
  // Compute or instantiate the exception specification now.
227
192k
  if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
228
186k
    EvaluateImplicitExceptionSpec(Loc, SourceDecl);
229
6.09k
  else
230
6.09k
    InstantiateExceptionSpec(Loc, SourceDecl);
231
232
192k
  const FunctionProtoType *Proto =
233
192k
    SourceDecl->getType()->castAs<FunctionProtoType>();
234
192k
  if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
235
2
    Diag(Loc, diag::err_exception_spec_not_parsed);
236
2
    Proto = nullptr;
237
2
  }
238
192k
  return Proto;
239
200k
}
240
241
void
242
Sema::UpdateExceptionSpec(FunctionDecl *FD,
243
596k
                          const FunctionProtoType::ExceptionSpecInfo &ESI) {
244
  // If we've fully resolved the exception specification, notify listeners.
245
596k
  if (!isUnresolvedExceptionSpec(ESI.Type))
246
596k
    if (auto *Listener = getASTMutationListener())
247
32.0k
      Listener->ResolvedExceptionSpec(FD);
248
249
596k
  for (FunctionDecl *Redecl : FD->redecls())
250
596k
    Context.adjustExceptionSpec(Redecl, ESI);
251
596k
}
252
253
473k
static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
254
473k
  auto *MD = dyn_cast<CXXMethodDecl>(FD);
255
473k
  if (!MD)
256
114k
    return false;
257
258
359k
  auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
259
359k
  return EST == EST_Unparsed ||
260
359k
         
(359k
EST == EST_Unevaluated359k
&&
MD->getParent()->isBeingDefined()18.3k
);
261
473k
}
262
263
static bool CheckEquivalentExceptionSpecImpl(
264
    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
265
    const FunctionProtoType *Old, SourceLocation OldLoc,
266
    const FunctionProtoType *New, SourceLocation NewLoc,
267
    bool *MissingExceptionSpecification = nullptr,
268
    bool *MissingEmptyExceptionSpecification = nullptr,
269
    bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
270
271
/// Determine whether a function has an implicitly-generated exception
272
/// specification.
273
385k
static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
274
385k
  if (!isa<CXXDestructorDecl>(Decl) &&
275
385k
      
Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete379k
&&
276
385k
      
Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete378k
)
277
377k
    return false;
278
279
  // For a function that the user didn't declare:
280
  //  - if this is a destructor, its exception specification is implicit.
281
  //  - if this is 'operator delete' or 'operator delete[]', the exception
282
  //    specification is as-if an explicit exception specification was given
283
  //    (per [basic.stc.dynamic]p2).
284
7.76k
  if (!Decl->getTypeSourceInfo())
285
911
    return isa<CXXDestructorDecl>(Decl);
286
287
6.85k
  auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
288
6.85k
  return !Ty->hasExceptionSpec();
289
7.76k
}
290
291
215k
bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
292
  // Just completely ignore this under -fno-exceptions prior to C++17.
293
  // In C++17 onwards, the exception specification is part of the type and
294
  // we will diagnose mismatches anyway, so it's better to check for them here.
295
215k
  if (!getLangOpts().CXXExceptions && 
!getLangOpts().CPlusPlus1721.5k
)
296
17.4k
    return false;
297
298
197k
  OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
299
197k
  bool IsOperatorNew = OO == OO_New || 
OO == OO_Array_New197k
;
300
197k
  bool MissingExceptionSpecification = false;
301
197k
  bool MissingEmptyExceptionSpecification = false;
302
303
197k
  unsigned DiagID = diag::err_mismatched_exception_spec;
304
197k
  bool ReturnValueOnError = true;
305
197k
  if (getLangOpts().MSVCCompat) {
306
234
    DiagID = diag::ext_mismatched_exception_spec;
307
234
    ReturnValueOnError = false;
308
234
  }
309
310
  // If we're befriending a member function of a class that's currently being
311
  // defined, we might not be able to work out its exception specification yet.
312
  // If not, defer the check until later.
313
197k
  if (exceptionSpecNotKnownYet(Old) || 
exceptionSpecNotKnownYet(New)197k
) {
314
17
    DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
315
17
    return false;
316
17
  }
317
318
  // Check the types as written: they must match before any exception
319
  // specification adjustment is applied.
320
197k
  if (!CheckEquivalentExceptionSpecImpl(
321
197k
        *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
322
197k
        Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
323
197k
        New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
324
197k
        &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
325
197k
        /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
326
    // C++11 [except.spec]p4 [DR1492]:
327
    //   If a declaration of a function has an implicit
328
    //   exception-specification, other declarations of the function shall
329
    //   not specify an exception-specification.
330
197k
    if (getLangOpts().CPlusPlus11 && 
getLangOpts().CXXExceptions196k
&&
331
197k
        
hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)192k
) {
332
23
      Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
333
23
        << hasImplicitExceptionSpec(Old);
334
23
      if (Old->getLocation().isValid())
335
11
        Diag(Old->getLocation(), diag::note_previous_declaration);
336
23
    }
337
197k
    return false;
338
197k
  }
339
340
  // The failure was something other than an missing exception
341
  // specification; return an error, except in MS mode where this is a warning.
342
300
  if (!MissingExceptionSpecification)
343
55
    return ReturnValueOnError;
344
345
245
  const FunctionProtoType *NewProto =
346
245
    New->getType()->castAs<FunctionProtoType>();
347
348
  // The new function declaration is only missing an empty exception
349
  // specification "throw()". If the throw() specification came from a
350
  // function in a system header that has C linkage, just add an empty
351
  // exception specification to the "new" declaration. Note that C library
352
  // implementations are permitted to add these nothrow exception
353
  // specifications.
354
  //
355
  // Likewise if the old function is a builtin.
356
245
  if (MissingEmptyExceptionSpecification && 
NewProto240
&&
357
245
      
(240
Old->getLocation().isInvalid()240
||
358
240
       
Context.getSourceManager().isInSystemHeader(Old->getLocation())238
||
359
240
       
Old->getBuiltinID()34
) &&
360
245
      
Old->isExternC()209
) {
361
207
    New->setType(Context.getFunctionType(
362
207
        NewProto->getReturnType(), NewProto->getParamTypes(),
363
207
        NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
364
207
    return false;
365
207
  }
366
367
38
  const FunctionProtoType *OldProto =
368
38
    Old->getType()->castAs<FunctionProtoType>();
369
370
38
  FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
371
38
  if (ESI.Type == EST_Dynamic) {
372
    // FIXME: What if the exceptions are described in terms of the old
373
    // prototype's parameters?
374
4
    ESI.Exceptions = OldProto->exceptions();
375
4
  }
376
377
38
  if (ESI.Type == EST_NoexceptFalse)
378
0
    ESI.Type = EST_None;
379
38
  if (ESI.Type == EST_NoexceptTrue)
380
1
    ESI.Type = EST_BasicNoexcept;
381
382
  // For dependent noexcept, we can't just take the expression from the old
383
  // prototype. It likely contains references to the old prototype's parameters.
384
38
  if (ESI.Type == EST_DependentNoexcept) {
385
1
    New->setInvalidDecl();
386
37
  } else {
387
    // Update the type of the function with the appropriate exception
388
    // specification.
389
37
    New->setType(Context.getFunctionType(
390
37
        NewProto->getReturnType(), NewProto->getParamTypes(),
391
37
        NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
392
37
  }
393
394
38
  if (getLangOpts().MSVCCompat && 
isDynamicExceptionSpec(ESI.Type)16
) {
395
6
    DiagID = diag::ext_missing_exception_specification;
396
6
    ReturnValueOnError = false;
397
32
  } else if (New->isReplaceableGlobalAllocationFunction() &&
398
32
             
ESI.Type != EST_DependentNoexcept4
) {
399
    // Allow missing exception specifications in redeclarations as an extension,
400
    // when declaring a replaceable global allocation function.
401
4
    DiagID = diag::ext_missing_exception_specification;
402
4
    ReturnValueOnError = false;
403
28
  } else if (ESI.Type == EST_NoThrow) {
404
    // Don't emit any warning for missing 'nothrow' in MSVC.
405
10
    if (getLangOpts().MSVCCompat) {
406
5
      return false;
407
5
    }
408
    // Allow missing attribute 'nothrow' in redeclarations, since this is a very
409
    // common omission.
410
5
    DiagID = diag::ext_missing_exception_specification;
411
5
    ReturnValueOnError = false;
412
18
  } else {
413
18
    DiagID = diag::err_missing_exception_specification;
414
18
    ReturnValueOnError = true;
415
18
  }
416
417
  // Warn about the lack of exception specification.
418
33
  SmallString<128> ExceptionSpecString;
419
33
  llvm::raw_svector_ostream OS(ExceptionSpecString);
420
33
  switch (OldProto->getExceptionSpecType()) {
421
13
  case EST_DynamicNone:
422
13
    OS << "throw()";
423
13
    break;
424
425
4
  case EST_Dynamic: {
426
4
    OS << "throw(";
427
4
    bool OnFirstException = true;
428
4
    for (const auto &E : OldProto->exceptions()) {
429
4
      if (OnFirstException)
430
4
        OnFirstException = false;
431
0
      else
432
0
        OS << ", ";
433
434
4
      OS << E.getAsString(getPrintingPolicy());
435
4
    }
436
4
    OS << ")";
437
4
    break;
438
0
  }
439
440
9
  case EST_BasicNoexcept:
441
9
    OS << "noexcept";
442
9
    break;
443
444
1
  case EST_DependentNoexcept:
445
1
  case EST_NoexceptFalse:
446
2
  case EST_NoexceptTrue:
447
2
    OS << "noexcept(";
448
2
    assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
449
0
    OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
450
2
    OS << ")";
451
2
    break;
452
5
  case EST_NoThrow:
453
5
    OS <<"__attribute__((nothrow))";
454
5
    break;
455
0
  case EST_None:
456
0
  case EST_MSAny:
457
0
  case EST_Unevaluated:
458
0
  case EST_Uninstantiated:
459
0
  case EST_Unparsed:
460
0
    llvm_unreachable("This spec type is compatible with none.");
461
33
  }
462
463
33
  SourceLocation FixItLoc;
464
33
  if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
465
33
    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
466
    // FIXME: Preserve enough information so that we can produce a correct fixit
467
    // location when there is a trailing return type.
468
33
    if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
469
33
      if (!FTLoc.getTypePtr()->hasTrailingReturn())
470
33
        FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
471
33
  }
472
473
33
  if (FixItLoc.isInvalid())
474
0
    Diag(New->getLocation(), DiagID)
475
0
      << New << OS.str();
476
33
  else {
477
33
    Diag(New->getLocation(), DiagID)
478
33
      << New << OS.str()
479
33
      << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
480
33
  }
481
482
33
  if (Old->getLocation().isValid())
483
30
    Diag(Old->getLocation(), diag::note_previous_declaration);
484
485
33
  return ReturnValueOnError;
486
33
}
487
488
/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
489
/// exception specifications. Exception specifications are equivalent if
490
/// they allow exactly the same set of exception types. It does not matter how
491
/// that is achieved. See C++ [except.spec]p2.
492
bool Sema::CheckEquivalentExceptionSpec(
493
    const FunctionProtoType *Old, SourceLocation OldLoc,
494
2.13k
    const FunctionProtoType *New, SourceLocation NewLoc) {
495
2.13k
  if (!getLangOpts().CXXExceptions)
496
1.29k
    return false;
497
498
841
  unsigned DiagID = diag::err_mismatched_exception_spec;
499
841
  if (getLangOpts().MSVCCompat)
500
0
    DiagID = diag::ext_mismatched_exception_spec;
501
841
  bool Result = CheckEquivalentExceptionSpecImpl(
502
841
      *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
503
841
      Old, OldLoc, New, NewLoc);
504
505
  // In Microsoft mode, mismatching exception specifications just cause a warning.
506
841
  if (getLangOpts().MSVCCompat)
507
0
    return false;
508
841
  return Result;
509
841
}
510
511
/// CheckEquivalentExceptionSpec - Check if the two types have compatible
512
/// exception specifications. See C++ [except.spec]p3.
513
///
514
/// \return \c false if the exception specifications match, \c true if there is
515
/// a problem. If \c true is returned, either a diagnostic has already been
516
/// produced or \c *MissingExceptionSpecification is set to \c true.
517
static bool CheckEquivalentExceptionSpecImpl(
518
    Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
519
    const FunctionProtoType *Old, SourceLocation OldLoc,
520
    const FunctionProtoType *New, SourceLocation NewLoc,
521
    bool *MissingExceptionSpecification,
522
    bool *MissingEmptyExceptionSpecification,
523
198k
    bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
524
198k
  if (MissingExceptionSpecification)
525
197k
    *MissingExceptionSpecification = false;
526
527
198k
  if (MissingEmptyExceptionSpecification)
528
197k
    *MissingEmptyExceptionSpecification = false;
529
530
198k
  Old = S.ResolveExceptionSpec(NewLoc, Old);
531
198k
  if (!Old)
532
0
    return false;
533
198k
  New = S.ResolveExceptionSpec(NewLoc, New);
534
198k
  if (!New)
535
0
    return false;
536
537
  // C++0x [except.spec]p3: Two exception-specifications are compatible if:
538
  //   - both are non-throwing, regardless of their form,
539
  //   - both have the form noexcept(constant-expression) and the constant-
540
  //     expressions are equivalent,
541
  //   - both are dynamic-exception-specifications that have the same set of
542
  //     adjusted types.
543
  //
544
  // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
545
  //   of the form throw(), noexcept, or noexcept(constant-expression) where the
546
  //   constant-expression yields true.
547
  //
548
  // C++0x [except.spec]p4: If any declaration of a function has an exception-
549
  //   specifier that is not a noexcept-specification allowing all exceptions,
550
  //   all declarations [...] of that function shall have a compatible
551
  //   exception-specification.
552
  //
553
  // That last point basically means that noexcept(false) matches no spec.
554
  // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
555
556
198k
  ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
557
198k
  ExceptionSpecificationType NewEST = New->getExceptionSpecType();
558
559
198k
  assert(!isUnresolvedExceptionSpec(OldEST) &&
560
198k
         !isUnresolvedExceptionSpec(NewEST) &&
561
198k
         "Shouldn't see unknown exception specifications here");
562
563
0
  CanThrowResult OldCanThrow = Old->canThrow();
564
198k
  CanThrowResult NewCanThrow = New->canThrow();
565
566
  // Any non-throwing specifications are compatible.
567
198k
  if (OldCanThrow == CT_Cannot && 
NewCanThrow == CT_Cannot47.5k
)
568
47.2k
    return false;
569
570
  // Any throws-anything specifications are usually compatible.
571
151k
  if (OldCanThrow == CT_Can && 
OldEST != EST_Dynamic144k
&&
572
151k
      
NewCanThrow == CT_Can144k
&&
NewEST != EST_Dynamic144k
) {
573
    // The exception is that the absence of an exception specification only
574
    // matches noexcept(false) for functions, as described above.
575
144k
    if (!AllowNoexceptAllMatchWithNoSpec &&
576
144k
        
(823
(823
OldEST == EST_None823
&&
NewEST == EST_NoexceptFalse821
) ||
577
823
         
(822
OldEST == EST_NoexceptFalse822
&&
NewEST == EST_None2
))) {
578
      // This is the disallowed case.
579
144k
    } else {
580
144k
      return false;
581
144k
    }
582
144k
  }
583
584
  // C++14 [except.spec]p3:
585
  //   Two exception-specifications are compatible if [...] both have the form
586
  //   noexcept(constant-expression) and the constant-expressions are equivalent
587
7.01k
  if (OldEST == EST_DependentNoexcept && 
NewEST == EST_DependentNoexcept6.66k
) {
588
6.66k
    llvm::FoldingSetNodeID OldFSN, NewFSN;
589
6.66k
    Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
590
6.66k
    New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
591
6.66k
    if (OldFSN == NewFSN)
592
6.65k
      return false;
593
6.66k
  }
594
595
  // Dynamic exception specifications with the same set of adjusted types
596
  // are compatible.
597
353
  if (OldEST == EST_Dynamic && 
NewEST == EST_Dynamic46
) {
598
29
    bool Success = true;
599
    // Both have a dynamic exception spec. Collect the first set, then compare
600
    // to the second.
601
29
    llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
602
29
    for (const auto &I : Old->exceptions())
603
34
      OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
604
605
36
    for (const auto &I : New->exceptions()) {
606
36
      CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
607
36
      if (OldTypes.count(TypePtr))
608
26
        NewTypes.insert(TypePtr);
609
10
      else {
610
10
        Success = false;
611
10
        break;
612
10
      }
613
36
    }
614
615
29
    if (Success && 
OldTypes.size() == NewTypes.size()19
)
616
19
      return false;
617
29
  }
618
619
  // As a special compatibility feature, under C++0x we accept no spec and
620
  // throw(std::bad_alloc) as equivalent for operator new and operator new[].
621
  // This is because the implicit declaration changed, but old code would break.
622
334
  if (S.getLangOpts().CPlusPlus11 && 
IsOperatorNew325
) {
623
12
    const FunctionProtoType *WithExceptions = nullptr;
624
12
    if (OldEST == EST_None && 
NewEST == EST_Dynamic9
)
625
6
      WithExceptions = New;
626
6
    else if (OldEST == EST_Dynamic && 
NewEST == EST_None3
)
627
3
      WithExceptions = Old;
628
12
    if (WithExceptions && 
WithExceptions->getNumExceptions() == 19
) {
629
      // One has no spec, the other throw(something). If that something is
630
      // std::bad_alloc, all conditions are met.
631
9
      QualType Exception = *WithExceptions->exception_begin();
632
9
      if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
633
9
        IdentifierInfo* Name = ExRecord->getIdentifier();
634
9
        if (Name && Name->getName() == "bad_alloc") {
635
          // It's called bad_alloc, but is it in std?
636
9
          if (ExRecord->isInStdNamespace()) {
637
9
            return false;
638
9
          }
639
9
        }
640
9
      }
641
9
    }
642
12
  }
643
644
  // If the caller wants to handle the case that the new function is
645
  // incompatible due to a missing exception specification, let it.
646
325
  if (MissingExceptionSpecification && 
OldEST != EST_None300
&&
647
325
      
NewEST == EST_None283
) {
648
    // The old type has an exception specification of some sort, but
649
    // the new type does not.
650
245
    *MissingExceptionSpecification = true;
651
652
245
    if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
653
      // The old type has a throw() or noexcept(true) exception specification
654
      // and the new type has no exception specification, and the caller asked
655
      // to handle this itself.
656
240
      *MissingEmptyExceptionSpecification = true;
657
240
    }
658
659
245
    return true;
660
245
  }
661
662
80
  S.Diag(NewLoc, DiagID);
663
80
  if (NoteID.getDiagID() != 0 && 
OldLoc.isValid()76
)
664
73
    S.Diag(OldLoc, NoteID);
665
80
  return true;
666
325
}
667
668
bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
669
                                        const PartialDiagnostic &NoteID,
670
                                        const FunctionProtoType *Old,
671
                                        SourceLocation OldLoc,
672
                                        const FunctionProtoType *New,
673
17
                                        SourceLocation NewLoc) {
674
17
  if (!getLangOpts().CXXExceptions)
675
0
    return false;
676
17
  return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
677
17
                                          New, NewLoc);
678
17
}
679
680
226
bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
681
  // [except.handle]p3:
682
  //   A handler is a match for an exception object of type E if:
683
684
  // HandlerType must be ExceptionType or derived from it, or pointer or
685
  // reference to such types.
686
226
  const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
687
226
  if (RefTy)
688
45
    HandlerType = RefTy->getPointeeType();
689
690
  //   -- the handler is of type cv T or cv T& and E and T are the same type
691
226
  if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
692
89
    return true;
693
694
  // FIXME: ObjC pointer types?
695
137
  if (HandlerType->isPointerType() || 
HandlerType->isMemberPointerType()77
) {
696
62
    if (RefTy && 
(16
!HandlerType.isConstQualified()16
||
697
16
                  
HandlerType.isVolatileQualified()12
))
698
6
      return false;
699
700
    // -- the handler is of type cv T or const T& where T is a pointer or
701
    //    pointer to member type and E is std::nullptr_t
702
56
    if (ExceptionType->isNullPtrType())
703
8
      return true;
704
705
    // -- the handler is of type cv T or const T& where T is a pointer or
706
    //    pointer to member type and E is a pointer or pointer to member type
707
    //    that can be converted to T by one or more of
708
    //    -- a qualification conversion
709
    //    -- a function pointer conversion
710
48
    bool LifetimeConv;
711
48
    QualType Result;
712
    // FIXME: Should we treat the exception as catchable if a lifetime
713
    // conversion is required?
714
48
    if (IsQualificationConversion(ExceptionType, HandlerType, false,
715
48
                                  LifetimeConv) ||
716
48
        
IsFunctionConversion(ExceptionType, HandlerType, Result)43
)
717
7
      return true;
718
719
    //    -- a standard pointer conversion [...]
720
41
    if (!ExceptionType->isPointerType() || 
!HandlerType->isPointerType()37
)
721
4
      return false;
722
723
    // Handle the "qualification conversion" portion.
724
37
    Qualifiers EQuals, HQuals;
725
37
    ExceptionType = Context.getUnqualifiedArrayType(
726
37
        ExceptionType->getPointeeType(), EQuals);
727
37
    HandlerType = Context.getUnqualifiedArrayType(
728
37
        HandlerType->getPointeeType(), HQuals);
729
37
    if (!HQuals.compatiblyIncludes(EQuals))
730
3
      return false;
731
732
34
    if (HandlerType->isVoidType() && 
ExceptionType->isObjectType()5
)
733
5
      return true;
734
735
    // The only remaining case is a derived-to-base conversion.
736
34
  }
737
738
  //   -- the handler is of type cg T or cv T& and T is an unambiguous public
739
  //      base class of E
740
104
  if (!ExceptionType->isRecordType() || 
!HandlerType->isRecordType()71
)
741
36
    return false;
742
68
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
743
68
                     /*DetectVirtual=*/false);
744
68
  if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
745
68
      
Paths.isAmbiguous(Context.getCanonicalType(HandlerType))56
)
746
22
    return false;
747
748
  // Do this check from a context without privileges.
749
46
  switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
750
46
                               Paths.front(),
751
46
                               /*Diagnostic*/ 0,
752
46
                               /*ForceCheck*/ true,
753
46
                               /*ForceUnprivileged*/ true)) {
754
31
  case AR_accessible: return true;
755
15
  case AR_inaccessible: return false;
756
0
  case AR_dependent:
757
0
    llvm_unreachable("access check dependent for unprivileged context");
758
0
  case AR_delayed:
759
0
    llvm_unreachable("access check delayed in non-declaration");
760
46
  }
761
0
  llvm_unreachable("unexpected access check result");
762
0
}
763
764
/// CheckExceptionSpecSubset - Check whether the second function type's
765
/// exception specification is a subset (or equivalent) of the first function
766
/// type. This is used by override and pointer assignment checks.
767
bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
768
                                    const PartialDiagnostic &NestedDiagID,
769
                                    const PartialDiagnostic &NoteID,
770
                                    const PartialDiagnostic &NoThrowDiagID,
771
                                    const FunctionProtoType *Superset,
772
                                    SourceLocation SuperLoc,
773
                                    const FunctionProtoType *Subset,
774
46.9k
                                    SourceLocation SubLoc) {
775
776
  // Just auto-succeed under -fno-exceptions.
777
46.9k
  if (!getLangOpts().CXXExceptions)
778
8.16k
    return false;
779
780
  // FIXME: As usual, we could be more specific in our error messages, but
781
  // that better waits until we've got types with source locations.
782
783
38.7k
  if (!SubLoc.isValid())
784
10.6k
    SubLoc = SuperLoc;
785
786
  // Resolve the exception specifications, if needed.
787
38.7k
  Superset = ResolveExceptionSpec(SuperLoc, Superset);
788
38.7k
  if (!Superset)
789
0
    return false;
790
38.7k
  Subset = ResolveExceptionSpec(SubLoc, Subset);
791
38.7k
  if (!Subset)
792
0
    return false;
793
794
38.7k
  ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
795
38.7k
  ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
796
38.7k
  assert(!isUnresolvedExceptionSpec(SuperEST) &&
797
38.7k
         !isUnresolvedExceptionSpec(SubEST) &&
798
38.7k
         "Shouldn't see unknown exception specifications here");
799
800
  // If there are dependent noexcept specs, assume everything is fine. Unlike
801
  // with the equivalency check, this is safe in this case, because we don't
802
  // want to merge declarations. Checks after instantiation will catch any
803
  // omissions we make here.
804
38.7k
  if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
805
1
    return false;
806
807
38.7k
  CanThrowResult SuperCanThrow = Superset->canThrow();
808
38.7k
  CanThrowResult SubCanThrow = Subset->canThrow();
809
810
  // If the superset contains everything or the subset contains nothing, we're
811
  // done.
812
38.7k
  if ((SuperCanThrow == CT_Can && 
SuperEST != EST_Dynamic17.9k
) ||
813
38.7k
      
SubCanThrow == CT_Cannot20.9k
)
814
38.5k
    return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
815
38.5k
                                   Subset, SubLoc);
816
817
  // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
818
  // some cases.
819
196
  if (NoThrowDiagID.getDiagID() != 0 && 
SubCanThrow == CT_Can98
&&
820
196
      
SuperCanThrow == CT_Cannot98
&&
SuperEST == EST_NoThrow11
) {
821
2
    Diag(SubLoc, NoThrowDiagID);
822
2
    if (NoteID.getDiagID() != 0)
823
2
      Diag(SuperLoc, NoteID);
824
2
    return true;
825
2
  }
826
827
  // If the subset contains everything or the superset contains nothing, we've
828
  // failed.
829
194
  if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
830
194
      
SuperCanThrow == CT_Cannot177
) {
831
52
    Diag(SubLoc, DiagID);
832
52
    if (NoteID.getDiagID() != 0)
833
11
      Diag(SuperLoc, NoteID);
834
52
    return true;
835
52
  }
836
837
142
  assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
838
142
         "Exception spec subset: non-dynamic case slipped through.");
839
840
  // Neither contains everything or nothing. Do a proper comparison.
841
163
  for (QualType SubI : Subset->exceptions()) {
842
163
    if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
843
23
      SubI = RefTy->getPointeeType();
844
845
    // Make sure it's in the superset.
846
163
    bool Contained = false;
847
176
    for (QualType SuperI : Superset->exceptions()) {
848
      // [except.spec]p5:
849
      //   the target entity shall allow at least the exceptions allowed by the
850
      //   source
851
      //
852
      // We interpret this as meaning that a handler for some target type would
853
      // catch an exception of each source type.
854
176
      if (handlerCanCatch(SuperI, SubI)) {
855
112
        Contained = true;
856
112
        break;
857
112
      }
858
176
    }
859
163
    if (!Contained) {
860
51
      Diag(SubLoc, DiagID);
861
51
      if (NoteID.getDiagID() != 0)
862
33
        Diag(SuperLoc, NoteID);
863
51
      return true;
864
51
    }
865
163
  }
866
  // We've run half the gauntlet.
867
91
  return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
868
91
                                 Subset, SubLoc);
869
142
}
870
871
static bool
872
CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
873
                            const PartialDiagnostic &NoteID, QualType Target,
874
                            SourceLocation TargetLoc, QualType Source,
875
57.5k
                            SourceLocation SourceLoc) {
876
57.5k
  const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
877
57.5k
  if (!TFunc)
878
57.5k
    return false;
879
9
  const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
880
9
  if (!SFunc)
881
0
    return false;
882
883
9
  return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
884
9
                                        SFunc, SourceLoc);
885
9
}
886
887
/// CheckParamExceptionSpec - Check if the parameter and return types of the
888
/// two functions have equivalent exception specs. This is part of the
889
/// assignment and override compatibility check. We do not check the parameters
890
/// of parameter function pointers recursively, as no sane programmer would
891
/// even be able to write such a function type.
892
bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
893
                                   const PartialDiagnostic &NoteID,
894
                                   const FunctionProtoType *Target,
895
                                   SourceLocation TargetLoc,
896
                                   const FunctionProtoType *Source,
897
38.6k
                                   SourceLocation SourceLoc) {
898
38.6k
  auto RetDiag = DiagID;
899
38.6k
  RetDiag << 0;
900
38.6k
  if (CheckSpecForTypesEquivalent(
901
38.6k
          *this, RetDiag, PDiag(),
902
38.6k
          Target->getReturnType(), TargetLoc, Source->getReturnType(),
903
38.6k
          SourceLoc))
904
2
    return true;
905
906
  // We shouldn't even be testing this unless the arguments are otherwise
907
  // compatible.
908
38.6k
  assert(Target->getNumParams() == Source->getNumParams() &&
909
38.6k
         "Functions have different argument counts.");
910
57.5k
  for (unsigned i = 0, E = Target->getNumParams(); i != E; 
++i18.9k
) {
911
18.9k
    auto ParamDiag = DiagID;
912
18.9k
    ParamDiag << 1;
913
18.9k
    if (CheckSpecForTypesEquivalent(
914
18.9k
            *this, ParamDiag, PDiag(),
915
18.9k
            Target->getParamType(i), TargetLoc, Source->getParamType(i),
916
18.9k
            SourceLoc))
917
2
      return true;
918
18.9k
  }
919
38.6k
  return false;
920
38.6k
}
921
922
4.76M
bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
923
  // First we check for applicability.
924
  // Target type must be a function, function pointer or function reference.
925
4.76M
  const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
926
4.76M
  if (!ToFunc || 
ToFunc->hasDependentExceptionSpec()15.7k
)
927
4.75M
    return false;
928
929
  // SourceType must be a function or function pointer.
930
15.7k
  const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
931
15.7k
  if (!FromFunc || 
FromFunc->hasDependentExceptionSpec()15.6k
)
932
142
    return false;
933
934
15.6k
  unsigned DiagID = diag::err_incompatible_exception_specs;
935
15.6k
  unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
936
  // This is not an error in C++17 onwards, unless the noexceptness doesn't
937
  // match, but in that case we have a full-on type mismatch, not just a
938
  // type sugar mismatch.
939
15.6k
  if (getLangOpts().CPlusPlus17) {
940
1.02k
    DiagID = diag::warn_incompatible_exception_specs;
941
1.02k
    NestedDiagID = diag::warn_deep_exception_specs_differ;
942
1.02k
  }
943
944
  // Now we've got the correct types on both sides, check their compatibility.
945
  // This means that the source of the conversion can only throw a subset of
946
  // the exceptions of the target, and any exception specs on arguments or
947
  // return types must be equivalent.
948
  //
949
  // FIXME: If there is a nested dependent exception specification, we should
950
  // not be checking it here. This is fine:
951
  //   template<typename T> void f() {
952
  //     void (*p)(void (*) throw(T));
953
  //     void (*q)(void (*) throw(int)) = p;
954
  //   }
955
  // ... because it might be instantiated with T=int.
956
15.6k
  return CheckExceptionSpecSubset(
957
15.6k
             PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc,
958
15.6k
             From->getSourceRange().getBegin(), FromFunc, SourceLocation()) &&
959
15.6k
         
!getLangOpts().CPlusPlus1763
;
960
15.7k
}
961
962
bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
963
40.1k
                                                const CXXMethodDecl *Old) {
964
  // If the new exception specification hasn't been parsed yet, skip the check.
965
  // We'll get called again once it's been parsed.
966
40.1k
  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
967
40.1k
      EST_Unparsed)
968
253
    return false;
969
970
  // Don't check uninstantiated template destructors at all. We can only
971
  // synthesize correct specs after the template is instantiated.
972
39.8k
  if (isa<CXXDestructorDecl>(New) && 
New->getParent()->isDependentType()23.7k
)
973
832
    return false;
974
975
  // If the old exception specification hasn't been parsed yet, or the new
976
  // exception specification can't be computed yet, remember that we need to
977
  // perform this check when we get to the end of the outermost
978
  // lexically-surrounding class.
979
39.0k
  if (exceptionSpecNotKnownYet(Old) || 
exceptionSpecNotKnownYet(New)39.0k
) {
980
7.79k
    DelayedOverridingExceptionSpecChecks.push_back({New, Old});
981
7.79k
    return false;
982
7.79k
  }
983
984
31.2k
  unsigned DiagID = diag::err_override_exception_spec;
985
31.2k
  if (getLangOpts().MSVCCompat)
986
96
    DiagID = diag::ext_override_exception_spec;
987
31.2k
  return CheckExceptionSpecSubset(PDiag(DiagID),
988
31.2k
                                  PDiag(diag::err_deep_exception_specs_differ),
989
31.2k
                                  PDiag(diag::note_overridden_virtual_function),
990
31.2k
                                  PDiag(diag::ext_override_exception_spec),
991
31.2k
                                  Old->getType()->castAs<FunctionProtoType>(),
992
31.2k
                                  Old->getLocation(),
993
31.2k
                                  New->getType()->castAs<FunctionProtoType>(),
994
31.2k
                                  New->getLocation());
995
39.0k
}
996
997
45.6k
static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) {
998
45.6k
  CanThrowResult R = CT_Cannot;
999
64.4k
  for (const Stmt *SubStmt : S->children()) {
1000
64.4k
    if (!SubStmt)
1001
5
      continue;
1002
64.4k
    R = mergeCanThrow(R, Self.canThrow(SubStmt));
1003
64.4k
    if (R == CT_Can)
1004
829
      break;
1005
64.4k
  }
1006
45.6k
  return R;
1007
45.6k
}
1008
1009
CanThrowResult Sema::canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1010
8.01k
                                    SourceLocation Loc) {
1011
  // As an extension, we assume that __attribute__((nothrow)) functions don't
1012
  // throw.
1013
8.01k
  if (D && 
isa<FunctionDecl>(D)7.83k
&&
D->hasAttr<NoThrowAttr>()7.79k
)
1014
3
    return CT_Cannot;
1015
1016
8.00k
  QualType T;
1017
1018
  // In C++1z, just look at the function type of the callee.
1019
8.00k
  if (S.getLangOpts().CPlusPlus17 && 
E3.12k
&&
isa<CallExpr>(E)3.11k
) {
1020
2.81k
    E = cast<CallExpr>(E)->getCallee();
1021
2.81k
    T = E->getType();
1022
2.81k
    if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1023
      // Sadly we don't preserve the actual type as part of the "bound member"
1024
      // placeholder, so we need to reconstruct it.
1025
2.53k
      E = E->IgnoreParenImpCasts();
1026
1027
      // Could be a call to a pointer-to-member or a plain member access.
1028
2.53k
      if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1029
0
        assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1030
0
        T = Op->getRHS()->getType()
1031
0
              ->castAs<MemberPointerType>()->getPointeeType();
1032
2.53k
      } else {
1033
2.53k
        T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1034
2.53k
      }
1035
2.53k
    }
1036
5.19k
  } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1037
5.00k
    T = VD->getType();
1038
184
  else
1039
    // If we have no clue what we're calling, assume the worst.
1040
184
    return CT_Can;
1041
1042
7.82k
  const FunctionProtoType *FT;
1043
7.82k
  if ((FT = T->getAs<FunctionProtoType>())) {
1044
7.51k
  } else 
if (const PointerType *306
PT306
= T->getAs<PointerType>())
1045
296
    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1046
10
  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1047
5
    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1048
5
  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1049
4
    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1050
1
  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1051
0
    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1052
1053
7.82k
  if (!FT)
1054
5
    return CT_Can;
1055
1056
7.81k
  if (Loc.isValid() || (Loc.isInvalid() && E))
1057
7.81k
    FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : 
Loc0
, FT);
1058
7.81k
  if (!FT)
1059
0
    return CT_Can;
1060
1061
7.81k
  return FT->canThrow();
1062
7.81k
}
1063
1064
94
static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) {
1065
94
  CanThrowResult CT = CT_Cannot;
1066
1067
  // Initialization might throw.
1068
94
  if (!VD->isUsableInConstantExpressions(Self.Context))
1069
94
    if (const Expr *Init = VD->getInit())
1070
94
      CT = mergeCanThrow(CT, Self.canThrow(Init));
1071
1072
  // Destructor might throw.
1073
94
  if (VD->needsDestruction(Self.Context) == QualType::DK_cxx_destructor) {
1074
0
    if (auto *RD =
1075
0
            VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
1076
0
      if (auto *Dtor = RD->getDestructor()) {
1077
0
        CT = mergeCanThrow(
1078
0
            CT, Sema::canCalleeThrow(Self, nullptr, Dtor, VD->getLocation()));
1079
0
      }
1080
0
    }
1081
0
  }
1082
1083
  // If this is a decomposition declaration, bindings might throw.
1084
94
  if (auto *DD = dyn_cast<DecompositionDecl>(VD))
1085
0
    for (auto *B : DD->bindings())
1086
0
      if (auto *HD = B->getHoldingVar())
1087
0
        CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD));
1088
1089
94
  return CT;
1090
94
}
1091
1092
8
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1093
8
  if (DC->isTypeDependent())
1094
0
    return CT_Dependent;
1095
1096
8
  if (!DC->getTypeAsWritten()->isReferenceType())
1097
4
    return CT_Cannot;
1098
1099
4
  if (DC->getSubExpr()->isTypeDependent())
1100
1
    return CT_Dependent;
1101
1102
3
  return DC->getCastKind() == clang::CK_Dynamic? 
CT_Can1
:
CT_Cannot2
;
1103
4
}
1104
1105
11
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1106
11
  if (DC->isTypeOperand())
1107
1
    return CT_Cannot;
1108
1109
10
  Expr *Op = DC->getExprOperand();
1110
10
  if (Op->isTypeDependent())
1111
1
    return CT_Dependent;
1112
1113
9
  const RecordType *RT = Op->getType()->getAs<RecordType>();
1114
9
  if (!RT)
1115
2
    return CT_Cannot;
1116
1117
7
  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1118
3
    return CT_Cannot;
1119
1120
4
  if (Op->Classify(S.Context).isPRValue())
1121
0
    return CT_Cannot;
1122
1123
4
  return CT_Can;
1124
4
}
1125
1126
84.2k
CanThrowResult Sema::canThrow(const Stmt *S) {
1127
  // C++ [expr.unary.noexcept]p3:
1128
  //   [Can throw] if in a potentially-evaluated context the expression would
1129
  //   contain:
1130
84.2k
  switch (S->getStmtClass()) {
1131
3
  case Expr::ConstantExprClass:
1132
3
    return canThrow(cast<ConstantExpr>(S)->getSubExpr());
1133
1134
12
  case Expr::CXXThrowExprClass:
1135
    //   - a potentially evaluated throw-expression
1136
12
    return CT_Can;
1137
1138
8
  case Expr::CXXDynamicCastExprClass: {
1139
    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1140
    //     where T is a reference type, that requires a run-time check
1141
8
    auto *CE = cast<CXXDynamicCastExpr>(S);
1142
    // FIXME: Properly determine whether a variably-modified type can throw.
1143
8
    if (CE->getType()->isVariablyModifiedType())
1144
0
      return CT_Can;
1145
8
    CanThrowResult CT = canDynamicCastThrow(CE);
1146
8
    if (CT == CT_Can)
1147
1
      return CT;
1148
7
    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1149
8
  }
1150
1151
11
  case Expr::CXXTypeidExprClass:
1152
    //   - a potentially evaluated typeid expression applied to a glvalue
1153
    //     expression whose type is a polymorphic class type
1154
11
    return canTypeidThrow(*this, cast<CXXTypeidExpr>(S));
1155
1156
    //   - a potentially evaluated call to a function, member function, function
1157
    //     pointer, or member function pointer that does not have a non-throwing
1158
    //     exception-specification
1159
15.9k
  case Expr::CallExprClass:
1160
16.1k
  case Expr::CXXMemberCallExprClass:
1161
16.8k
  case Expr::CXXOperatorCallExprClass:
1162
16.8k
  case Expr::UserDefinedLiteralClass: {
1163
16.8k
    const CallExpr *CE = cast<CallExpr>(S);
1164
16.8k
    CanThrowResult CT;
1165
16.8k
    if (CE->isTypeDependent())
1166
15.2k
      CT = CT_Dependent;
1167
1.54k
    else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1168
1
      CT = CT_Cannot;
1169
1.54k
    else
1170
1.54k
      CT = canCalleeThrow(*this, CE, CE->getCalleeDecl());
1171
16.8k
    if (CT == CT_Can)
1172
737
      return CT;
1173
16.0k
    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1174
16.8k
  }
1175
1176
1.49k
  case Expr::CXXConstructExprClass:
1177
2.54k
  case Expr::CXXTemporaryObjectExprClass: {
1178
2.54k
    auto *CE = cast<CXXConstructExpr>(S);
1179
    // FIXME: Properly determine whether a variably-modified type can throw.
1180
2.54k
    if (CE->getType()->isVariablyModifiedType())
1181
0
      return CT_Can;
1182
2.54k
    CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor());
1183
2.54k
    if (CT == CT_Can)
1184
198
      return CT;
1185
2.34k
    return mergeCanThrow(CT, canSubStmtsThrow(*this, CE));
1186
2.54k
  }
1187
1188
0
  case Expr::CXXInheritedCtorInitExprClass: {
1189
0
    auto *ICIE = cast<CXXInheritedCtorInitExpr>(S);
1190
0
    return canCalleeThrow(*this, ICIE, ICIE->getConstructor());
1191
2.54k
  }
1192
1193
12
  case Expr::LambdaExprClass: {
1194
12
    const LambdaExpr *Lambda = cast<LambdaExpr>(S);
1195
12
    CanThrowResult CT = CT_Cannot;
1196
12
    for (LambdaExpr::const_capture_init_iterator
1197
12
             Cap = Lambda->capture_init_begin(),
1198
12
             CapEnd = Lambda->capture_init_end();
1199
12
         Cap != CapEnd; 
++Cap0
)
1200
0
      CT = mergeCanThrow(CT, canThrow(*Cap));
1201
12
    return CT;
1202
2.54k
  }
1203
1204
29
  case Expr::CXXNewExprClass: {
1205
29
    auto *NE = cast<CXXNewExpr>(S);
1206
29
    CanThrowResult CT;
1207
29
    if (NE->isTypeDependent())
1208
4
      CT = CT_Dependent;
1209
25
    else
1210
25
      CT = canCalleeThrow(*this, NE, NE->getOperatorNew());
1211
29
    if (CT == CT_Can)
1212
4
      return CT;
1213
25
    return mergeCanThrow(CT, canSubStmtsThrow(*this, NE));
1214
29
  }
1215
1216
16
  case Expr::CXXDeleteExprClass: {
1217
16
    auto *DE = cast<CXXDeleteExpr>(S);
1218
16
    CanThrowResult CT;
1219
16
    QualType DTy = DE->getDestroyedType();
1220
16
    if (DTy.isNull() || 
DTy->isDependentType()15
) {
1221
2
      CT = CT_Dependent;
1222
14
    } else {
1223
14
      CT = canCalleeThrow(*this, DE, DE->getOperatorDelete());
1224
14
      if (const RecordType *RT = DTy->getAs<RecordType>()) {
1225
12
        const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1226
12
        const CXXDestructorDecl *DD = RD->getDestructor();
1227
12
        if (DD)
1228
11
          CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, DD));
1229
12
      }
1230
14
      if (CT == CT_Can)
1231
6
        return CT;
1232
14
    }
1233
10
    return mergeCanThrow(CT, canSubStmtsThrow(*this, DE));
1234
16
  }
1235
1236
644
  case Expr::CXXBindTemporaryExprClass: {
1237
644
    auto *BTE = cast<CXXBindTemporaryExpr>(S);
1238
    // The bound temporary has to be destroyed again, which might throw.
1239
644
    CanThrowResult CT =
1240
644
        canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor());
1241
644
    if (CT == CT_Can)
1242
11
      return CT;
1243
633
    return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE));
1244
644
  }
1245
1246
15
  case Expr::PseudoObjectExprClass: {
1247
15
    auto *POE = cast<PseudoObjectExpr>(S);
1248
15
    CanThrowResult CT = CT_Cannot;
1249
45
    for (const Expr *E : POE->semantics()) {
1250
45
      CT = mergeCanThrow(CT, canThrow(E));
1251
45
      if (CT == CT_Can)
1252
13
        break;
1253
45
    }
1254
15
    return CT;
1255
644
  }
1256
1257
    // ObjC message sends are like function calls, but never have exception
1258
    // specs.
1259
1
  case Expr::ObjCMessageExprClass:
1260
1
  case Expr::ObjCPropertyRefExprClass:
1261
1
  case Expr::ObjCSubscriptRefExprClass:
1262
1
    return CT_Can;
1263
1264
    // All the ObjC literals that are implemented as calls are
1265
    // potentially throwing unless we decide to close off that
1266
    // possibility.
1267
0
  case Expr::ObjCArrayLiteralClass:
1268
0
  case Expr::ObjCDictionaryLiteralClass:
1269
0
  case Expr::ObjCBoxedExprClass:
1270
0
    return CT_Can;
1271
1272
    // Many other things have subexpressions, so we have to test those.
1273
    // Some are simple:
1274
0
  case Expr::CoawaitExprClass:
1275
19
  case Expr::ConditionalOperatorClass:
1276
19
  case Expr::CoyieldExprClass:
1277
74
  case Expr::CXXRewrittenBinaryOperatorClass:
1278
78
  case Expr::CXXStdInitializerListExprClass:
1279
78
  case Expr::DesignatedInitExprClass:
1280
78
  case Expr::DesignatedInitUpdateExprClass:
1281
217
  case Expr::ExprWithCleanupsClass:
1282
217
  case Expr::ExtVectorElementExprClass:
1283
737
  case Expr::InitListExprClass:
1284
737
  case Expr::ArrayInitLoopExprClass:
1285
1.08k
  case Expr::MemberExprClass:
1286
1.08k
  case Expr::ObjCIsaExprClass:
1287
1.08k
  case Expr::ObjCIvarRefExprClass:
1288
5.83k
  case Expr::ParenExprClass:
1289
5.83k
  case Expr::ParenListExprClass:
1290
5.83k
  case Expr::ShuffleVectorExprClass:
1291
5.84k
  case Expr::StmtExprClass:
1292
5.84k
  case Expr::ConvertVectorExprClass:
1293
5.84k
  case Expr::VAArgExprClass:
1294
5.84k
    return canSubStmtsThrow(*this, S);
1295
1296
1
  case Expr::CompoundLiteralExprClass:
1297
1
  case Expr::CXXConstCastExprClass:
1298
1
  case Expr::CXXAddrspaceCastExprClass:
1299
3
  case Expr::CXXReinterpretCastExprClass:
1300
3
  case Expr::BuiltinBitCastExprClass:
1301
      // FIXME: Properly determine whether a variably-modified type can throw.
1302
3
    if (cast<Expr>(S)->getType()->isVariablyModifiedType())
1303
2
      return CT_Can;
1304
1
    return canSubStmtsThrow(*this, S);
1305
1306
    // Some might be dependent for other reasons.
1307
17
  case Expr::ArraySubscriptExprClass:
1308
17
  case Expr::MatrixSubscriptExprClass:
1309
17
  case Expr::OMPArraySectionExprClass:
1310
17
  case Expr::OMPArrayShapingExprClass:
1311
17
  case Expr::OMPIteratorExprClass:
1312
7.22k
  case Expr::BinaryOperatorClass:
1313
7.22k
  case Expr::DependentCoawaitExprClass:
1314
7.22k
  case Expr::CompoundAssignOperatorClass:
1315
7.23k
  case Expr::CStyleCastExprClass:
1316
12.0k
  case Expr::CXXStaticCastExprClass:
1317
12.1k
  case Expr::CXXFunctionalCastExprClass:
1318
17.1k
  case Expr::ImplicitCastExprClass:
1319
17.2k
  case Expr::MaterializeTemporaryExprClass:
1320
20.1k
  case Expr::UnaryOperatorClass: {
1321
    // FIXME: Properly determine whether a variably-modified type can throw.
1322
20.1k
    if (auto *CE = dyn_cast<CastExpr>(S))
1323
9.92k
      if (CE->getType()->isVariablyModifiedType())
1324
3
        return CT_Can;
1325
20.1k
    CanThrowResult CT =
1326
20.1k
        cast<Expr>(S)->isTypeDependent() ? 
CT_Dependent13.4k
:
CT_Cannot6.72k
;
1327
20.1k
    return mergeCanThrow(CT, canSubStmtsThrow(*this, S));
1328
20.1k
  }
1329
1330
28
  case Expr::CXXDefaultArgExprClass:
1331
28
    return canThrow(cast<CXXDefaultArgExpr>(S)->getExpr());
1332
1333
162
  case Expr::CXXDefaultInitExprClass:
1334
162
    return canThrow(cast<CXXDefaultInitExpr>(S)->getExpr());
1335
1336
0
  case Expr::ChooseExprClass: {
1337
0
    auto *CE = cast<ChooseExpr>(S);
1338
0
    if (CE->isTypeDependent() || CE->isValueDependent())
1339
0
      return CT_Dependent;
1340
0
    return canThrow(CE->getChosenSubExpr());
1341
0
  }
1342
1343
0
  case Expr::GenericSelectionExprClass:
1344
0
    if (cast<GenericSelectionExpr>(S)->isResultDependent())
1345
0
      return CT_Dependent;
1346
0
    return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr());
1347
1348
    // Some expressions are always dependent.
1349
3.04k
  case Expr::CXXDependentScopeMemberExprClass:
1350
3.09k
  case Expr::CXXUnresolvedConstructExprClass:
1351
3.09k
  case Expr::DependentScopeDeclRefExprClass:
1352
3.09k
  case Expr::CXXFoldExprClass:
1353
3.11k
  case Expr::RecoveryExprClass:
1354
3.11k
    return CT_Dependent;
1355
1356
0
  case Expr::AsTypeExprClass:
1357
0
  case Expr::BinaryConditionalOperatorClass:
1358
9
  case Expr::BlockExprClass:
1359
9
  case Expr::CUDAKernelCallExprClass:
1360
13.6k
  case Expr::DeclRefExprClass:
1361
13.6k
  case Expr::ObjCBridgedCastExprClass:
1362
13.6k
  case Expr::ObjCIndirectCopyRestoreExprClass:
1363
13.6k
  case Expr::ObjCProtocolExprClass:
1364
13.6k
  case Expr::ObjCSelectorExprClass:
1365
13.6k
  case Expr::ObjCAvailabilityCheckExprClass:
1366
13.6k
  case Expr::OffsetOfExprClass:
1367
18.3k
  case Expr::PackExpansionExprClass:
1368
18.3k
  case Expr::SubstNonTypeTemplateParmExprClass:
1369
18.3k
  case Expr::SubstNonTypeTemplateParmPackExprClass:
1370
18.3k
  case Expr::FunctionParmPackExprClass:
1371
18.4k
  case Expr::UnaryExprOrTypeTraitExprClass:
1372
26.3k
  case Expr::UnresolvedLookupExprClass:
1373
26.3k
  case Expr::UnresolvedMemberExprClass:
1374
26.3k
  case Expr::TypoExprClass:
1375
    // FIXME: Many of the above can throw.
1376
26.3k
    return CT_Cannot;
1377
1378
0
  case Expr::AddrLabelExprClass:
1379
0
  case Expr::ArrayTypeTraitExprClass:
1380
0
  case Expr::AtomicExprClass:
1381
0
  case Expr::TypeTraitExprClass:
1382
38
  case Expr::CXXBoolLiteralExprClass:
1383
38
  case Expr::CXXNoexceptExprClass:
1384
80
  case Expr::CXXNullPtrLiteralExprClass:
1385
554
  case Expr::CXXPseudoDestructorExprClass:
1386
559
  case Expr::CXXScalarValueInitExprClass:
1387
752
  case Expr::CXXThisExprClass:
1388
752
  case Expr::CXXUuidofExprClass:
1389
771
  case Expr::CharacterLiteralClass:
1390
771
  case Expr::ExpressionTraitExprClass:
1391
832
  case Expr::FloatingLiteralClass:
1392
832
  case Expr::GNUNullExprClass:
1393
832
  case Expr::ImaginaryLiteralClass:
1394
1.11k
  case Expr::ImplicitValueInitExprClass:
1395
2.23k
  case Expr::IntegerLiteralClass:
1396
2.23k
  case Expr::FixedPointLiteralClass:
1397
2.23k
  case Expr::ArrayInitIndexExprClass:
1398
2.23k
  case Expr::NoInitExprClass:
1399
2.23k
  case Expr::ObjCEncodeExprClass:
1400
2.23k
  case Expr::ObjCStringLiteralClass:
1401
2.23k
  case Expr::ObjCBoolLiteralExprClass:
1402
7.69k
  case Expr::OpaqueValueExprClass:
1403
7.69k
  case Expr::PredefinedExprClass:
1404
7.69k
  case Expr::SizeOfPackExprClass:
1405
7.70k
  case Expr::StringLiteralClass:
1406
7.73k
  case Expr::SourceLocExprClass:
1407
7.73k
  case Expr::ConceptSpecializationExprClass:
1408
7.73k
  case Expr::RequiresExprClass:
1409
    // These expressions can never throw.
1410
7.73k
    return CT_Cannot;
1411
1412
0
  case Expr::MSPropertyRefExprClass:
1413
0
  case Expr::MSPropertySubscriptExprClass:
1414
0
    llvm_unreachable("Invalid class for expression");
1415
1416
    // Most statements can throw if any substatement can throw.
1417
0
  case Stmt::AttributedStmtClass:
1418
0
  case Stmt::BreakStmtClass:
1419
0
  case Stmt::CapturedStmtClass:
1420
0
  case Stmt::CaseStmtClass:
1421
248
  case Stmt::CompoundStmtClass:
1422
248
  case Stmt::ContinueStmtClass:
1423
248
  case Stmt::CoreturnStmtClass:
1424
248
  case Stmt::CoroutineBodyStmtClass:
1425
248
  case Stmt::CXXCatchStmtClass:
1426
248
  case Stmt::CXXForRangeStmtClass:
1427
248
  case Stmt::DefaultStmtClass:
1428
248
  case Stmt::DoStmtClass:
1429
253
  case Stmt::ForStmtClass:
1430
253
  case Stmt::GCCAsmStmtClass:
1431
253
  case Stmt::GotoStmtClass:
1432
253
  case Stmt::IndirectGotoStmtClass:
1433
253
  case Stmt::LabelStmtClass:
1434
253
  case Stmt::MSAsmStmtClass:
1435
253
  case Stmt::MSDependentExistsStmtClass:
1436
253
  case Stmt::NullStmtClass:
1437
253
  case Stmt::ObjCAtCatchStmtClass:
1438
253
  case Stmt::ObjCAtFinallyStmtClass:
1439
253
  case Stmt::ObjCAtSynchronizedStmtClass:
1440
253
  case Stmt::ObjCAutoreleasePoolStmtClass:
1441
253
  case Stmt::ObjCForCollectionStmtClass:
1442
253
  case Stmt::OMPAtomicDirectiveClass:
1443
253
  case Stmt::OMPBarrierDirectiveClass:
1444
253
  case Stmt::OMPCancelDirectiveClass:
1445
253
  case Stmt::OMPCancellationPointDirectiveClass:
1446
253
  case Stmt::OMPCriticalDirectiveClass:
1447
253
  case Stmt::OMPDistributeDirectiveClass:
1448
253
  case Stmt::OMPDistributeParallelForDirectiveClass:
1449
253
  case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1450
253
  case Stmt::OMPDistributeSimdDirectiveClass:
1451
253
  case Stmt::OMPFlushDirectiveClass:
1452
253
  case Stmt::OMPDepobjDirectiveClass:
1453
253
  case Stmt::OMPScanDirectiveClass:
1454
253
  case Stmt::OMPForDirectiveClass:
1455
253
  case Stmt::OMPForSimdDirectiveClass:
1456
253
  case Stmt::OMPMasterDirectiveClass:
1457
253
  case Stmt::OMPMasterTaskLoopDirectiveClass:
1458
253
  case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1459
253
  case Stmt::OMPOrderedDirectiveClass:
1460
253
  case Stmt::OMPCanonicalLoopClass:
1461
253
  case Stmt::OMPParallelDirectiveClass:
1462
253
  case Stmt::OMPParallelForDirectiveClass:
1463
253
  case Stmt::OMPParallelForSimdDirectiveClass:
1464
253
  case Stmt::OMPParallelMasterDirectiveClass:
1465
253
  case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1466
253
  case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1467
253
  case Stmt::OMPParallelSectionsDirectiveClass:
1468
253
  case Stmt::OMPSectionDirectiveClass:
1469
253
  case Stmt::OMPSectionsDirectiveClass:
1470
253
  case Stmt::OMPSimdDirectiveClass:
1471
253
  case Stmt::OMPTileDirectiveClass:
1472
253
  case Stmt::OMPUnrollDirectiveClass:
1473
253
  case Stmt::OMPSingleDirectiveClass:
1474
253
  case Stmt::OMPTargetDataDirectiveClass:
1475
253
  case Stmt::OMPTargetDirectiveClass:
1476
253
  case Stmt::OMPTargetEnterDataDirectiveClass:
1477
253
  case Stmt::OMPTargetExitDataDirectiveClass:
1478
253
  case Stmt::OMPTargetParallelDirectiveClass:
1479
253
  case Stmt::OMPTargetParallelForDirectiveClass:
1480
253
  case Stmt::OMPTargetParallelForSimdDirectiveClass:
1481
253
  case Stmt::OMPTargetSimdDirectiveClass:
1482
253
  case Stmt::OMPTargetTeamsDirectiveClass:
1483
253
  case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1484
253
  case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1485
253
  case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1486
253
  case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1487
253
  case Stmt::OMPTargetUpdateDirectiveClass:
1488
253
  case Stmt::OMPTaskDirectiveClass:
1489
253
  case Stmt::OMPTaskgroupDirectiveClass:
1490
253
  case Stmt::OMPTaskLoopDirectiveClass:
1491
253
  case Stmt::OMPTaskLoopSimdDirectiveClass:
1492
253
  case Stmt::OMPTaskwaitDirectiveClass:
1493
253
  case Stmt::OMPTaskyieldDirectiveClass:
1494
253
  case Stmt::OMPTeamsDirectiveClass:
1495
253
  case Stmt::OMPTeamsDistributeDirectiveClass:
1496
253
  case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1497
253
  case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1498
253
  case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1499
253
  case Stmt::OMPInteropDirectiveClass:
1500
253
  case Stmt::OMPDispatchDirectiveClass:
1501
253
  case Stmt::OMPMaskedDirectiveClass:
1502
253
  case Stmt::OMPMetaDirectiveClass:
1503
253
  case Stmt::OMPGenericLoopDirectiveClass:
1504
503
  case Stmt::ReturnStmtClass:
1505
503
  case Stmt::SEHExceptStmtClass:
1506
503
  case Stmt::SEHFinallyStmtClass:
1507
503
  case Stmt::SEHLeaveStmtClass:
1508
503
  case Stmt::SEHTryStmtClass:
1509
503
  case Stmt::SwitchStmtClass:
1510
503
  case Stmt::WhileStmtClass:
1511
503
    return canSubStmtsThrow(*this, S);
1512
1513
94
  case Stmt::DeclStmtClass: {
1514
94
    CanThrowResult CT = CT_Cannot;
1515
94
    for (const Decl *D : cast<DeclStmt>(S)->decls()) {
1516
94
      if (auto *VD = dyn_cast<VarDecl>(D))
1517
94
        CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD));
1518
1519
      // FIXME: Properly determine whether a variably-modified type can throw.
1520
94
      if (auto *TND = dyn_cast<TypedefNameDecl>(D))
1521
0
        if (TND->getUnderlyingType()->isVariablyModifiedType())
1522
0
          return CT_Can;
1523
94
      if (auto *VD = dyn_cast<ValueDecl>(D))
1524
94
        if (VD->getType()->isVariablyModifiedType())
1525
0
          return CT_Can;
1526
94
    }
1527
94
    return CT;
1528
94
  }
1529
1530
100
  case Stmt::IfStmtClass: {
1531
100
    auto *IS = cast<IfStmt>(S);
1532
100
    CanThrowResult CT = CT_Cannot;
1533
100
    if (const Stmt *Init = IS->getInit())
1534
89
      CT = mergeCanThrow(CT, canThrow(Init));
1535
100
    if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())
1536
0
      CT = mergeCanThrow(CT, canThrow(CondDS));
1537
100
    CT = mergeCanThrow(CT, canThrow(IS->getCond()));
1538
1539
    // For 'if constexpr', consider only the non-discarded case.
1540
    // FIXME: We should add a DiscardedStmt marker to the AST.
1541
100
    if (Optional<const Stmt *> Case = IS->getNondiscardedCase(Context))
1542
3
      return *Case ? 
mergeCanThrow(CT, canThrow(*Case))2
:
CT1
;
1543
1544
97
    CanThrowResult Then = canThrow(IS->getThen());
1545
97
    CanThrowResult Else = IS->getElse() ? 
canThrow(IS->getElse())0
: CT_Cannot;
1546
97
    if (Then == Else)
1547
96
      return mergeCanThrow(CT, Then);
1548
1549
    // For a dependent 'if constexpr', the result is dependent if it depends on
1550
    // the value of the condition.
1551
1
    return mergeCanThrow(CT, IS->isConstexpr() ? 
CT_Dependent0
1552
1
                                               : mergeCanThrow(Then, Else));
1553
97
  }
1554
1555
3
  case Stmt::CXXTryStmtClass: {
1556
3
    auto *TS = cast<CXXTryStmt>(S);
1557
    // try /*...*/ catch (...) { H } can throw only if H can throw.
1558
    // Any other try-catch can throw if any substatement can throw.
1559
3
    const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1);
1560
3
    if (!FinalHandler->getExceptionDecl())
1561
2
      return canThrow(FinalHandler->getHandlerBlock());
1562
1
    return canSubStmtsThrow(*this, S);
1563
3
  }
1564
1565
0
  case Stmt::ObjCAtThrowStmtClass:
1566
0
    return CT_Can;
1567
1568
0
  case Stmt::ObjCAtTryStmtClass: {
1569
0
    auto *TS = cast<ObjCAtTryStmt>(S);
1570
1571
    // @catch(...) need not be last in Objective-C. Walk backwards until we
1572
    // see one or hit the @try.
1573
0
    CanThrowResult CT = CT_Cannot;
1574
0
    if (const Stmt *Finally = TS->getFinallyStmt())
1575
0
      CT = mergeCanThrow(CT, canThrow(Finally));
1576
0
    for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {
1577
0
      const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1);
1578
0
      CT = mergeCanThrow(CT, canThrow(Catch));
1579
      // If we reach a @catch(...), no earlier exceptions can escape.
1580
0
      if (Catch->hasEllipsis())
1581
0
        return CT;
1582
0
    }
1583
1584
    // Didn't find an @catch(...). Exceptions from the @try body can escape.
1585
0
    return mergeCanThrow(CT, canThrow(TS->getTryBody()));
1586
0
  }
1587
1588
0
  case Stmt::SYCLUniqueStableNameExprClass:
1589
0
    return CT_Cannot;
1590
0
  case Stmt::NoStmtClass:
1591
0
    llvm_unreachable("Invalid class for statement");
1592
84.2k
  }
1593
0
  llvm_unreachable("Bogus StmtClass");
1594
0
}
1595
1596
} // end namespace clang