]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExceptionSpec.cpp
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / contrib / llvm / tools / clang / lib / Sema / SemaExceptionSpec.cpp
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/CXXInheritance.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Lex/Preprocessor.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 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
39 /// exception specification. Incomplete types, or pointers to incomplete types
40 /// other than void are not allowed.
41 ///
42 /// \param[in,out] T  The exception type. This will be decayed to a pointer type
43 ///                   when the input is an array or a function type.
44 bool Sema::CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range) {
45   // C++11 [except.spec]p2:
46   //   A type cv T, "array of T", or "function returning T" denoted
47   //   in an exception-specification is adjusted to type T, "pointer to T", or
48   //   "pointer to function returning T", respectively.
49   //
50   // We also apply this rule in C++98.
51   if (T->isArrayType())
52     T = Context.getArrayDecayedType(T);
53   else if (T->isFunctionType())
54     T = Context.getPointerType(T);
55
56   int Kind = 0;
57   QualType PointeeT = T;
58   if (const PointerType *PT = T->getAs<PointerType>()) {
59     PointeeT = PT->getPointeeType();
60     Kind = 1;
61
62     // cv void* is explicitly permitted, despite being a pointer to an
63     // incomplete type.
64     if (PointeeT->isVoidType())
65       return false;
66   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
67     PointeeT = RT->getPointeeType();
68     Kind = 2;
69
70     if (RT->isRValueReferenceType()) {
71       // C++11 [except.spec]p2:
72       //   A type denoted in an exception-specification shall not denote [...]
73       //   an rvalue reference type.
74       Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
75         << T << Range;
76       return true;
77     }
78   }
79
80   // C++11 [except.spec]p2:
81   //   A type denoted in an exception-specification shall not denote an
82   //   incomplete type other than a class currently being defined [...].
83   //   A type denoted in an exception-specification shall not denote a
84   //   pointer or reference to an incomplete type, other than (cv) void* or a
85   //   pointer or reference to a class currently being defined.
86   if (!(PointeeT->isRecordType() &&
87         PointeeT->getAs<RecordType>()->isBeingDefined()) &&
88       RequireCompleteType(Range.getBegin(), PointeeT,
89                           diag::err_incomplete_in_exception_spec, Kind, Range))
90     return true;
91
92   return false;
93 }
94
95 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
96 /// to member to a function with an exception specification. This means that
97 /// it is invalid to add another level of indirection.
98 bool Sema::CheckDistantExceptionSpec(QualType T) {
99   if (const PointerType *PT = T->getAs<PointerType>())
100     T = PT->getPointeeType();
101   else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
102     T = PT->getPointeeType();
103   else
104     return false;
105
106   const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
107   if (!FnT)
108     return false;
109
110   return FnT->hasExceptionSpec();
111 }
112
113 const FunctionProtoType *
114 Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
115   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
116     return FPT;
117
118   FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
119   const FunctionProtoType *SourceFPT =
120       SourceDecl->getType()->castAs<FunctionProtoType>();
121
122   // If the exception specification has already been resolved, just return it.
123   if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
124     return SourceFPT;
125
126   // Compute or instantiate the exception specification now.
127   if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
128     EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
129   else
130     InstantiateExceptionSpec(Loc, SourceDecl);
131
132   return SourceDecl->getType()->castAs<FunctionProtoType>();
133 }
134
135 /// Determine whether a function has an implicitly-generated exception
136 /// specification.
137 static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
138   if (!isa<CXXDestructorDecl>(Decl) &&
139       Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
140       Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
141     return false;
142
143   // If the user didn't declare the function, its exception specification must
144   // be implicit.
145   if (!Decl->getTypeSourceInfo())
146     return true;
147
148   const FunctionProtoType *Ty =
149     Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
150   return !Ty->hasExceptionSpec();
151 }
152
153 bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
154   OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
155   bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
156   bool MissingExceptionSpecification = false;
157   bool MissingEmptyExceptionSpecification = false;
158   unsigned DiagID = diag::err_mismatched_exception_spec;
159   if (getLangOpts().MicrosoftExt)
160     DiagID = diag::warn_mismatched_exception_spec; 
161
162   // Check the types as written: they must match before any exception
163   // specification adjustment is applied.
164   if (!CheckEquivalentExceptionSpec(
165         PDiag(DiagID), PDiag(diag::note_previous_declaration),
166         Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
167         New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
168         &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
169         /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
170     // C++11 [except.spec]p4 [DR1492]:
171     //   If a declaration of a function has an implicit
172     //   exception-specification, other declarations of the function shall
173     //   not specify an exception-specification.
174     if (getLangOpts().CPlusPlus11 &&
175         hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
176       Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
177         << hasImplicitExceptionSpec(Old);
178       if (!Old->getLocation().isInvalid())
179         Diag(Old->getLocation(), diag::note_previous_declaration);
180     }
181     return false;
182   }
183
184   // The failure was something other than an missing exception
185   // specification; return an error.
186   if (!MissingExceptionSpecification)
187     return true;
188
189   const FunctionProtoType *NewProto =
190     New->getType()->castAs<FunctionProtoType>();
191
192   // The new function declaration is only missing an empty exception
193   // specification "throw()". If the throw() specification came from a
194   // function in a system header that has C linkage, just add an empty
195   // exception specification to the "new" declaration. This is an
196   // egregious workaround for glibc, which adds throw() specifications
197   // to many libc functions as an optimization. Unfortunately, that
198   // optimization isn't permitted by the C++ standard, so we're forced
199   // to work around it here.
200   if (MissingEmptyExceptionSpecification && NewProto &&
201       (Old->getLocation().isInvalid() ||
202        Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
203       Old->isExternC()) {
204     FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
205     EPI.ExceptionSpecType = EST_DynamicNone;
206     QualType NewType = Context.getFunctionType(NewProto->getResultType(),
207                                                NewProto->getArgTypes(), EPI);
208     New->setType(NewType);
209     return false;
210   }
211
212   const FunctionProtoType *OldProto =
213     Old->getType()->castAs<FunctionProtoType>();
214
215   FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
216   EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
217   if (EPI.ExceptionSpecType == EST_Dynamic) {
218     EPI.NumExceptions = OldProto->getNumExceptions();
219     EPI.Exceptions = OldProto->exception_begin();
220   } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
221     // FIXME: We can't just take the expression from the old prototype. It
222     // likely contains references to the old prototype's parameters.
223   }
224
225   // Update the type of the function with the appropriate exception
226   // specification.
227   QualType NewType = Context.getFunctionType(NewProto->getResultType(),
228                                              NewProto->getArgTypes(), EPI);
229   New->setType(NewType);
230
231   // Warn about the lack of exception specification.
232   SmallString<128> ExceptionSpecString;
233   llvm::raw_svector_ostream OS(ExceptionSpecString);
234   switch (OldProto->getExceptionSpecType()) {
235   case EST_DynamicNone:
236     OS << "throw()";
237     break;
238
239   case EST_Dynamic: {
240     OS << "throw(";
241     bool OnFirstException = true;
242     for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
243                                             EEnd = OldProto->exception_end();
244          E != EEnd;
245          ++E) {
246       if (OnFirstException)
247         OnFirstException = false;
248       else
249         OS << ", ";
250       
251       OS << E->getAsString(getPrintingPolicy());
252     }
253     OS << ")";
254     break;
255   }
256
257   case EST_BasicNoexcept:
258     OS << "noexcept";
259     break;
260
261   case EST_ComputedNoexcept:
262     OS << "noexcept(";
263     OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
264     OS << ")";
265     break;
266
267   default:
268     llvm_unreachable("This spec type is compatible with none.");
269   }
270   OS.flush();
271
272   SourceLocation FixItLoc;
273   if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
274     TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
275     if (FunctionTypeLoc FTLoc = TL.getAs<FunctionTypeLoc>())
276       FixItLoc = PP.getLocForEndOfToken(FTLoc.getLocalRangeEnd());
277   }
278
279   if (FixItLoc.isInvalid())
280     Diag(New->getLocation(), diag::warn_missing_exception_specification)
281       << New << OS.str();
282   else {
283     // FIXME: This will get more complicated with C++0x
284     // late-specified return types.
285     Diag(New->getLocation(), diag::warn_missing_exception_specification)
286       << New << OS.str()
287       << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
288   }
289
290   if (!Old->getLocation().isInvalid())
291     Diag(Old->getLocation(), diag::note_previous_declaration);
292
293   return false;
294 }
295
296 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
297 /// exception specifications. Exception specifications are equivalent if
298 /// they allow exactly the same set of exception types. It does not matter how
299 /// that is achieved. See C++ [except.spec]p2.
300 bool Sema::CheckEquivalentExceptionSpec(
301     const FunctionProtoType *Old, SourceLocation OldLoc,
302     const FunctionProtoType *New, SourceLocation NewLoc) {
303   unsigned DiagID = diag::err_mismatched_exception_spec;
304   if (getLangOpts().MicrosoftExt)
305     DiagID = diag::warn_mismatched_exception_spec; 
306   return CheckEquivalentExceptionSpec(PDiag(DiagID),
307                                       PDiag(diag::note_previous_declaration),
308                                       Old, OldLoc, New, NewLoc);
309 }
310
311 /// CheckEquivalentExceptionSpec - Check if the two types have compatible
312 /// exception specifications. See C++ [except.spec]p3.
313 ///
314 /// \return \c false if the exception specifications match, \c true if there is
315 /// a problem. If \c true is returned, either a diagnostic has already been
316 /// produced or \c *MissingExceptionSpecification is set to \c true.
317 bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
318                                         const PartialDiagnostic & NoteID,
319                                         const FunctionProtoType *Old,
320                                         SourceLocation OldLoc,
321                                         const FunctionProtoType *New,
322                                         SourceLocation NewLoc,
323                                         bool *MissingExceptionSpecification,
324                                         bool*MissingEmptyExceptionSpecification,
325                                         bool AllowNoexceptAllMatchWithNoSpec,
326                                         bool IsOperatorNew) {
327   // Just completely ignore this under -fno-exceptions.
328   if (!getLangOpts().CXXExceptions)
329     return false;
330
331   if (MissingExceptionSpecification)
332     *MissingExceptionSpecification = false;
333
334   if (MissingEmptyExceptionSpecification)
335     *MissingEmptyExceptionSpecification = false;
336
337   Old = ResolveExceptionSpec(NewLoc, Old);
338   if (!Old)
339     return false;
340   New = ResolveExceptionSpec(NewLoc, New);
341   if (!New)
342     return false;
343
344   // C++0x [except.spec]p3: Two exception-specifications are compatible if:
345   //   - both are non-throwing, regardless of their form,
346   //   - both have the form noexcept(constant-expression) and the constant-
347   //     expressions are equivalent,
348   //   - both are dynamic-exception-specifications that have the same set of
349   //     adjusted types.
350   //
351   // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
352   //   of the form throw(), noexcept, or noexcept(constant-expression) where the
353   //   constant-expression yields true.
354   //
355   // C++0x [except.spec]p4: If any declaration of a function has an exception-
356   //   specifier that is not a noexcept-specification allowing all exceptions,
357   //   all declarations [...] of that function shall have a compatible
358   //   exception-specification.
359   //
360   // That last point basically means that noexcept(false) matches no spec.
361   // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
362
363   ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
364   ExceptionSpecificationType NewEST = New->getExceptionSpecType();
365
366   assert(!isUnresolvedExceptionSpec(OldEST) &&
367          !isUnresolvedExceptionSpec(NewEST) &&
368          "Shouldn't see unknown exception specifications here");
369
370   // Shortcut the case where both have no spec.
371   if (OldEST == EST_None && NewEST == EST_None)
372     return false;
373
374   FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
375   FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
376   if (OldNR == FunctionProtoType::NR_BadNoexcept ||
377       NewNR == FunctionProtoType::NR_BadNoexcept)
378     return false;
379
380   // Dependent noexcept specifiers are compatible with each other, but nothing
381   // else.
382   // One noexcept is compatible with another if the argument is the same
383   if (OldNR == NewNR &&
384       OldNR != FunctionProtoType::NR_NoNoexcept &&
385       NewNR != FunctionProtoType::NR_NoNoexcept)
386     return false;
387   if (OldNR != NewNR &&
388       OldNR != FunctionProtoType::NR_NoNoexcept &&
389       NewNR != FunctionProtoType::NR_NoNoexcept) {
390     Diag(NewLoc, DiagID);
391     if (NoteID.getDiagID() != 0)
392       Diag(OldLoc, NoteID);
393     return true;
394   }
395
396   // The MS extension throw(...) is compatible with itself.
397   if (OldEST == EST_MSAny && NewEST == EST_MSAny)
398     return false;
399
400   // It's also compatible with no spec.
401   if ((OldEST == EST_None && NewEST == EST_MSAny) ||
402       (OldEST == EST_MSAny && NewEST == EST_None))
403     return false;
404
405   // It's also compatible with noexcept(false).
406   if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
407     return false;
408   if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
409     return false;
410
411   // As described above, noexcept(false) matches no spec only for functions.
412   if (AllowNoexceptAllMatchWithNoSpec) {
413     if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
414       return false;
415     if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
416       return false;
417   }
418
419   // Any non-throwing specifications are compatible.
420   bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
421                         OldEST == EST_DynamicNone;
422   bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
423                         NewEST == EST_DynamicNone;
424   if (OldNonThrowing && NewNonThrowing)
425     return false;
426
427   // As a special compatibility feature, under C++0x we accept no spec and
428   // throw(std::bad_alloc) as equivalent for operator new and operator new[].
429   // This is because the implicit declaration changed, but old code would break.
430   if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
431     const FunctionProtoType *WithExceptions = 0;
432     if (OldEST == EST_None && NewEST == EST_Dynamic)
433       WithExceptions = New;
434     else if (OldEST == EST_Dynamic && NewEST == EST_None)
435       WithExceptions = Old;
436     if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
437       // One has no spec, the other throw(something). If that something is
438       // std::bad_alloc, all conditions are met.
439       QualType Exception = *WithExceptions->exception_begin();
440       if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
441         IdentifierInfo* Name = ExRecord->getIdentifier();
442         if (Name && Name->getName() == "bad_alloc") {
443           // It's called bad_alloc, but is it in std?
444           DeclContext* DC = ExRecord->getDeclContext();
445           DC = DC->getEnclosingNamespaceContext();
446           if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
447             IdentifierInfo* NSName = NS->getIdentifier();
448             DC = DC->getParent();
449             if (NSName && NSName->getName() == "std" &&
450                 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
451               return false;
452             }
453           }
454         }
455       }
456     }
457   }
458
459   // At this point, the only remaining valid case is two matching dynamic
460   // specifications. We return here unless both specifications are dynamic.
461   if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
462     if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
463         !New->hasExceptionSpec()) {
464       // The old type has an exception specification of some sort, but
465       // the new type does not.
466       *MissingExceptionSpecification = true;
467
468       if (MissingEmptyExceptionSpecification && OldNonThrowing) {
469         // The old type has a throw() or noexcept(true) exception specification
470         // and the new type has no exception specification, and the caller asked
471         // to handle this itself.
472         *MissingEmptyExceptionSpecification = true;
473       }
474
475       return true;
476     }
477
478     Diag(NewLoc, DiagID);
479     if (NoteID.getDiagID() != 0)
480       Diag(OldLoc, NoteID);
481     return true;
482   }
483
484   assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
485       "Exception compatibility logic error: non-dynamic spec slipped through.");
486
487   bool Success = true;
488   // Both have a dynamic exception spec. Collect the first set, then compare
489   // to the second.
490   llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
491   for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
492        E = Old->exception_end(); I != E; ++I)
493     OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
494
495   for (FunctionProtoType::exception_iterator I = New->exception_begin(),
496        E = New->exception_end(); I != E && Success; ++I) {
497     CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
498     if(OldTypes.count(TypePtr))
499       NewTypes.insert(TypePtr);
500     else
501       Success = false;
502   }
503
504   Success = Success && OldTypes.size() == NewTypes.size();
505
506   if (Success) {
507     return false;
508   }
509   Diag(NewLoc, DiagID);
510   if (NoteID.getDiagID() != 0)
511     Diag(OldLoc, NoteID);
512   return true;
513 }
514
515 /// CheckExceptionSpecSubset - Check whether the second function type's
516 /// exception specification is a subset (or equivalent) of the first function
517 /// type. This is used by override and pointer assignment checks.
518 bool Sema::CheckExceptionSpecSubset(
519     const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
520     const FunctionProtoType *Superset, SourceLocation SuperLoc,
521     const FunctionProtoType *Subset, SourceLocation SubLoc) {
522
523   // Just auto-succeed under -fno-exceptions.
524   if (!getLangOpts().CXXExceptions)
525     return false;
526
527   // FIXME: As usual, we could be more specific in our error messages, but
528   // that better waits until we've got types with source locations.
529
530   if (!SubLoc.isValid())
531     SubLoc = SuperLoc;
532
533   // Resolve the exception specifications, if needed.
534   Superset = ResolveExceptionSpec(SuperLoc, Superset);
535   if (!Superset)
536     return false;
537   Subset = ResolveExceptionSpec(SubLoc, Subset);
538   if (!Subset)
539     return false;
540
541   ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
542
543   // If superset contains everything, we're done.
544   if (SuperEST == EST_None || SuperEST == EST_MSAny)
545     return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
546
547   // If there are dependent noexcept specs, assume everything is fine. Unlike
548   // with the equivalency check, this is safe in this case, because we don't
549   // want to merge declarations. Checks after instantiation will catch any
550   // omissions we make here.
551   // We also shortcut checking if a noexcept expression was bad.
552
553   FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
554   if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
555       SuperNR == FunctionProtoType::NR_Dependent)
556     return false;
557
558   // Another case of the superset containing everything.
559   if (SuperNR == FunctionProtoType::NR_Throw)
560     return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
561
562   ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
563
564   assert(!isUnresolvedExceptionSpec(SuperEST) &&
565          !isUnresolvedExceptionSpec(SubEST) &&
566          "Shouldn't see unknown exception specifications here");
567
568   // It does not. If the subset contains everything, we've failed.
569   if (SubEST == EST_None || SubEST == EST_MSAny) {
570     Diag(SubLoc, DiagID);
571     if (NoteID.getDiagID() != 0)
572       Diag(SuperLoc, NoteID);
573     return true;
574   }
575
576   FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
577   if (SubNR == FunctionProtoType::NR_BadNoexcept ||
578       SubNR == FunctionProtoType::NR_Dependent)
579     return false;
580
581   // Another case of the subset containing everything.
582   if (SubNR == FunctionProtoType::NR_Throw) {
583     Diag(SubLoc, DiagID);
584     if (NoteID.getDiagID() != 0)
585       Diag(SuperLoc, NoteID);
586     return true;
587   }
588
589   // If the subset contains nothing, we're done.
590   if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
591     return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
592
593   // Otherwise, if the superset contains nothing, we've failed.
594   if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
595     Diag(SubLoc, DiagID);
596     if (NoteID.getDiagID() != 0)
597       Diag(SuperLoc, NoteID);
598     return true;
599   }
600
601   assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
602          "Exception spec subset: non-dynamic case slipped through.");
603
604   // Neither contains everything or nothing. Do a proper comparison.
605   for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
606        SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
607     // Take one type from the subset.
608     QualType CanonicalSubT = Context.getCanonicalType(*SubI);
609     // Unwrap pointers and references so that we can do checks within a class
610     // hierarchy. Don't unwrap member pointers; they don't have hierarchy
611     // conversions on the pointee.
612     bool SubIsPointer = false;
613     if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
614       CanonicalSubT = RefTy->getPointeeType();
615     if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
616       CanonicalSubT = PtrTy->getPointeeType();
617       SubIsPointer = true;
618     }
619     bool SubIsClass = CanonicalSubT->isRecordType();
620     CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
621
622     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
623                        /*DetectVirtual=*/false);
624
625     bool Contained = false;
626     // Make sure it's in the superset.
627     for (FunctionProtoType::exception_iterator SuperI =
628            Superset->exception_begin(), SuperE = Superset->exception_end();
629          SuperI != SuperE; ++SuperI) {
630       QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
631       // SubT must be SuperT or derived from it, or pointer or reference to
632       // such types.
633       if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
634         CanonicalSuperT = RefTy->getPointeeType();
635       if (SubIsPointer) {
636         if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
637           CanonicalSuperT = PtrTy->getPointeeType();
638         else {
639           continue;
640         }
641       }
642       CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
643       // If the types are the same, move on to the next type in the subset.
644       if (CanonicalSubT == CanonicalSuperT) {
645         Contained = true;
646         break;
647       }
648
649       // Otherwise we need to check the inheritance.
650       if (!SubIsClass || !CanonicalSuperT->isRecordType())
651         continue;
652
653       Paths.clear();
654       if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
655         continue;
656
657       if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
658         continue;
659
660       // Do this check from a context without privileges.
661       switch (CheckBaseClassAccess(SourceLocation(),
662                                    CanonicalSuperT, CanonicalSubT,
663                                    Paths.front(),
664                                    /*Diagnostic*/ 0,
665                                    /*ForceCheck*/ true,
666                                    /*ForceUnprivileged*/ true)) {
667       case AR_accessible: break;
668       case AR_inaccessible: continue;
669       case AR_dependent:
670         llvm_unreachable("access check dependent for unprivileged context");
671       case AR_delayed:
672         llvm_unreachable("access check delayed in non-declaration");
673       }
674
675       Contained = true;
676       break;
677     }
678     if (!Contained) {
679       Diag(SubLoc, DiagID);
680       if (NoteID.getDiagID() != 0)
681         Diag(SuperLoc, NoteID);
682       return true;
683     }
684   }
685   // We've run half the gauntlet.
686   return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
687 }
688
689 static bool CheckSpecForTypesEquivalent(Sema &S,
690     const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
691     QualType Target, SourceLocation TargetLoc,
692     QualType Source, SourceLocation SourceLoc)
693 {
694   const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
695   if (!TFunc)
696     return false;
697   const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
698   if (!SFunc)
699     return false;
700
701   return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
702                                         SFunc, SourceLoc);
703 }
704
705 /// CheckParamExceptionSpec - Check if the parameter and return types of the
706 /// two functions have equivalent exception specs. This is part of the
707 /// assignment and override compatibility check. We do not check the parameters
708 /// of parameter function pointers recursively, as no sane programmer would
709 /// even be able to write such a function type.
710 bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
711     const FunctionProtoType *Target, SourceLocation TargetLoc,
712     const FunctionProtoType *Source, SourceLocation SourceLoc)
713 {
714   if (CheckSpecForTypesEquivalent(*this,
715                            PDiag(diag::err_deep_exception_specs_differ) << 0, 
716                                   PDiag(),
717                                   Target->getResultType(), TargetLoc,
718                                   Source->getResultType(), SourceLoc))
719     return true;
720
721   // We shouldn't even be testing this unless the arguments are otherwise
722   // compatible.
723   assert(Target->getNumArgs() == Source->getNumArgs() &&
724          "Functions have different argument counts.");
725   for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
726     if (CheckSpecForTypesEquivalent(*this,
727                            PDiag(diag::err_deep_exception_specs_differ) << 1, 
728                                     PDiag(),
729                                     Target->getArgType(i), TargetLoc,
730                                     Source->getArgType(i), SourceLoc))
731       return true;
732   }
733   return false;
734 }
735
736 bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
737 {
738   // First we check for applicability.
739   // Target type must be a function, function pointer or function reference.
740   const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
741   if (!ToFunc)
742     return false;
743
744   // SourceType must be a function or function pointer.
745   const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
746   if (!FromFunc)
747     return false;
748
749   // Now we've got the correct types on both sides, check their compatibility.
750   // This means that the source of the conversion can only throw a subset of
751   // the exceptions of the target, and any exception specs on arguments or
752   // return types must be equivalent.
753   return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
754                                   PDiag(), ToFunc, 
755                                   From->getSourceRange().getBegin(),
756                                   FromFunc, SourceLocation());
757 }
758
759 bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
760                                                 const CXXMethodDecl *Old) {
761   if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
762     // Don't check uninstantiated template destructors at all. We can only
763     // synthesize correct specs after the template is instantiated.
764     if (New->getParent()->isDependentType())
765       return false;
766     if (New->getParent()->isBeingDefined()) {
767       // The destructor might be updated once the definition is finished. So
768       // remember it and check later.
769       DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
770         cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
771       return false;
772     }
773   }
774   unsigned DiagID = diag::err_override_exception_spec;
775   if (getLangOpts().MicrosoftExt)
776     DiagID = diag::warn_override_exception_spec;
777   return CheckExceptionSpecSubset(PDiag(DiagID),
778                                   PDiag(diag::note_overridden_virtual_function),
779                                   Old->getType()->getAs<FunctionProtoType>(),
780                                   Old->getLocation(),
781                                   New->getType()->getAs<FunctionProtoType>(),
782                                   New->getLocation());
783 }
784
785 static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
786   Expr *E = const_cast<Expr*>(CE);
787   CanThrowResult R = CT_Cannot;
788   for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
789     R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
790   return R;
791 }
792
793 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
794   assert(D && "Expected decl");
795
796   // See if we can get a function type from the decl somehow.
797   const ValueDecl *VD = dyn_cast<ValueDecl>(D);
798   if (!VD) // If we have no clue what we're calling, assume the worst.
799     return CT_Can;
800
801   // As an extension, we assume that __attribute__((nothrow)) functions don't
802   // throw.
803   if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
804     return CT_Cannot;
805
806   QualType T = VD->getType();
807   const FunctionProtoType *FT;
808   if ((FT = T->getAs<FunctionProtoType>())) {
809   } else if (const PointerType *PT = T->getAs<PointerType>())
810     FT = PT->getPointeeType()->getAs<FunctionProtoType>();
811   else if (const ReferenceType *RT = T->getAs<ReferenceType>())
812     FT = RT->getPointeeType()->getAs<FunctionProtoType>();
813   else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
814     FT = MT->getPointeeType()->getAs<FunctionProtoType>();
815   else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
816     FT = BT->getPointeeType()->getAs<FunctionProtoType>();
817
818   if (!FT)
819     return CT_Can;
820
821   FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
822   if (!FT)
823     return CT_Can;
824
825   return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
826 }
827
828 static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
829   if (DC->isTypeDependent())
830     return CT_Dependent;
831
832   if (!DC->getTypeAsWritten()->isReferenceType())
833     return CT_Cannot;
834
835   if (DC->getSubExpr()->isTypeDependent())
836     return CT_Dependent;
837
838   return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
839 }
840
841 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
842   if (DC->isTypeOperand())
843     return CT_Cannot;
844
845   Expr *Op = DC->getExprOperand();
846   if (Op->isTypeDependent())
847     return CT_Dependent;
848
849   const RecordType *RT = Op->getType()->getAs<RecordType>();
850   if (!RT)
851     return CT_Cannot;
852
853   if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
854     return CT_Cannot;
855
856   if (Op->Classify(S.Context).isPRValue())
857     return CT_Cannot;
858
859   return CT_Can;
860 }
861
862 CanThrowResult Sema::canThrow(const Expr *E) {
863   // C++ [expr.unary.noexcept]p3:
864   //   [Can throw] if in a potentially-evaluated context the expression would
865   //   contain:
866   switch (E->getStmtClass()) {
867   case Expr::CXXThrowExprClass:
868     //   - a potentially evaluated throw-expression
869     return CT_Can;
870
871   case Expr::CXXDynamicCastExprClass: {
872     //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
873     //     where T is a reference type, that requires a run-time check
874     CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
875     if (CT == CT_Can)
876       return CT;
877     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
878   }
879
880   case Expr::CXXTypeidExprClass:
881     //   - a potentially evaluated typeid expression applied to a glvalue
882     //     expression whose type is a polymorphic class type
883     return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
884
885     //   - a potentially evaluated call to a function, member function, function
886     //     pointer, or member function pointer that does not have a non-throwing
887     //     exception-specification
888   case Expr::CallExprClass:
889   case Expr::CXXMemberCallExprClass:
890   case Expr::CXXOperatorCallExprClass:
891   case Expr::UserDefinedLiteralClass: {
892     const CallExpr *CE = cast<CallExpr>(E);
893     CanThrowResult CT;
894     if (E->isTypeDependent())
895       CT = CT_Dependent;
896     else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
897       CT = CT_Cannot;
898     else if (CE->getCalleeDecl())
899       CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
900     else
901       CT = CT_Can;
902     if (CT == CT_Can)
903       return CT;
904     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
905   }
906
907   case Expr::CXXConstructExprClass:
908   case Expr::CXXTemporaryObjectExprClass: {
909     CanThrowResult CT = canCalleeThrow(*this, E,
910         cast<CXXConstructExpr>(E)->getConstructor());
911     if (CT == CT_Can)
912       return CT;
913     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
914   }
915
916   case Expr::LambdaExprClass: {
917     const LambdaExpr *Lambda = cast<LambdaExpr>(E);
918     CanThrowResult CT = CT_Cannot;
919     for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
920                                         CapEnd = Lambda->capture_init_end();
921          Cap != CapEnd; ++Cap)
922       CT = mergeCanThrow(CT, canThrow(*Cap));
923     return CT;
924   }
925
926   case Expr::CXXNewExprClass: {
927     CanThrowResult CT;
928     if (E->isTypeDependent())
929       CT = CT_Dependent;
930     else
931       CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
932     if (CT == CT_Can)
933       return CT;
934     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
935   }
936
937   case Expr::CXXDeleteExprClass: {
938     CanThrowResult CT;
939     QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
940     if (DTy.isNull() || DTy->isDependentType()) {
941       CT = CT_Dependent;
942     } else {
943       CT = canCalleeThrow(*this, E,
944                           cast<CXXDeleteExpr>(E)->getOperatorDelete());
945       if (const RecordType *RT = DTy->getAs<RecordType>()) {
946         const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
947         const CXXDestructorDecl *DD = RD->getDestructor();
948         if (DD)
949           CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
950       }
951       if (CT == CT_Can)
952         return CT;
953     }
954     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
955   }
956
957   case Expr::CXXBindTemporaryExprClass: {
958     // The bound temporary has to be destroyed again, which might throw.
959     CanThrowResult CT = canCalleeThrow(*this, E,
960       cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
961     if (CT == CT_Can)
962       return CT;
963     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
964   }
965
966     // ObjC message sends are like function calls, but never have exception
967     // specs.
968   case Expr::ObjCMessageExprClass:
969   case Expr::ObjCPropertyRefExprClass:
970   case Expr::ObjCSubscriptRefExprClass:
971     return CT_Can;
972
973     // All the ObjC literals that are implemented as calls are
974     // potentially throwing unless we decide to close off that
975     // possibility.
976   case Expr::ObjCArrayLiteralClass:
977   case Expr::ObjCDictionaryLiteralClass:
978   case Expr::ObjCBoxedExprClass:
979     return CT_Can;
980
981     // Many other things have subexpressions, so we have to test those.
982     // Some are simple:
983   case Expr::ConditionalOperatorClass:
984   case Expr::CompoundLiteralExprClass:
985   case Expr::CXXConstCastExprClass:
986   case Expr::CXXReinterpretCastExprClass:
987   case Expr::CXXStdInitializerListExprClass:
988   case Expr::DesignatedInitExprClass:
989   case Expr::ExprWithCleanupsClass:
990   case Expr::ExtVectorElementExprClass:
991   case Expr::InitListExprClass:
992   case Expr::MemberExprClass:
993   case Expr::ObjCIsaExprClass:
994   case Expr::ObjCIvarRefExprClass:
995   case Expr::ParenExprClass:
996   case Expr::ParenListExprClass:
997   case Expr::ShuffleVectorExprClass:
998   case Expr::ConvertVectorExprClass:
999   case Expr::VAArgExprClass:
1000     return canSubExprsThrow(*this, E);
1001
1002     // Some might be dependent for other reasons.
1003   case Expr::ArraySubscriptExprClass:
1004   case Expr::BinaryOperatorClass:
1005   case Expr::CompoundAssignOperatorClass:
1006   case Expr::CStyleCastExprClass:
1007   case Expr::CXXStaticCastExprClass:
1008   case Expr::CXXFunctionalCastExprClass:
1009   case Expr::ImplicitCastExprClass:
1010   case Expr::MaterializeTemporaryExprClass:
1011   case Expr::UnaryOperatorClass: {
1012     CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1013     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1014   }
1015
1016     // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1017   case Expr::StmtExprClass:
1018     return CT_Can;
1019
1020   case Expr::CXXDefaultArgExprClass:
1021     return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1022
1023   case Expr::CXXDefaultInitExprClass:
1024     return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1025
1026   case Expr::ChooseExprClass:
1027     if (E->isTypeDependent() || E->isValueDependent())
1028       return CT_Dependent;
1029     return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1030
1031   case Expr::GenericSelectionExprClass:
1032     if (cast<GenericSelectionExpr>(E)->isResultDependent())
1033       return CT_Dependent;
1034     return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1035
1036     // Some expressions are always dependent.
1037   case Expr::CXXDependentScopeMemberExprClass:
1038   case Expr::CXXUnresolvedConstructExprClass:
1039   case Expr::DependentScopeDeclRefExprClass:
1040     return CT_Dependent;
1041
1042   case Expr::AsTypeExprClass:
1043   case Expr::BinaryConditionalOperatorClass:
1044   case Expr::BlockExprClass:
1045   case Expr::CUDAKernelCallExprClass:
1046   case Expr::DeclRefExprClass:
1047   case Expr::ObjCBridgedCastExprClass:
1048   case Expr::ObjCIndirectCopyRestoreExprClass:
1049   case Expr::ObjCProtocolExprClass:
1050   case Expr::ObjCSelectorExprClass:
1051   case Expr::OffsetOfExprClass:
1052   case Expr::PackExpansionExprClass:
1053   case Expr::PseudoObjectExprClass:
1054   case Expr::SubstNonTypeTemplateParmExprClass:
1055   case Expr::SubstNonTypeTemplateParmPackExprClass:
1056   case Expr::FunctionParmPackExprClass:
1057   case Expr::UnaryExprOrTypeTraitExprClass:
1058   case Expr::UnresolvedLookupExprClass:
1059   case Expr::UnresolvedMemberExprClass:
1060     // FIXME: Can any of the above throw?  If so, when?
1061     return CT_Cannot;
1062
1063   case Expr::AddrLabelExprClass:
1064   case Expr::ArrayTypeTraitExprClass:
1065   case Expr::AtomicExprClass:
1066   case Expr::BinaryTypeTraitExprClass:
1067   case Expr::TypeTraitExprClass:
1068   case Expr::CXXBoolLiteralExprClass:
1069   case Expr::CXXNoexceptExprClass:
1070   case Expr::CXXNullPtrLiteralExprClass:
1071   case Expr::CXXPseudoDestructorExprClass:
1072   case Expr::CXXScalarValueInitExprClass:
1073   case Expr::CXXThisExprClass:
1074   case Expr::CXXUuidofExprClass:
1075   case Expr::CharacterLiteralClass:
1076   case Expr::ExpressionTraitExprClass:
1077   case Expr::FloatingLiteralClass:
1078   case Expr::GNUNullExprClass:
1079   case Expr::ImaginaryLiteralClass:
1080   case Expr::ImplicitValueInitExprClass:
1081   case Expr::IntegerLiteralClass:
1082   case Expr::ObjCEncodeExprClass:
1083   case Expr::ObjCStringLiteralClass:
1084   case Expr::ObjCBoolLiteralExprClass:
1085   case Expr::OpaqueValueExprClass:
1086   case Expr::PredefinedExprClass:
1087   case Expr::SizeOfPackExprClass:
1088   case Expr::StringLiteralClass:
1089   case Expr::UnaryTypeTraitExprClass:
1090     // These expressions can never throw.
1091     return CT_Cannot;
1092
1093   case Expr::MSPropertyRefExprClass:
1094     llvm_unreachable("Invalid class for expression");
1095
1096 #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1097 #define STMT_RANGE(Base, First, Last)
1098 #define LAST_STMT_RANGE(BASE, FIRST, LAST)
1099 #define EXPR(CLASS, PARENT)
1100 #define ABSTRACT_STMT(STMT)
1101 #include "clang/AST/StmtNodes.inc"
1102   case Expr::NoStmtClass:
1103     llvm_unreachable("Invalid class for expression");
1104   }
1105   llvm_unreachable("Bogus StmtClass");
1106 }
1107
1108 } // end namespace clang