1 //===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- 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 provides Sema routines for C++ exception specification testing.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.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 {
29   if (const PointerType *PtrTy = T->getAs<PointerType>())
30     T = PtrTy->getPointeeType();
31   else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32     T = RefTy->getPointeeType();
33   else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34     T = MPTy->getPointeeType();
35   return T->getAs<FunctionProtoType>();
36 }
37 
38 /// HACK: libstdc++ has a bug where it shadows std::swap with a member
39 /// swap function then tries to call std::swap unqualified from the exception
40 /// specification of that function. This function detects whether we're in
41 /// such a case and turns off delay-parsing of exception specifications.
42 bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
43   auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44 
45   // All the problem cases are member functions named "swap" within class
46   // templates declared directly within namespace std or std::__debug or
47   // std::__profile.
48   if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
49       !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
50     return false;
51 
52   auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
53   if (!ND)
54     return false;
55 
56   bool IsInStd = ND->isStdNamespace();
57   if (!IsInStd) {
58     // This isn't a direct member of namespace std, but it might still be
59     // libstdc++'s std::__debug::array or std::__profile::array.
60     IdentifierInfo *II = ND->getIdentifier();
61     if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
62         !ND->isInStdNamespace())
63       return false;
64   }
65 
66   // Only apply this hack within a system header.
67   if (!Context.getSourceManager().isInSystemHeader(D.getLocStart()))
68     return false;
69 
70   return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
71       .Case("array", true)
72       .Case("pair", IsInStd)
73       .Case("priority_queue", IsInStd)
74       .Case("stack", IsInStd)
75       .Case("queue", IsInStd)
76       .Default(false);
77 }
78 
79 ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
80                                    Expr *NoexceptExpr,
81                                    ExceptionSpecificationType &EST) {
82   // FIXME: This is bogus, a noexcept expression is not a condition.
83   ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
84   if (Converted.isInvalid())
85     return Converted;
86 
87   if (Converted.get()->isValueDependent()) {
88     EST = EST_DependentNoexcept;
89     return Converted;
90   }
91 
92   llvm::APSInt Result;
93   Converted = VerifyIntegerConstantExpression(
94       Converted.get(), &Result,
95       diag::err_noexcept_needs_constant_expression,
96       /*AllowFold*/ false);
97   if (!Converted.isInvalid())
98     EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
99   return Converted;
100 }
101 
102 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
103 /// exception specification. Incomplete types, or pointers to incomplete types
104 /// other than void are not allowed.
105 ///
106 /// \param[in,out] T  The exception type. This will be decayed to a pointer type
107 ///                   when the input is an array or a function type.
108 bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
109   // C++11 [except.spec]p2:
110   //   A type cv T, "array of T", or "function returning T" denoted
111   //   in an exception-specification is adjusted to type T, "pointer to T", or
112   //   "pointer to function returning T", respectively.
113   //
114   // We also apply this rule in C++98.
115   if (T->isArrayType())
116     T = Context.getArrayDecayedType(T);
117   else if (T->isFunctionType())
118     T = Context.getPointerType(T);
119 
120   int Kind = 0;
121   QualType PointeeT = T;
122   if (const PointerType *PT = T->getAs<PointerType>()) {
123     PointeeT = PT->getPointeeType();
124     Kind = 1;
125 
126     // cv void* is explicitly permitted, despite being a pointer to an
127     // incomplete type.
128     if (PointeeT->isVoidType())
129       return false;
130   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
131     PointeeT = RT->getPointeeType();
132     Kind = 2;
133 
134     if (RT->isRValueReferenceType()) {
135       // C++11 [except.spec]p2:
136       //   A type denoted in an exception-specification shall not denote [...]
137       //   an rvalue reference type.
138       Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
139         << T << Range;
140       return true;
141     }
142   }
143 
144   // C++11 [except.spec]p2:
145   //   A type denoted in an exception-specification shall not denote an
146   //   incomplete type other than a class currently being defined [...].
147   //   A type denoted in an exception-specification shall not denote a
148   //   pointer or reference to an incomplete type, other than (cv) void* or a
149   //   pointer or reference to a class currently being defined.
150   // In Microsoft mode, downgrade this to a warning.
151   unsigned DiagID = diag::err_incomplete_in_exception_spec;
152   bool ReturnValueOnError = true;
153   if (getLangOpts().MicrosoftExt) {
154     DiagID = diag::ext_incomplete_in_exception_spec;
155     ReturnValueOnError = false;
156   }
157   if (!(PointeeT->isRecordType() &&
158         PointeeT->getAs<RecordType>()->isBeingDefined()) &&
159       RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
160     return ReturnValueOnError;
161 
162   return false;
163 }
164 
165 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
166 /// to member to a function with an exception specification. This means that
167 /// it is invalid to add another level of indirection.
168 bool Sema::CheckDistantExceptionSpec(QualType T) {
169   // C++17 removes this rule in favor of putting exception specifications into
170   // the type system.
171   if (getLangOpts().CPlusPlus17)
172     return false;
173 
174   if (const PointerType *PT = T->getAs<PointerType>())
175     T = PT->getPointeeType();
176   else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
177     T = PT->getPointeeType();
178   else
179     return false;
180 
181   const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
182   if (!FnT)
183     return false;
184 
185   return FnT->hasExceptionSpec();
186 }
187 
188 const FunctionProtoType *
189 Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
190   if (FPT->getExceptionSpecType() == EST_Unparsed) {
191     Diag(Loc, diag::err_exception_spec_not_parsed);
192     return nullptr;
193   }
194 
195   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
196     return FPT;
197 
198   FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
199   const FunctionProtoType *SourceFPT =
200       SourceDecl->getType()->castAs<FunctionProtoType>();
201 
202   // If the exception specification has already been resolved, just return it.
203   if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
204     return SourceFPT;
205 
206   // Compute or instantiate the exception specification now.
207   if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
208     EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
209   else
210     InstantiateExceptionSpec(Loc, SourceDecl);
211 
212   const FunctionProtoType *Proto =
213     SourceDecl->getType()->castAs<FunctionProtoType>();
214   if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
215     Diag(Loc, diag::err_exception_spec_not_parsed);
216     Proto = nullptr;
217   }
218   return Proto;
219 }
220 
221 void
222 Sema::UpdateExceptionSpec(FunctionDecl *FD,
223                           const FunctionProtoType::ExceptionSpecInfo &ESI) {
224   // If we've fully resolved the exception specification, notify listeners.
225   if (!isUnresolvedExceptionSpec(ESI.Type))
226     if (auto *Listener = getASTMutationListener())
227       Listener->ResolvedExceptionSpec(FD);
228 
229   for (FunctionDecl *Redecl : FD->redecls())
230     Context.adjustExceptionSpec(Redecl, ESI);
231 }
232 
233 static bool CheckEquivalentExceptionSpecImpl(
234     Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
235     const FunctionProtoType *Old, SourceLocation OldLoc,
236     const FunctionProtoType *New, SourceLocation NewLoc,
237     bool *MissingExceptionSpecification = nullptr,
238     bool *MissingEmptyExceptionSpecification = nullptr,
239     bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
240 
241 /// Determine whether a function has an implicitly-generated exception
242 /// specification.
243 static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
244   if (!isa<CXXDestructorDecl>(Decl) &&
245       Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
246       Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
247     return false;
248 
249   // For a function that the user didn't declare:
250   //  - if this is a destructor, its exception specification is implicit.
251   //  - if this is 'operator delete' or 'operator delete[]', the exception
252   //    specification is as-if an explicit exception specification was given
253   //    (per [basic.stc.dynamic]p2).
254   if (!Decl->getTypeSourceInfo())
255     return isa<CXXDestructorDecl>(Decl);
256 
257   const FunctionProtoType *Ty =
258     Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
259   return !Ty->hasExceptionSpec();
260 }
261 
262 bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
263   // Just completely ignore this under -fno-exceptions prior to C++17.
264   // In C++17 onwards, the exception specification is part of the type and
265   // we will diagnose mismatches anyway, so it's better to check for them here.
266   if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
267     return false;
268 
269   OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
270   bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
271   bool MissingExceptionSpecification = false;
272   bool MissingEmptyExceptionSpecification = false;
273 
274   unsigned DiagID = diag::err_mismatched_exception_spec;
275   bool ReturnValueOnError = true;
276   if (getLangOpts().MicrosoftExt) {
277     DiagID = diag::ext_mismatched_exception_spec;
278     ReturnValueOnError = false;
279   }
280 
281   // Check the types as written: they must match before any exception
282   // specification adjustment is applied.
283   if (!CheckEquivalentExceptionSpecImpl(
284         *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
285         Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
286         New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
287         &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
288         /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
289     // C++11 [except.spec]p4 [DR1492]:
290     //   If a declaration of a function has an implicit
291     //   exception-specification, other declarations of the function shall
292     //   not specify an exception-specification.
293     if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
294         hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
295       Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
296         << hasImplicitExceptionSpec(Old);
297       if (Old->getLocation().isValid())
298         Diag(Old->getLocation(), diag::note_previous_declaration);
299     }
300     return false;
301   }
302 
303   // The failure was something other than an missing exception
304   // specification; return an error, except in MS mode where this is a warning.
305   if (!MissingExceptionSpecification)
306     return ReturnValueOnError;
307 
308   const FunctionProtoType *NewProto =
309     New->getType()->castAs<FunctionProtoType>();
310 
311   // The new function declaration is only missing an empty exception
312   // specification "throw()". If the throw() specification came from a
313   // function in a system header that has C linkage, just add an empty
314   // exception specification to the "new" declaration. Note that C library
315   // implementations are permitted to add these nothrow exception
316   // specifications.
317   //
318   // Likewise if the old function is a builtin.
319   if (MissingEmptyExceptionSpecification && NewProto &&
320       (Old->getLocation().isInvalid() ||
321        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
322        Old->getBuiltinID()) &&
323       Old->isExternC()) {
324     New->setType(Context.getFunctionType(
325         NewProto->getReturnType(), NewProto->getParamTypes(),
326         NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
327     return false;
328   }
329 
330   const FunctionProtoType *OldProto =
331     Old->getType()->castAs<FunctionProtoType>();
332 
333   FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
334   if (ESI.Type == EST_Dynamic) {
335     // FIXME: What if the exceptions are described in terms of the old
336     // prototype's parameters?
337     ESI.Exceptions = OldProto->exceptions();
338   }
339 
340   if (ESI.Type == EST_NoexceptFalse)
341     ESI.Type = EST_None;
342   if (ESI.Type == EST_NoexceptTrue)
343     ESI.Type = EST_BasicNoexcept;
344 
345   // For dependent noexcept, we can't just take the expression from the old
346   // prototype. It likely contains references to the old prototype's parameters.
347   if (ESI.Type == EST_DependentNoexcept) {
348     New->setInvalidDecl();
349   } else {
350     // Update the type of the function with the appropriate exception
351     // specification.
352     New->setType(Context.getFunctionType(
353         NewProto->getReturnType(), NewProto->getParamTypes(),
354         NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
355   }
356 
357   if (getLangOpts().MicrosoftExt && ESI.Type != EST_DependentNoexcept) {
358     // Allow missing exception specifications in redeclarations as an extension.
359     DiagID = diag::ext_ms_missing_exception_specification;
360     ReturnValueOnError = false;
361   } else if (New->isReplaceableGlobalAllocationFunction() &&
362              ESI.Type != EST_DependentNoexcept) {
363     // Allow missing exception specifications in redeclarations as an extension,
364     // when declaring a replaceable global allocation function.
365     DiagID = diag::ext_missing_exception_specification;
366     ReturnValueOnError = false;
367   } else {
368     DiagID = diag::err_missing_exception_specification;
369     ReturnValueOnError = true;
370   }
371 
372   // Warn about the lack of exception specification.
373   SmallString<128> ExceptionSpecString;
374   llvm::raw_svector_ostream OS(ExceptionSpecString);
375   switch (OldProto->getExceptionSpecType()) {
376   case EST_DynamicNone:
377     OS << "throw()";
378     break;
379 
380   case EST_Dynamic: {
381     OS << "throw(";
382     bool OnFirstException = true;
383     for (const auto &E : OldProto->exceptions()) {
384       if (OnFirstException)
385         OnFirstException = false;
386       else
387         OS << ", ";
388 
389       OS << E.getAsString(getPrintingPolicy());
390     }
391     OS << ")";
392     break;
393   }
394 
395   case EST_BasicNoexcept:
396     OS << "noexcept";
397     break;
398 
399   case EST_DependentNoexcept:
400   case EST_NoexceptFalse:
401   case EST_NoexceptTrue:
402     OS << "noexcept(";
403     assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
404     OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
405     OS << ")";
406     break;
407 
408   default:
409     llvm_unreachable("This spec type is compatible with none.");
410   }
411 
412   SourceLocation FixItLoc;
413   if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
414     TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
415     // FIXME: Preserve enough information so that we can produce a correct fixit
416     // location when there is a trailing return type.
417     if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
418       if (!FTLoc.getTypePtr()->hasTrailingReturn())
419         FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
420   }
421 
422   if (FixItLoc.isInvalid())
423     Diag(New->getLocation(), DiagID)
424       << New << OS.str();
425   else {
426     Diag(New->getLocation(), DiagID)
427       << New << OS.str()
428       << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
429   }
430 
431   if (Old->getLocation().isValid())
432     Diag(Old->getLocation(), diag::note_previous_declaration);
433 
434   return ReturnValueOnError;
435 }
436 
437 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
438 /// exception specifications. Exception specifications are equivalent if
439 /// they allow exactly the same set of exception types. It does not matter how
440 /// that is achieved. See C++ [except.spec]p2.
441 bool Sema::CheckEquivalentExceptionSpec(
442     const FunctionProtoType *Old, SourceLocation OldLoc,
443     const FunctionProtoType *New, SourceLocation NewLoc) {
444   if (!getLangOpts().CXXExceptions)
445     return false;
446 
447   unsigned DiagID = diag::err_mismatched_exception_spec;
448   if (getLangOpts().MicrosoftExt)
449     DiagID = diag::ext_mismatched_exception_spec;
450   bool Result = CheckEquivalentExceptionSpecImpl(
451       *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
452       Old, OldLoc, New, NewLoc);
453 
454   // In Microsoft mode, mismatching exception specifications just cause a warning.
455   if (getLangOpts().MicrosoftExt)
456     return false;
457   return Result;
458 }
459 
460 /// CheckEquivalentExceptionSpec - Check if the two types have compatible
461 /// exception specifications. See C++ [except.spec]p3.
462 ///
463 /// \return \c false if the exception specifications match, \c true if there is
464 /// a problem. If \c true is returned, either a diagnostic has already been
465 /// produced or \c *MissingExceptionSpecification is set to \c true.
466 static bool CheckEquivalentExceptionSpecImpl(
467     Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
468     const FunctionProtoType *Old, SourceLocation OldLoc,
469     const FunctionProtoType *New, SourceLocation NewLoc,
470     bool *MissingExceptionSpecification,
471     bool *MissingEmptyExceptionSpecification,
472     bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
473   if (MissingExceptionSpecification)
474     *MissingExceptionSpecification = false;
475 
476   if (MissingEmptyExceptionSpecification)
477     *MissingEmptyExceptionSpecification = false;
478 
479   Old = S.ResolveExceptionSpec(NewLoc, Old);
480   if (!Old)
481     return false;
482   New = S.ResolveExceptionSpec(NewLoc, New);
483   if (!New)
484     return false;
485 
486   // C++0x [except.spec]p3: Two exception-specifications are compatible if:
487   //   - both are non-throwing, regardless of their form,
488   //   - both have the form noexcept(constant-expression) and the constant-
489   //     expressions are equivalent,
490   //   - both are dynamic-exception-specifications that have the same set of
491   //     adjusted types.
492   //
493   // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
494   //   of the form throw(), noexcept, or noexcept(constant-expression) where the
495   //   constant-expression yields true.
496   //
497   // C++0x [except.spec]p4: If any declaration of a function has an exception-
498   //   specifier that is not a noexcept-specification allowing all exceptions,
499   //   all declarations [...] of that function shall have a compatible
500   //   exception-specification.
501   //
502   // That last point basically means that noexcept(false) matches no spec.
503   // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
504 
505   ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
506   ExceptionSpecificationType NewEST = New->getExceptionSpecType();
507 
508   assert(!isUnresolvedExceptionSpec(OldEST) &&
509          !isUnresolvedExceptionSpec(NewEST) &&
510          "Shouldn't see unknown exception specifications here");
511 
512   CanThrowResult OldCanThrow = Old->canThrow();
513   CanThrowResult NewCanThrow = New->canThrow();
514 
515   // Any non-throwing specifications are compatible.
516   if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
517     return false;
518 
519   // Any throws-anything specifications are usually compatible.
520   if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
521       NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
522     // The exception is that the absence of an exception specification only
523     // matches noexcept(false) for functions, as described above.
524     if (!AllowNoexceptAllMatchWithNoSpec &&
525         ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
526          (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
527       // This is the disallowed case.
528     } else {
529       return false;
530     }
531   }
532 
533   // FIXME: We treat dependent noexcept specifications as compatible even if
534   // their expressions are not equivalent.
535   if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept)
536     return false;
537 
538   // Dynamic exception specifications with the same set of adjusted types
539   // are compatible.
540   if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
541     bool Success = true;
542     // Both have a dynamic exception spec. Collect the first set, then compare
543     // to the second.
544     llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
545     for (const auto &I : Old->exceptions())
546       OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
547 
548     for (const auto &I : New->exceptions()) {
549       CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
550       if (OldTypes.count(TypePtr))
551         NewTypes.insert(TypePtr);
552       else {
553         Success = false;
554         break;
555       }
556     }
557 
558     if (Success && OldTypes.size() == NewTypes.size())
559       return false;
560   }
561 
562   // As a special compatibility feature, under C++0x we accept no spec and
563   // throw(std::bad_alloc) as equivalent for operator new and operator new[].
564   // This is because the implicit declaration changed, but old code would break.
565   if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
566     const FunctionProtoType *WithExceptions = nullptr;
567     if (OldEST == EST_None && NewEST == EST_Dynamic)
568       WithExceptions = New;
569     else if (OldEST == EST_Dynamic && NewEST == EST_None)
570       WithExceptions = Old;
571     if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
572       // One has no spec, the other throw(something). If that something is
573       // std::bad_alloc, all conditions are met.
574       QualType Exception = *WithExceptions->exception_begin();
575       if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
576         IdentifierInfo* Name = ExRecord->getIdentifier();
577         if (Name && Name->getName() == "bad_alloc") {
578           // It's called bad_alloc, but is it in std?
579           if (ExRecord->isInStdNamespace()) {
580             return false;
581           }
582         }
583       }
584     }
585   }
586 
587   // If the caller wants to handle the case that the new function is
588   // incompatible due to a missing exception specification, let it.
589   if (MissingExceptionSpecification && OldEST != EST_None &&
590       NewEST == EST_None) {
591     // The old type has an exception specification of some sort, but
592     // the new type does not.
593     *MissingExceptionSpecification = true;
594 
595     if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
596       // The old type has a throw() or noexcept(true) exception specification
597       // and the new type has no exception specification, and the caller asked
598       // to handle this itself.
599       *MissingEmptyExceptionSpecification = true;
600     }
601 
602     return true;
603   }
604 
605   S.Diag(NewLoc, DiagID);
606   if (NoteID.getDiagID() != 0 && OldLoc.isValid())
607     S.Diag(OldLoc, NoteID);
608   return true;
609 }
610 
611 bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
612                                         const PartialDiagnostic &NoteID,
613                                         const FunctionProtoType *Old,
614                                         SourceLocation OldLoc,
615                                         const FunctionProtoType *New,
616                                         SourceLocation NewLoc) {
617   if (!getLangOpts().CXXExceptions)
618     return false;
619   return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
620                                           New, NewLoc);
621 }
622 
623 bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
624   // [except.handle]p3:
625   //   A handler is a match for an exception object of type E if:
626 
627   // HandlerType must be ExceptionType or derived from it, or pointer or
628   // reference to such types.
629   const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
630   if (RefTy)
631     HandlerType = RefTy->getPointeeType();
632 
633   //   -- the handler is of type cv T or cv T& and E and T are the same type
634   if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
635     return true;
636 
637   // FIXME: ObjC pointer types?
638   if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
639     if (RefTy && (!HandlerType.isConstQualified() ||
640                   HandlerType.isVolatileQualified()))
641       return false;
642 
643     // -- the handler is of type cv T or const T& where T is a pointer or
644     //    pointer to member type and E is std::nullptr_t
645     if (ExceptionType->isNullPtrType())
646       return true;
647 
648     // -- the handler is of type cv T or const T& where T is a pointer or
649     //    pointer to member type and E is a pointer or pointer to member type
650     //    that can be converted to T by one or more of
651     //    -- a qualification conversion
652     //    -- a function pointer conversion
653     bool LifetimeConv;
654     QualType Result;
655     // FIXME: Should we treat the exception as catchable if a lifetime
656     // conversion is required?
657     if (IsQualificationConversion(ExceptionType, HandlerType, false,
658                                   LifetimeConv) ||
659         IsFunctionConversion(ExceptionType, HandlerType, Result))
660       return true;
661 
662     //    -- a standard pointer conversion [...]
663     if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
664       return false;
665 
666     // Handle the "qualification conversion" portion.
667     Qualifiers EQuals, HQuals;
668     ExceptionType = Context.getUnqualifiedArrayType(
669         ExceptionType->getPointeeType(), EQuals);
670     HandlerType = Context.getUnqualifiedArrayType(
671         HandlerType->getPointeeType(), HQuals);
672     if (!HQuals.compatiblyIncludes(EQuals))
673       return false;
674 
675     if (HandlerType->isVoidType() && ExceptionType->isObjectType())
676       return true;
677 
678     // The only remaining case is a derived-to-base conversion.
679   }
680 
681   //   -- the handler is of type cg T or cv T& and T is an unambiguous public
682   //      base class of E
683   if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
684     return false;
685   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
686                      /*DetectVirtual=*/false);
687   if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
688       Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
689     return false;
690 
691   // Do this check from a context without privileges.
692   switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
693                                Paths.front(),
694                                /*Diagnostic*/ 0,
695                                /*ForceCheck*/ true,
696                                /*ForceUnprivileged*/ true)) {
697   case AR_accessible: return true;
698   case AR_inaccessible: return false;
699   case AR_dependent:
700     llvm_unreachable("access check dependent for unprivileged context");
701   case AR_delayed:
702     llvm_unreachable("access check delayed in non-declaration");
703   }
704   llvm_unreachable("unexpected access check result");
705 }
706 
707 /// CheckExceptionSpecSubset - Check whether the second function type's
708 /// exception specification is a subset (or equivalent) of the first function
709 /// type. This is used by override and pointer assignment checks.
710 bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
711                                     const PartialDiagnostic &NestedDiagID,
712                                     const PartialDiagnostic &NoteID,
713                                     const FunctionProtoType *Superset,
714                                     SourceLocation SuperLoc,
715                                     const FunctionProtoType *Subset,
716                                     SourceLocation SubLoc) {
717 
718   // Just auto-succeed under -fno-exceptions.
719   if (!getLangOpts().CXXExceptions)
720     return false;
721 
722   // FIXME: As usual, we could be more specific in our error messages, but
723   // that better waits until we've got types with source locations.
724 
725   if (!SubLoc.isValid())
726     SubLoc = SuperLoc;
727 
728   // Resolve the exception specifications, if needed.
729   Superset = ResolveExceptionSpec(SuperLoc, Superset);
730   if (!Superset)
731     return false;
732   Subset = ResolveExceptionSpec(SubLoc, Subset);
733   if (!Subset)
734     return false;
735 
736   ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
737   ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
738   assert(!isUnresolvedExceptionSpec(SuperEST) &&
739          !isUnresolvedExceptionSpec(SubEST) &&
740          "Shouldn't see unknown exception specifications here");
741 
742   // If there are dependent noexcept specs, assume everything is fine. Unlike
743   // with the equivalency check, this is safe in this case, because we don't
744   // want to merge declarations. Checks after instantiation will catch any
745   // omissions we make here.
746   if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
747     return false;
748 
749   CanThrowResult SuperCanThrow = Superset->canThrow();
750   CanThrowResult SubCanThrow = Subset->canThrow();
751 
752   // If the superset contains everything or the subset contains nothing, we're
753   // done.
754   if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
755       SubCanThrow == CT_Cannot)
756     return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
757                                    Subset, SubLoc);
758 
759   // If the subset contains everything or the superset contains nothing, we've
760   // failed.
761   if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
762       SuperCanThrow == CT_Cannot) {
763     Diag(SubLoc, DiagID);
764     if (NoteID.getDiagID() != 0)
765       Diag(SuperLoc, NoteID);
766     return true;
767   }
768 
769   assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
770          "Exception spec subset: non-dynamic case slipped through.");
771 
772   // Neither contains everything or nothing. Do a proper comparison.
773   for (QualType SubI : Subset->exceptions()) {
774     if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
775       SubI = RefTy->getPointeeType();
776 
777     // Make sure it's in the superset.
778     bool Contained = false;
779     for (QualType SuperI : Superset->exceptions()) {
780       // [except.spec]p5:
781       //   the target entity shall allow at least the exceptions allowed by the
782       //   source
783       //
784       // We interpret this as meaning that a handler for some target type would
785       // catch an exception of each source type.
786       if (handlerCanCatch(SuperI, SubI)) {
787         Contained = true;
788         break;
789       }
790     }
791     if (!Contained) {
792       Diag(SubLoc, DiagID);
793       if (NoteID.getDiagID() != 0)
794         Diag(SuperLoc, NoteID);
795       return true;
796     }
797   }
798   // We've run half the gauntlet.
799   return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
800                                  Subset, SubLoc);
801 }
802 
803 static bool
804 CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
805                             const PartialDiagnostic &NoteID, QualType Target,
806                             SourceLocation TargetLoc, QualType Source,
807                             SourceLocation SourceLoc) {
808   const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
809   if (!TFunc)
810     return false;
811   const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
812   if (!SFunc)
813     return false;
814 
815   return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
816                                         SFunc, SourceLoc);
817 }
818 
819 /// CheckParamExceptionSpec - Check if the parameter and return types of the
820 /// two functions have equivalent exception specs. This is part of the
821 /// assignment and override compatibility check. We do not check the parameters
822 /// of parameter function pointers recursively, as no sane programmer would
823 /// even be able to write such a function type.
824 bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
825                                    const PartialDiagnostic &NoteID,
826                                    const FunctionProtoType *Target,
827                                    SourceLocation TargetLoc,
828                                    const FunctionProtoType *Source,
829                                    SourceLocation SourceLoc) {
830   auto RetDiag = DiagID;
831   RetDiag << 0;
832   if (CheckSpecForTypesEquivalent(
833           *this, RetDiag, PDiag(),
834           Target->getReturnType(), TargetLoc, Source->getReturnType(),
835           SourceLoc))
836     return true;
837 
838   // We shouldn't even be testing this unless the arguments are otherwise
839   // compatible.
840   assert(Target->getNumParams() == Source->getNumParams() &&
841          "Functions have different argument counts.");
842   for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
843     auto ParamDiag = DiagID;
844     ParamDiag << 1;
845     if (CheckSpecForTypesEquivalent(
846             *this, ParamDiag, PDiag(),
847             Target->getParamType(i), TargetLoc, Source->getParamType(i),
848             SourceLoc))
849       return true;
850   }
851   return false;
852 }
853 
854 bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
855   // First we check for applicability.
856   // Target type must be a function, function pointer or function reference.
857   const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
858   if (!ToFunc || ToFunc->hasDependentExceptionSpec())
859     return false;
860 
861   // SourceType must be a function or function pointer.
862   const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
863   if (!FromFunc || FromFunc->hasDependentExceptionSpec())
864     return false;
865 
866   unsigned DiagID = diag::err_incompatible_exception_specs;
867   unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
868   // This is not an error in C++17 onwards, unless the noexceptness doesn't
869   // match, but in that case we have a full-on type mismatch, not just a
870   // type sugar mismatch.
871   if (getLangOpts().CPlusPlus17) {
872     DiagID = diag::warn_incompatible_exception_specs;
873     NestedDiagID = diag::warn_deep_exception_specs_differ;
874   }
875 
876   // Now we've got the correct types on both sides, check their compatibility.
877   // This means that the source of the conversion can only throw a subset of
878   // the exceptions of the target, and any exception specs on arguments or
879   // return types must be equivalent.
880   //
881   // FIXME: If there is a nested dependent exception specification, we should
882   // not be checking it here. This is fine:
883   //   template<typename T> void f() {
884   //     void (*p)(void (*) throw(T));
885   //     void (*q)(void (*) throw(int)) = p;
886   //   }
887   // ... because it might be instantiated with T=int.
888   return CheckExceptionSpecSubset(PDiag(DiagID), PDiag(NestedDiagID), PDiag(),
889                                   ToFunc, From->getSourceRange().getBegin(),
890                                   FromFunc, SourceLocation()) &&
891          !getLangOpts().CPlusPlus17;
892 }
893 
894 bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
895                                                 const CXXMethodDecl *Old) {
896   // If the new exception specification hasn't been parsed yet, skip the check.
897   // We'll get called again once it's been parsed.
898   if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
899       EST_Unparsed)
900     return false;
901   if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
902     // Don't check uninstantiated template destructors at all. We can only
903     // synthesize correct specs after the template is instantiated.
904     if (New->getParent()->isDependentType())
905       return false;
906     if (New->getParent()->isBeingDefined()) {
907       // The destructor might be updated once the definition is finished. So
908       // remember it and check later.
909       DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
910       return false;
911     }
912   }
913   // If the old exception specification hasn't been parsed yet, remember that
914   // we need to perform this check when we get to the end of the outermost
915   // lexically-surrounding class.
916   if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
917       EST_Unparsed) {
918     DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
919     return false;
920   }
921   unsigned DiagID = diag::err_override_exception_spec;
922   if (getLangOpts().MicrosoftExt)
923     DiagID = diag::ext_override_exception_spec;
924   return CheckExceptionSpecSubset(PDiag(DiagID),
925                                   PDiag(diag::err_deep_exception_specs_differ),
926                                   PDiag(diag::note_overridden_virtual_function),
927                                   Old->getType()->getAs<FunctionProtoType>(),
928                                   Old->getLocation(),
929                                   New->getType()->getAs<FunctionProtoType>(),
930                                   New->getLocation());
931 }
932 
933 static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
934   CanThrowResult R = CT_Cannot;
935   for (const Stmt *SubStmt : E->children()) {
936     R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
937     if (R == CT_Can)
938       break;
939   }
940   return R;
941 }
942 
943 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
944   // As an extension, we assume that __attribute__((nothrow)) functions don't
945   // throw.
946   if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
947     return CT_Cannot;
948 
949   QualType T;
950 
951   // In C++1z, just look at the function type of the callee.
952   if (S.getLangOpts().CPlusPlus17 && isa<CallExpr>(E)) {
953     E = cast<CallExpr>(E)->getCallee();
954     T = E->getType();
955     if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
956       // Sadly we don't preserve the actual type as part of the "bound member"
957       // placeholder, so we need to reconstruct it.
958       E = E->IgnoreParenImpCasts();
959 
960       // Could be a call to a pointer-to-member or a plain member access.
961       if (auto *Op = dyn_cast<BinaryOperator>(E)) {
962         assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
963         T = Op->getRHS()->getType()
964               ->castAs<MemberPointerType>()->getPointeeType();
965       } else {
966         T = cast<MemberExpr>(E)->getMemberDecl()->getType();
967       }
968     }
969   } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
970     T = VD->getType();
971   else
972     // If we have no clue what we're calling, assume the worst.
973     return CT_Can;
974 
975   const FunctionProtoType *FT;
976   if ((FT = T->getAs<FunctionProtoType>())) {
977   } else if (const PointerType *PT = T->getAs<PointerType>())
978     FT = PT->getPointeeType()->getAs<FunctionProtoType>();
979   else if (const ReferenceType *RT = T->getAs<ReferenceType>())
980     FT = RT->getPointeeType()->getAs<FunctionProtoType>();
981   else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
982     FT = MT->getPointeeType()->getAs<FunctionProtoType>();
983   else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
984     FT = BT->getPointeeType()->getAs<FunctionProtoType>();
985 
986   if (!FT)
987     return CT_Can;
988 
989   FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
990   if (!FT)
991     return CT_Can;
992 
993   return FT->canThrow();
994 }
995 
996 static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
997   if (DC->isTypeDependent())
998     return CT_Dependent;
999 
1000   if (!DC->getTypeAsWritten()->isReferenceType())
1001     return CT_Cannot;
1002 
1003   if (DC->getSubExpr()->isTypeDependent())
1004     return CT_Dependent;
1005 
1006   return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1007 }
1008 
1009 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1010   if (DC->isTypeOperand())
1011     return CT_Cannot;
1012 
1013   Expr *Op = DC->getExprOperand();
1014   if (Op->isTypeDependent())
1015     return CT_Dependent;
1016 
1017   const RecordType *RT = Op->getType()->getAs<RecordType>();
1018   if (!RT)
1019     return CT_Cannot;
1020 
1021   if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1022     return CT_Cannot;
1023 
1024   if (Op->Classify(S.Context).isPRValue())
1025     return CT_Cannot;
1026 
1027   return CT_Can;
1028 }
1029 
1030 CanThrowResult Sema::canThrow(const Expr *E) {
1031   // C++ [expr.unary.noexcept]p3:
1032   //   [Can throw] if in a potentially-evaluated context the expression would
1033   //   contain:
1034   switch (E->getStmtClass()) {
1035   case Expr::CXXThrowExprClass:
1036     //   - a potentially evaluated throw-expression
1037     return CT_Can;
1038 
1039   case Expr::CXXDynamicCastExprClass: {
1040     //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1041     //     where T is a reference type, that requires a run-time check
1042     CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
1043     if (CT == CT_Can)
1044       return CT;
1045     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1046   }
1047 
1048   case Expr::CXXTypeidExprClass:
1049     //   - a potentially evaluated typeid expression applied to a glvalue
1050     //     expression whose type is a polymorphic class type
1051     return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
1052 
1053     //   - a potentially evaluated call to a function, member function, function
1054     //     pointer, or member function pointer that does not have a non-throwing
1055     //     exception-specification
1056   case Expr::CallExprClass:
1057   case Expr::CXXMemberCallExprClass:
1058   case Expr::CXXOperatorCallExprClass:
1059   case Expr::UserDefinedLiteralClass: {
1060     const CallExpr *CE = cast<CallExpr>(E);
1061     CanThrowResult CT;
1062     if (E->isTypeDependent())
1063       CT = CT_Dependent;
1064     else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1065       CT = CT_Cannot;
1066     else
1067       CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
1068     if (CT == CT_Can)
1069       return CT;
1070     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1071   }
1072 
1073   case Expr::CXXConstructExprClass:
1074   case Expr::CXXTemporaryObjectExprClass: {
1075     CanThrowResult CT = canCalleeThrow(*this, E,
1076         cast<CXXConstructExpr>(E)->getConstructor());
1077     if (CT == CT_Can)
1078       return CT;
1079     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1080   }
1081 
1082   case Expr::CXXInheritedCtorInitExprClass:
1083     return canCalleeThrow(*this, E,
1084                           cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
1085 
1086   case Expr::LambdaExprClass: {
1087     const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1088     CanThrowResult CT = CT_Cannot;
1089     for (LambdaExpr::const_capture_init_iterator
1090              Cap = Lambda->capture_init_begin(),
1091              CapEnd = Lambda->capture_init_end();
1092          Cap != CapEnd; ++Cap)
1093       CT = mergeCanThrow(CT, canThrow(*Cap));
1094     return CT;
1095   }
1096 
1097   case Expr::CXXNewExprClass: {
1098     CanThrowResult CT;
1099     if (E->isTypeDependent())
1100       CT = CT_Dependent;
1101     else
1102       CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1103     if (CT == CT_Can)
1104       return CT;
1105     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1106   }
1107 
1108   case Expr::CXXDeleteExprClass: {
1109     CanThrowResult CT;
1110     QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1111     if (DTy.isNull() || DTy->isDependentType()) {
1112       CT = CT_Dependent;
1113     } else {
1114       CT = canCalleeThrow(*this, E,
1115                           cast<CXXDeleteExpr>(E)->getOperatorDelete());
1116       if (const RecordType *RT = DTy->getAs<RecordType>()) {
1117         const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1118         const CXXDestructorDecl *DD = RD->getDestructor();
1119         if (DD)
1120           CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
1121       }
1122       if (CT == CT_Can)
1123         return CT;
1124     }
1125     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1126   }
1127 
1128   case Expr::CXXBindTemporaryExprClass: {
1129     // The bound temporary has to be destroyed again, which might throw.
1130     CanThrowResult CT = canCalleeThrow(*this, E,
1131       cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1132     if (CT == CT_Can)
1133       return CT;
1134     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1135   }
1136 
1137     // ObjC message sends are like function calls, but never have exception
1138     // specs.
1139   case Expr::ObjCMessageExprClass:
1140   case Expr::ObjCPropertyRefExprClass:
1141   case Expr::ObjCSubscriptRefExprClass:
1142     return CT_Can;
1143 
1144     // All the ObjC literals that are implemented as calls are
1145     // potentially throwing unless we decide to close off that
1146     // possibility.
1147   case Expr::ObjCArrayLiteralClass:
1148   case Expr::ObjCDictionaryLiteralClass:
1149   case Expr::ObjCBoxedExprClass:
1150     return CT_Can;
1151 
1152     // Many other things have subexpressions, so we have to test those.
1153     // Some are simple:
1154   case Expr::CoawaitExprClass:
1155   case Expr::ConditionalOperatorClass:
1156   case Expr::CompoundLiteralExprClass:
1157   case Expr::CoyieldExprClass:
1158   case Expr::CXXConstCastExprClass:
1159   case Expr::CXXReinterpretCastExprClass:
1160   case Expr::CXXStdInitializerListExprClass:
1161   case Expr::DesignatedInitExprClass:
1162   case Expr::DesignatedInitUpdateExprClass:
1163   case Expr::ExprWithCleanupsClass:
1164   case Expr::ExtVectorElementExprClass:
1165   case Expr::InitListExprClass:
1166   case Expr::ArrayInitLoopExprClass:
1167   case Expr::MemberExprClass:
1168   case Expr::ObjCIsaExprClass:
1169   case Expr::ObjCIvarRefExprClass:
1170   case Expr::ParenExprClass:
1171   case Expr::ParenListExprClass:
1172   case Expr::ShuffleVectorExprClass:
1173   case Expr::ConvertVectorExprClass:
1174   case Expr::VAArgExprClass:
1175     return canSubExprsThrow(*this, E);
1176 
1177     // Some might be dependent for other reasons.
1178   case Expr::ArraySubscriptExprClass:
1179   case Expr::OMPArraySectionExprClass:
1180   case Expr::BinaryOperatorClass:
1181   case Expr::DependentCoawaitExprClass:
1182   case Expr::CompoundAssignOperatorClass:
1183   case Expr::CStyleCastExprClass:
1184   case Expr::CXXStaticCastExprClass:
1185   case Expr::CXXFunctionalCastExprClass:
1186   case Expr::ImplicitCastExprClass:
1187   case Expr::MaterializeTemporaryExprClass:
1188   case Expr::UnaryOperatorClass: {
1189     CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1190     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1191   }
1192 
1193     // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1194   case Expr::StmtExprClass:
1195     return CT_Can;
1196 
1197   case Expr::CXXDefaultArgExprClass:
1198     return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1199 
1200   case Expr::CXXDefaultInitExprClass:
1201     return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1202 
1203   case Expr::ChooseExprClass:
1204     if (E->isTypeDependent() || E->isValueDependent())
1205       return CT_Dependent;
1206     return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1207 
1208   case Expr::GenericSelectionExprClass:
1209     if (cast<GenericSelectionExpr>(E)->isResultDependent())
1210       return CT_Dependent;
1211     return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1212 
1213     // Some expressions are always dependent.
1214   case Expr::CXXDependentScopeMemberExprClass:
1215   case Expr::CXXUnresolvedConstructExprClass:
1216   case Expr::DependentScopeDeclRefExprClass:
1217   case Expr::CXXFoldExprClass:
1218     return CT_Dependent;
1219 
1220   case Expr::AsTypeExprClass:
1221   case Expr::BinaryConditionalOperatorClass:
1222   case Expr::BlockExprClass:
1223   case Expr::CUDAKernelCallExprClass:
1224   case Expr::DeclRefExprClass:
1225   case Expr::ObjCBridgedCastExprClass:
1226   case Expr::ObjCIndirectCopyRestoreExprClass:
1227   case Expr::ObjCProtocolExprClass:
1228   case Expr::ObjCSelectorExprClass:
1229   case Expr::ObjCAvailabilityCheckExprClass:
1230   case Expr::OffsetOfExprClass:
1231   case Expr::PackExpansionExprClass:
1232   case Expr::PseudoObjectExprClass:
1233   case Expr::SubstNonTypeTemplateParmExprClass:
1234   case Expr::SubstNonTypeTemplateParmPackExprClass:
1235   case Expr::FunctionParmPackExprClass:
1236   case Expr::UnaryExprOrTypeTraitExprClass:
1237   case Expr::UnresolvedLookupExprClass:
1238   case Expr::UnresolvedMemberExprClass:
1239   case Expr::TypoExprClass:
1240     // FIXME: Can any of the above throw?  If so, when?
1241     return CT_Cannot;
1242 
1243   case Expr::AddrLabelExprClass:
1244   case Expr::ArrayTypeTraitExprClass:
1245   case Expr::AtomicExprClass:
1246   case Expr::TypeTraitExprClass:
1247   case Expr::CXXBoolLiteralExprClass:
1248   case Expr::CXXNoexceptExprClass:
1249   case Expr::CXXNullPtrLiteralExprClass:
1250   case Expr::CXXPseudoDestructorExprClass:
1251   case Expr::CXXScalarValueInitExprClass:
1252   case Expr::CXXThisExprClass:
1253   case Expr::CXXUuidofExprClass:
1254   case Expr::CharacterLiteralClass:
1255   case Expr::ExpressionTraitExprClass:
1256   case Expr::FloatingLiteralClass:
1257   case Expr::GNUNullExprClass:
1258   case Expr::ImaginaryLiteralClass:
1259   case Expr::ImplicitValueInitExprClass:
1260   case Expr::IntegerLiteralClass:
1261   case Expr::ArrayInitIndexExprClass:
1262   case Expr::NoInitExprClass:
1263   case Expr::ObjCEncodeExprClass:
1264   case Expr::ObjCStringLiteralClass:
1265   case Expr::ObjCBoolLiteralExprClass:
1266   case Expr::OpaqueValueExprClass:
1267   case Expr::PredefinedExprClass:
1268   case Expr::SizeOfPackExprClass:
1269   case Expr::StringLiteralClass:
1270     // These expressions can never throw.
1271     return CT_Cannot;
1272 
1273   case Expr::MSPropertyRefExprClass:
1274   case Expr::MSPropertySubscriptExprClass:
1275     llvm_unreachable("Invalid class for expression");
1276 
1277 #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1278 #define STMT_RANGE(Base, First, Last)
1279 #define LAST_STMT_RANGE(BASE, FIRST, LAST)
1280 #define EXPR(CLASS, PARENT)
1281 #define ABSTRACT_STMT(STMT)
1282 #include "clang/AST/StmtNodes.inc"
1283   case Expr::NoStmtClass:
1284     llvm_unreachable("Invalid class for expression");
1285   }
1286   llvm_unreachable("Bogus StmtClass");
1287 }
1288 
1289 } // end namespace clang
1290