blob: 9be411b552adf0a999a9704bfb754f3fb3825c83 [file] [log] [blame]
Sebastian Redldced2262009-10-11 09:03:14 +00001//===--- 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 "Sema.h"
Sebastian Redldced2262009-10-11 09:03:14 +000015#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
Douglas Gregore13ad832010-02-12 07:32:17 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/SourceManager.h"
Sebastian Redldced2262009-10-11 09:03:14 +000020#include "llvm/ADT/SmallPtrSet.h"
21
22namespace clang {
23
24static const FunctionProtoType *GetUnderlyingFunction(QualType T)
25{
26 if (const PointerType *PtrTy = T->getAs<PointerType>())
27 T = PtrTy->getPointeeType();
28 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
29 T = RefTy->getPointeeType();
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +000030 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
31 T = MPTy->getPointeeType();
Sebastian Redldced2262009-10-11 09:03:14 +000032 return T->getAs<FunctionProtoType>();
33}
34
35/// CheckSpecifiedExceptionType - Check if the given type is valid in an
36/// exception specification. Incomplete types, or pointers to incomplete types
37/// other than void are not allowed.
38bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
Sebastian Redldced2262009-10-11 09:03:14 +000039
Douglas Gregor0966f352009-12-10 18:13:52 +000040 // This check (and the similar one below) deals with issue 437, that changes
41 // C++ 9.2p2 this way:
42 // Within the class member-specification, the class is regarded as complete
43 // within function bodies, default arguments, exception-specifications, and
44 // constructor ctor-initializers (including such things in nested classes).
45 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
46 return false;
47
Sebastian Redldced2262009-10-11 09:03:14 +000048 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
49 // an incomplete type.
Sebastian Redl491b84c2009-10-14 14:59:48 +000050 if (RequireCompleteType(Range.getBegin(), T,
51 PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/0 << Range))
52 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000053
54 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
55 // an incomplete type a pointer or reference to an incomplete type, other
56 // than (cv) void*.
57 int kind;
58 if (const PointerType* IT = T->getAs<PointerType>()) {
59 T = IT->getPointeeType();
60 kind = 1;
61 } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
62 T = IT->getPointeeType();
63 kind = 2;
64 } else
65 return false;
66
Douglas Gregor0966f352009-12-10 18:13:52 +000067 // Again as before
68 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
69 return false;
70
Sebastian Redl491b84c2009-10-14 14:59:48 +000071 if (!T->isVoidType() && RequireCompleteType(Range.getBegin(), T,
Douglas Gregor0966f352009-12-10 18:13:52 +000072 PDiag(diag::err_incomplete_in_exception_spec) << kind << Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000073 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000074
75 return false;
76}
77
78/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
79/// to member to a function with an exception specification. This means that
80/// it is invalid to add another level of indirection.
81bool Sema::CheckDistantExceptionSpec(QualType T) {
82 if (const PointerType *PT = T->getAs<PointerType>())
83 T = PT->getPointeeType();
84 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
85 T = PT->getPointeeType();
86 else
87 return false;
88
89 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
90 if (!FnT)
91 return false;
92
93 return FnT->hasExceptionSpec();
94}
95
Douglas Gregore13ad832010-02-12 07:32:17 +000096bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
97 bool MissingEmptyExceptionSpecification = false;
98 if (!CheckEquivalentExceptionSpec(diag::err_mismatched_exception_spec,
99 diag::note_previous_declaration,
100 Old->getType()->getAs<FunctionProtoType>(),
101 Old->getLocation(),
102 New->getType()->getAs<FunctionProtoType>(),
103 New->getLocation(),
104 &MissingEmptyExceptionSpecification))
105 return false;
106
107 // The failure was something other than an empty exception
108 // specification; return an error.
109 if (!MissingEmptyExceptionSpecification)
110 return true;
111
112 // The new function declaration is only missing an empty exception
113 // specification "throw()". If the throw() specification came from a
114 // function in a system header that has C linkage, just add an empty
115 // exception specification to the "new" declaration. This is an
116 // egregious workaround for glibc, which adds throw() specifications
117 // to many libc functions as an optimization. Unfortunately, that
118 // optimization isn't permitted by the C++ standard, so we're forced
119 // to work around it here.
120 if (isa<FunctionProtoType>(New->getType()) &&
121 Context.getSourceManager().isInSystemHeader(Old->getLocation()) &&
122 Old->isExternC()) {
123 const FunctionProtoType *NewProto
124 = cast<FunctionProtoType>(New->getType());
125 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
126 NewProto->arg_type_begin(),
127 NewProto->getNumArgs(),
128 NewProto->isVariadic(),
129 NewProto->getTypeQuals(),
130 true, false, 0, 0,
131 NewProto->getNoReturnAttr(),
132 NewProto->getCallConv());
133 New->setType(NewType);
134 return false;
135 }
136
137 Diag(New->getLocation(), diag::err_mismatched_exception_spec);
138 Diag(Old->getLocation(), diag::note_previous_declaration);
139 return true;
140}
141
Sebastian Redldced2262009-10-11 09:03:14 +0000142/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
143/// exception specifications. Exception specifications are equivalent if
144/// they allow exactly the same set of exception types. It does not matter how
145/// that is achieved. See C++ [except.spec]p2.
146bool Sema::CheckEquivalentExceptionSpec(
147 const FunctionProtoType *Old, SourceLocation OldLoc,
148 const FunctionProtoType *New, SourceLocation NewLoc) {
149 return CheckEquivalentExceptionSpec(diag::err_mismatched_exception_spec,
150 diag::note_previous_declaration,
151 Old, OldLoc, New, NewLoc);
152}
153
154/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
155/// exception specifications. Exception specifications are equivalent if
156/// they allow exactly the same set of exception types. It does not matter how
157/// that is achieved. See C++ [except.spec]p2.
158bool Sema::CheckEquivalentExceptionSpec(
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000159 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000160 const FunctionProtoType *Old, SourceLocation OldLoc,
Douglas Gregore13ad832010-02-12 07:32:17 +0000161 const FunctionProtoType *New, SourceLocation NewLoc,
162 bool *MissingEmptyExceptionSpecification) {
163 if (MissingEmptyExceptionSpecification)
164 *MissingEmptyExceptionSpecification = false;
165
Sebastian Redldced2262009-10-11 09:03:14 +0000166 bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec();
167 bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec();
168 if (OldAny && NewAny)
169 return false;
170 if (OldAny || NewAny) {
Douglas Gregore13ad832010-02-12 07:32:17 +0000171 if (MissingEmptyExceptionSpecification && Old->hasExceptionSpec() &&
172 !Old->hasAnyExceptionSpec() && Old->getNumExceptions() == 0 &&
173 !New->hasExceptionSpec()) {
174 // The old type has a throw() exception specification and the
175 // new type has no exception specification, and the caller asked
176 // to handle this itself.
177 *MissingEmptyExceptionSpecification = true;
178 return true;
179 }
180
Sebastian Redldced2262009-10-11 09:03:14 +0000181 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000182 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000183 Diag(OldLoc, NoteID);
184 return true;
185 }
186
187 bool Success = true;
188 // Both have a definite exception spec. Collect the first set, then compare
189 // to the second.
Sebastian Redl1219d152009-10-14 15:06:25 +0000190 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redldced2262009-10-11 09:03:14 +0000191 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
192 E = Old->exception_end(); I != E; ++I)
Sebastian Redl1219d152009-10-14 15:06:25 +0000193 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redldced2262009-10-11 09:03:14 +0000194
195 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl5db4d902009-10-11 09:11:23 +0000196 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl1219d152009-10-14 15:06:25 +0000197 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl5db4d902009-10-11 09:11:23 +0000198 if(OldTypes.count(TypePtr))
199 NewTypes.insert(TypePtr);
200 else
201 Success = false;
202 }
Sebastian Redldced2262009-10-11 09:03:14 +0000203
Sebastian Redl5db4d902009-10-11 09:11:23 +0000204 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redldced2262009-10-11 09:03:14 +0000205
206 if (Success) {
207 return false;
208 }
209 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000210 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000211 Diag(OldLoc, NoteID);
212 return true;
213}
214
215/// CheckExceptionSpecSubset - Check whether the second function type's
216/// exception specification is a subset (or equivalent) of the first function
217/// type. This is used by override and pointer assignment checks.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000218bool Sema::CheckExceptionSpecSubset(
219 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000220 const FunctionProtoType *Superset, SourceLocation SuperLoc,
221 const FunctionProtoType *Subset, SourceLocation SubLoc) {
222 // FIXME: As usual, we could be more specific in our error messages, but
223 // that better waits until we've got types with source locations.
224
225 if (!SubLoc.isValid())
226 SubLoc = SuperLoc;
227
228 // If superset contains everything, we're done.
229 if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec())
230 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
231
232 // It does not. If the subset contains everything, we've failed.
233 if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) {
234 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000235 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000236 Diag(SuperLoc, NoteID);
237 return true;
238 }
239
240 // Neither contains everything. Do a proper comparison.
241 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
242 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
243 // Take one type from the subset.
244 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +0000245 // Unwrap pointers and references so that we can do checks within a class
246 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
247 // conversions on the pointee.
Sebastian Redldced2262009-10-11 09:03:14 +0000248 bool SubIsPointer = false;
249 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
250 CanonicalSubT = RefTy->getPointeeType();
251 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
252 CanonicalSubT = PtrTy->getPointeeType();
253 SubIsPointer = true;
254 }
255 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregora4923eb2009-11-16 21:35:15 +0000256 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000257
258 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
259 /*DetectVirtual=*/false);
260
261 bool Contained = false;
262 // Make sure it's in the superset.
263 for (FunctionProtoType::exception_iterator SuperI =
264 Superset->exception_begin(), SuperE = Superset->exception_end();
265 SuperI != SuperE; ++SuperI) {
266 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
267 // SubT must be SuperT or derived from it, or pointer or reference to
268 // such types.
269 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
270 CanonicalSuperT = RefTy->getPointeeType();
271 if (SubIsPointer) {
272 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
273 CanonicalSuperT = PtrTy->getPointeeType();
274 else {
275 continue;
276 }
277 }
Douglas Gregora4923eb2009-11-16 21:35:15 +0000278 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000279 // If the types are the same, move on to the next type in the subset.
280 if (CanonicalSubT == CanonicalSuperT) {
281 Contained = true;
282 break;
283 }
284
285 // Otherwise we need to check the inheritance.
286 if (!SubIsClass || !CanonicalSuperT->isRecordType())
287 continue;
288
289 Paths.clear();
290 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
291 continue;
292
293 if (Paths.isAmbiguous(CanonicalSuperT))
294 continue;
295
John McCall6b2accb2010-02-10 09:31:12 +0000296 // Do this check from a context without privileges.
297 switch (CheckBaseClassAccess(SourceLocation(), false,
298 CanonicalSuperT, CanonicalSubT,
299 Paths.front(),
300 /*ForceCheck*/ true,
301 /*ForceUnprivileged*/ true,
302 ADK_quiet)) {
303 case AR_accessible: break;
304 case AR_inaccessible: continue;
305 case AR_dependent:
306 llvm_unreachable("access check dependent for unprivileged context");
307 break;
308 case AR_delayed:
309 llvm_unreachable("access check delayed in non-declaration");
310 break;
311 }
Sebastian Redldced2262009-10-11 09:03:14 +0000312
313 Contained = true;
314 break;
315 }
316 if (!Contained) {
317 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000318 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000319 Diag(SuperLoc, NoteID);
320 return true;
321 }
322 }
323 // We've run half the gauntlet.
324 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
325}
326
327static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000328 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000329 QualType Target, SourceLocation TargetLoc,
330 QualType Source, SourceLocation SourceLoc)
331{
332 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
333 if (!TFunc)
334 return false;
335 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
336 if (!SFunc)
337 return false;
338
339 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
340 SFunc, SourceLoc);
341}
342
343/// CheckParamExceptionSpec - Check if the parameter and return types of the
344/// two functions have equivalent exception specs. This is part of the
345/// assignment and override compatibility check. We do not check the parameters
346/// of parameter function pointers recursively, as no sane programmer would
347/// even be able to write such a function type.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000348bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000349 const FunctionProtoType *Target, SourceLocation TargetLoc,
350 const FunctionProtoType *Source, SourceLocation SourceLoc)
351{
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000352 if (CheckSpecForTypesEquivalent(*this,
353 PDiag(diag::err_deep_exception_specs_differ) << 0, 0,
Sebastian Redldced2262009-10-11 09:03:14 +0000354 Target->getResultType(), TargetLoc,
355 Source->getResultType(), SourceLoc))
356 return true;
357
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000358 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redldced2262009-10-11 09:03:14 +0000359 // compatible.
360 assert(Target->getNumArgs() == Source->getNumArgs() &&
361 "Functions have different argument counts.");
362 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000363 if (CheckSpecForTypesEquivalent(*this,
364 PDiag(diag::err_deep_exception_specs_differ) << 1, 0,
Sebastian Redldced2262009-10-11 09:03:14 +0000365 Target->getArgType(i), TargetLoc,
366 Source->getArgType(i), SourceLoc))
367 return true;
368 }
369 return false;
370}
371
372bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
373{
374 // First we check for applicability.
375 // Target type must be a function, function pointer or function reference.
376 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
377 if (!ToFunc)
378 return false;
379
380 // SourceType must be a function or function pointer.
381 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
382 if (!FromFunc)
383 return false;
384
385 // Now we've got the correct types on both sides, check their compatibility.
386 // This means that the source of the conversion can only throw a subset of
387 // the exceptions of the target, and any exception specs on arguments or
388 // return types must be equivalent.
389 return CheckExceptionSpecSubset(diag::err_incompatible_exception_specs,
390 0, ToFunc, From->getSourceRange().getBegin(),
391 FromFunc, SourceLocation());
392}
393
394bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
395 const CXXMethodDecl *Old) {
396 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
397 diag::note_overridden_virtual_function,
398 Old->getType()->getAs<FunctionProtoType>(),
399 Old->getLocation(),
400 New->getType()->getAs<FunctionProtoType>(),
401 New->getLocation());
402}
403
404} // end namespace clang