blob: 08c4f50091f7ec8495f1750926a427122755e358 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Richard Smith7447af42013-03-26 01:15:19 +000045/// \brief Handle the result of the special case name lookup for inheriting
46/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
John McCallba7bf592010-08-24 05:47:05 +000083ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000085 SourceLocation NameLoc,
86 Scope *S, CXXScopeSpec &SS,
87 ParsedType ObjectTypePtr,
88 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000089 // Determine where to perform name lookup.
90
91 // FIXME: This area of the standard is very messy, and the current
92 // wording is rather unclear about which scopes we search for the
93 // destructor name; see core issues 399 and 555. Issue 399 in
94 // particular shows where the current description of destructor name
95 // lookup is completely out of line with existing practice, e.g.,
96 // this appears to be ill-formed:
97 //
98 // namespace N {
99 // template <typename T> struct S {
100 // ~S();
101 // };
102 // }
103 //
104 // void f(N::S<int>* s) {
105 // s->N::S<int>::~S();
106 // }
107 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000108 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000109 // For this reason, we're currently only doing the C++03 version of this
110 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000111 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000112 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000113 bool isDependent = false;
114 bool LookInScope = false;
115
Richard Smith64e033f2015-01-15 00:48:52 +0000116 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000117 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000118
Douglas Gregorfe17d252010-02-16 19:09:40 +0000119 // If we have an object type, it's because we are in a
120 // pseudo-destructor-expression or a member access expression, and
121 // we know what type we're looking for.
122 if (ObjectTypePtr)
123 SearchType = GetTypeFromParser(ObjectTypePtr);
124
125 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000126 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127
Douglas Gregor46841e12010-02-23 00:15:22 +0000128 bool AlreadySearched = false;
129 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000130 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000132 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000133 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000134 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000135 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000136 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000137 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000139 // Here, we determine whether the code below is permitted to look at the
140 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000141 DeclContext *DC = computeDeclContext(SS, EnteringContext);
142 if (DC && DC->isFileContext()) {
143 AlreadySearched = true;
144 LookupCtx = DC;
145 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000146 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000147 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000148 LookInScope = true;
149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Sebastian Redla771d222010-07-07 23:17:38 +0000151 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000152 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000153 if (AlreadySearched) {
154 // Nothing left to do.
155 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
156 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000157 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000158 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
159 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000160 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161 LookupCtx = computeDeclContext(SearchType);
162 isDependent = SearchType->isDependentType();
163 } else {
164 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000165 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000167 } else if (ObjectTypePtr) {
168 // C++ [basic.lookup.classref]p3:
169 // If the unqualified-id is ~type-name, the type-name is looked up
170 // in the context of the entire postfix-expression. If the type T
171 // of the object expression is of a class type C, the type-name is
172 // also looked up in the scope of class C. At least one of the
173 // lookups shall find a name that refers to (possibly
174 // cv-qualified) T.
175 LookupCtx = computeDeclContext(SearchType);
176 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000177 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000178 "Caller should have completed object type");
179
180 LookInScope = true;
181 } else {
182 // Perform lookup into the current scope (only).
183 LookInScope = true;
184 }
185
Craig Topperc3ec1492014-05-26 06:22:03 +0000186 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000187 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
188 for (unsigned Step = 0; Step != 2; ++Step) {
189 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000190 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000191 // we're allowed to look there).
192 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000193 if (Step == 0 && LookupCtx) {
194 if (RequireCompleteDeclContext(SS, LookupCtx))
195 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000196 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000197 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000199 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000200 continue;
John McCallcb731542017-06-11 20:33:00 +0000201 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 // FIXME: Should we be suppressing ambiguities here?
204 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000205 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
208 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000209 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210
211 if (SearchType.isNull() || SearchType->isDependentType() ||
212 Context.hasSameUnqualifiedType(T, SearchType)) {
213 // We found our type!
214
Richard Smithc278c002014-01-22 00:30:17 +0000215 return CreateParsedType(T,
216 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000218
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000219 if (!SearchType.isNull())
220 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000221 }
222
223 // If the name that we found is a class template name, and it is
224 // the same name as the template name in the last part of the
225 // nested-name-specifier (if present) or the object type, then
226 // this is the destructor for that class.
227 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000228 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000229 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
230 QualType MemberOfType;
231 if (SS.isSet()) {
232 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
233 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
235 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000236 }
237 }
238 if (MemberOfType.isNull())
239 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregorfe17d252010-02-16 19:09:40 +0000241 if (MemberOfType.isNull())
242 continue;
243
244 // We're referring into a class template specialization. If the
245 // class template we found is the same as the template being
246 // specialized, we found what we are looking for.
247 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
248 if (ClassTemplateSpecializationDecl *Spec
249 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
250 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
251 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000252 return CreateParsedType(
253 MemberOfType,
254 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000255 }
256
257 continue;
258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259
Douglas Gregorfe17d252010-02-16 19:09:40 +0000260 // We're referring to an unresolved class template
261 // specialization. Determine whether we class template we found
262 // is the same as the template being specialized or, if we don't
263 // know which template is being specialized, that it at least
264 // has the same name.
265 if (const TemplateSpecializationType *SpecType
266 = MemberOfType->getAs<TemplateSpecializationType>()) {
267 TemplateName SpecName = SpecType->getTemplateName();
268
269 // The class template we found is the same template being
270 // specialized.
271 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
272 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000273 return CreateParsedType(
274 MemberOfType,
275 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000276
277 continue;
278 }
279
280 // The class template we found has the same name as the
281 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000283 = SpecName.getAsDependentTemplateName()) {
284 if (DepTemplate->isIdentifier() &&
285 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000286 return CreateParsedType(
287 MemberOfType,
288 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000289
290 continue;
291 }
292 }
293 }
294 }
295
296 if (isDependent) {
297 // We didn't find our type, but that's okay: it's dependent
298 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000299
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000300 // FIXME: What if we have no nested-name-specifier?
301 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
302 SS.getWithLocInContext(Context),
303 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000304 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000305 }
306
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000307 if (NonMatchingTypeDecl) {
308 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
309 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
310 << T << SearchType;
311 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
312 << T;
313 } else if (ObjectTypePtr)
314 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000315 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000316 else {
317 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
318 diag::err_destructor_class_name);
319 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000320 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000321 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
322 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
323 Class->getNameAsString());
324 }
325 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000326
David Blaikieefdccaa2016-01-15 23:43:34 +0000327 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000328}
329
Richard Smithef2cd8f2017-02-08 20:39:08 +0000330ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
331 ParsedType ObjectType) {
332 if (DS.getTypeSpecType() == DeclSpec::TST_error)
333 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000334
Richard Smithef2cd8f2017-02-08 20:39:08 +0000335 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
336 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
337 return nullptr;
338 }
339
340 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
341 "unexpected type in getDestructorType");
342 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
343
344 // If we know the type of the object, check that the correct destructor
345 // type was named now; we can give better diagnostics this way.
346 QualType SearchType = GetTypeFromParser(ObjectType);
347 if (!SearchType.isNull() && !SearchType->isDependentType() &&
348 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000349 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000351 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000352 }
353
354 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000355}
356
Richard Smithd091dc12013-12-05 00:58:33 +0000357bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
358 const UnqualifiedId &Name) {
359 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
360
361 if (!SS.isValid())
362 return false;
363
364 switch (SS.getScopeRep()->getKind()) {
365 case NestedNameSpecifier::Identifier:
366 case NestedNameSpecifier::TypeSpec:
367 case NestedNameSpecifier::TypeSpecWithTemplate:
368 // Per C++11 [over.literal]p2, literal operators can only be declared at
369 // namespace scope. Therefore, this unqualified-id cannot name anything.
370 // Reject it early, because we have no AST representation for this in the
371 // case where the scope is dependent.
372 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
373 << SS.getScopeRep();
374 return true;
375
376 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000377 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000378 case NestedNameSpecifier::Namespace:
379 case NestedNameSpecifier::NamespaceAlias:
380 return false;
381 }
382
383 llvm_unreachable("unknown nested name specifier kind");
384}
385
Douglas Gregor9da64192010-04-26 22:37:10 +0000386/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000387ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000388 SourceLocation TypeidLoc,
389 TypeSourceInfo *Operand,
390 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000391 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000393 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000395 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000396 Qualifiers Quals;
397 QualType T
398 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
399 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000400 if (T->getAs<RecordType>() &&
401 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
402 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000403
David Majnemer6f3150a2014-11-21 21:09:12 +0000404 if (T->isVariablyModifiedType())
405 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
406
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000407 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
408 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000409}
410
411/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000412ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000416 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000417 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000418 if (E->getType()->isPlaceholderType()) {
419 ExprResult result = CheckPlaceholderExpr(E);
420 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000421 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000422 }
423
Douglas Gregor9da64192010-04-26 22:37:10 +0000424 QualType T = E->getType();
425 if (const RecordType *RecordT = T->getAs<RecordType>()) {
426 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
427 // C++ [expr.typeid]p3:
428 // [...] If the type of the expression is a class type, the class
429 // shall be completely-defined.
430 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
431 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000434 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // polymorphic class type [...] [the] expression is an unevaluated
436 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000437 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000438 // The subexpression is potentially evaluated; switch the context
439 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000440 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000441 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000442 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000443
444 // We require a vtable to query the type at run time.
445 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000446 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000447 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 // C++ [expr.typeid]p4:
451 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452 // cv-qualified type, the result of the typeid expression refers to a
453 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000454 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000455 Qualifiers Quals;
456 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
457 if (!Context.hasSameType(T, UnqualT)) {
458 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000459 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000460 }
461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
David Majnemer6f3150a2014-11-21 21:09:12 +0000463 if (E->getType()->isVariablyModifiedType())
464 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
465 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000466 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000467 E->HasSideEffects(Context, WasEvaluated)) {
468 // The expression operand for typeid is in an unevaluated expression
469 // context, so side effects could result in unintended consequences.
470 Diag(E->getExprLoc(), WasEvaluated
471 ? diag::warn_side_effects_typeid
472 : diag::warn_side_effects_unevaluated_context);
473 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000474
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000475 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
476 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000477}
478
479/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000480ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000481Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
482 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000483 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000484 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000485 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000486
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000487 if (!CXXTypeInfoDecl) {
488 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
489 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
490 LookupQualifiedName(R, getStdNamespace());
491 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000492 // Microsoft's typeinfo doesn't have type_info in std but in the global
493 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000494 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000495 LookupQualifiedName(R, Context.getTranslationUnitDecl());
496 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
497 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000498 if (!CXXTypeInfoDecl)
499 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
Nico Weber1b7f39d2012-05-20 01:27:21 +0000502 if (!getLangOpts().RTTI) {
503 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
504 }
505
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000506 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507
Douglas Gregor9da64192010-04-26 22:37:10 +0000508 if (isType) {
509 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000510 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000511 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
512 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000513 if (T.isNull())
514 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Douglas Gregor9da64192010-04-26 22:37:10 +0000516 if (!TInfo)
517 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000518
Douglas Gregor9da64192010-04-26 22:37:10 +0000519 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000522 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000523 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000524}
525
David Majnemer1dbc7a72016-03-27 04:46:07 +0000526/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
527/// a single GUID.
528static void
529getUuidAttrOfType(Sema &SemaRef, QualType QT,
530 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
531 // Optionally remove one level of pointer, reference or array indirection.
532 const Type *Ty = QT.getTypePtr();
533 if (QT->isPointerType() || QT->isReferenceType())
534 Ty = QT->getPointeeType().getTypePtr();
535 else if (QT->isArrayType())
536 Ty = Ty->getBaseElementTypeUnsafe();
537
Reid Klecknere516eab2016-12-13 18:58:09 +0000538 const auto *TD = Ty->getAsTagDecl();
539 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000540 return;
541
Reid Klecknere516eab2016-12-13 18:58:09 +0000542 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000543 UuidAttrs.insert(Uuid);
544 return;
545 }
546
547 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000548 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000549 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
550 for (const TemplateArgument &TA : TAL.asArray()) {
551 const UuidAttr *UuidForTA = nullptr;
552 if (TA.getKind() == TemplateArgument::Type)
553 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
554 else if (TA.getKind() == TemplateArgument::Declaration)
555 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
556
557 if (UuidForTA)
558 UuidAttrs.insert(UuidForTA);
559 }
560 }
561}
562
Francois Pichet9f4f2072010-09-08 12:20:18 +0000563/// \brief Build a Microsoft __uuidof expression with a type operand.
564ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
565 SourceLocation TypeidLoc,
566 TypeSourceInfo *Operand,
567 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000568 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000569 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000570 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
571 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
572 if (UuidAttrs.empty())
573 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
574 if (UuidAttrs.size() > 1)
575 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000576 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
David Majnemer2041b462016-03-28 03:19:50 +0000579 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000580 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000581}
582
583/// \brief Build a Microsoft __uuidof expression with an expression operand.
584ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
585 SourceLocation TypeidLoc,
586 Expr *E,
587 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000588 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000589 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000590 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
591 UuidStr = "00000000-0000-0000-0000-000000000000";
592 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000593 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
594 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
595 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000596 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000597 if (UuidAttrs.size() > 1)
598 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000599 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000600 }
Francois Pichetb7577652010-12-27 01:32:00 +0000601 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000602
David Majnemer2041b462016-03-28 03:19:50 +0000603 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000604 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000605}
606
607/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
608ExprResult
609Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
610 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000612 if (!MSVCGuidDecl) {
613 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
614 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
615 LookupQualifiedName(R, Context.getTranslationUnitDecl());
616 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
617 if (!MSVCGuidDecl)
618 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619 }
620
Francois Pichet9f4f2072010-09-08 12:20:18 +0000621 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623 if (isType) {
624 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000625 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000626 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
627 &TInfo);
628 if (T.isNull())
629 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000630
Francois Pichet9f4f2072010-09-08 12:20:18 +0000631 if (!TInfo)
632 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
633
634 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
635 }
636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000638 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
639}
640
Steve Naroff66356bd2007-09-16 14:56:35 +0000641/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000642ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000643Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000644 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000645 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000646 return new (Context)
647 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000648}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000649
Sebastian Redl576fd422009-05-10 18:38:11 +0000650/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000651ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000652Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000653 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000654}
655
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000656/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000657ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000658Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
659 bool IsThrownVarInScope = false;
660 if (Ex) {
661 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000662 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000663 // copy/move construction of a class object [...]
664 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000665 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000667 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000668 // innermost enclosing try-block (if there is one), the copy/move
669 // operation from the operand to the exception object (15.1) can be
670 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000671 // exception object
672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
674 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
675 for( ; S; S = S->getParent()) {
676 if (S->isDeclScope(Var)) {
677 IsThrownVarInScope = true;
678 break;
679 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000680
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000681 if (S->getFlags() &
682 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
683 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
684 Scope::TryScope))
685 break;
686 }
687 }
688 }
689 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000690
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000691 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
692}
693
Simon Pilgrim75c26882016-09-30 14:25:09 +0000694ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000695 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000696 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000697 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000698 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000699 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000700
Justin Lebar2a8db342016-09-28 22:45:54 +0000701 // Exceptions aren't allowed in CUDA device code.
702 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000703 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
704 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000705
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000706 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
707 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
708
John Wiegley01296292011-04-08 18:41:53 +0000709 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000710 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
711 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000712 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000713
714 // Initialize the exception result. This implicitly weeds out
715 // abstract types or types with inaccessible copy constructors.
716
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
720 //
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or
723 // catch-clause
724 // parameter) whose scope does not extend beyond the end of the
725 // innermost enclosing try-block (if there is one), the copy/move
726 // operation from the operand to the exception object (15.1) can be
727 // omitted by constructing the automatic object directly into the
728 // exception object
729 const VarDecl *NRVOVariable = nullptr;
730 if (IsThrownVarInScope)
731 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
732
733 InitializedEntity Entity = InitializedEntity::InitializeException(
734 OpLoc, ExceptionObjectTy,
735 /*NRVO=*/NRVOVariable != nullptr);
736 ExprResult Res = PerformMoveOrCopyInitialization(
737 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
738 if (Res.isInvalid())
739 return ExprError();
740 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000741 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000742
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000743 return new (Context)
744 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000745}
746
David Majnemere7a818f2015-03-06 18:53:55 +0000747static void
748collectPublicBases(CXXRecordDecl *RD,
749 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
750 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
751 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
752 bool ParentIsPublic) {
753 for (const CXXBaseSpecifier &BS : RD->bases()) {
754 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
755 bool NewSubobject;
756 // Virtual bases constitute the same subobject. Non-virtual bases are
757 // always distinct subobjects.
758 if (BS.isVirtual())
759 NewSubobject = VBases.insert(BaseDecl).second;
760 else
761 NewSubobject = true;
762
763 if (NewSubobject)
764 ++SubobjectsSeen[BaseDecl];
765
766 // Only add subobjects which have public access throughout the entire chain.
767 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
768 if (PublicPath)
769 PublicSubobjectsSeen.insert(BaseDecl);
770
771 // Recurse on to each base subobject.
772 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 PublicPath);
774 }
775}
776
777static void getUnambiguousPublicSubobjects(
778 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
779 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
780 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
781 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
782 SubobjectsSeen[RD] = 1;
783 PublicSubobjectsSeen.insert(RD);
784 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
785 /*ParentIsPublic=*/true);
786
787 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
788 // Skip ambiguous objects.
789 if (SubobjectsSeen[PublicSubobject] > 1)
790 continue;
791
792 Objects.push_back(PublicSubobject);
793 }
794}
795
Sebastian Redl4de47b42009-04-27 20:27:31 +0000796/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
798 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000799 // If the type of the exception would be an incomplete type or a pointer
800 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000801 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000802 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000803 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000804 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000805 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000806 }
807 if (!isPointer || !Ty->isVoidType()) {
808 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000809 isPointer ? diag::err_throw_incomplete_ptr
810 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000811 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000812 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000813
David Majnemerd09a51c2015-03-03 01:50:05 +0000814 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000815 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000816 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000817 }
818
Eli Friedman91a3d272010-06-03 20:39:03 +0000819 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000820 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
821 if (!RD)
822 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000823
Douglas Gregor88d292c2010-05-13 16:44:06 +0000824 // If we are throwing a polymorphic class type or pointer thereof,
825 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000826 MarkVTableUsed(ThrowLoc, RD);
827
Eli Friedman36ebbec2010-10-12 20:32:36 +0000828 // If a pointer is thrown, the referenced object will not be destroyed.
829 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000830 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000831
Richard Smitheec915d62012-02-18 04:13:32 +0000832 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000833 if (!RD->hasIrrelevantDestructor()) {
834 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
835 MarkFunctionReferenced(E->getExprLoc(), Destructor);
836 CheckDestructorAccess(E->getExprLoc(), Destructor,
837 PDiag(diag::err_access_dtor_exception) << Ty);
838 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000839 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000840 }
841 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000842
David Majnemerdfa6d202015-03-11 18:36:39 +0000843 // The MSVC ABI creates a list of all types which can catch the exception
844 // object. This list also references the appropriate copy constructor to call
845 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000847 // We are only interested in the public, unambiguous bases contained within
848 // the exception object. Bases which are ambiguous or otherwise
849 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000850 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
851 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000852
David Majnemere7a818f2015-03-06 18:53:55 +0000853 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000854 // Attempt to lookup the copy constructor. Various pieces of machinery
855 // will spring into action, like template instantiation, which means this
856 // cannot be a simple walk of the class's decls. Instead, we must perform
857 // lookup and overload resolution.
858 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
859 if (!CD)
860 continue;
861
862 // Mark the constructor referenced as it is used by this throw expression.
863 MarkFunctionReferenced(E->getExprLoc(), CD);
864
865 // Skip this copy constructor if it is trivial, we don't need to record it
866 // in the catchable type data.
867 if (CD->isTrivial())
868 continue;
869
870 // The copy constructor is non-trivial, create a mapping from this class
871 // type to this constructor.
872 // N.B. The selection of copy constructor is not sensitive to this
873 // particular throw-site. Lookup will be performed at the catch-site to
874 // ensure that the copy constructor is, in fact, accessible (via
875 // friendship or any other means).
876 Context.addCopyConstructorForExceptionObject(Subobject, CD);
877
878 // We don't keep the instantiated default argument expressions around so
879 // we must rebuild them here.
880 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000881 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
882 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000883 }
884 }
885 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000886
David Majnemerba3e5ec2015-03-13 18:26:17 +0000887 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000888}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000889
Faisal Vali67b04462016-06-11 16:41:54 +0000890static QualType adjustCVQualifiersForCXXThisWithinLambda(
891 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
892 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
893
894 QualType ClassType = ThisTy->getPointeeType();
895 LambdaScopeInfo *CurLSI = nullptr;
896 DeclContext *CurDC = CurSemaContext;
897
898 // Iterate through the stack of lambdas starting from the innermost lambda to
899 // the outermost lambda, checking if '*this' is ever captured by copy - since
900 // that could change the cv-qualifiers of the '*this' object.
901 // The object referred to by '*this' starts out with the cv-qualifiers of its
902 // member function. We then start with the innermost lambda and iterate
903 // outward checking to see if any lambda performs a by-copy capture of '*this'
904 // - and if so, any nested lambda must respect the 'constness' of that
905 // capturing lamdbda's call operator.
906 //
907
Faisal Vali999f27e2017-05-02 20:56:34 +0000908 // Since the FunctionScopeInfo stack is representative of the lexical
909 // nesting of the lambda expressions during initial parsing (and is the best
910 // place for querying information about captures about lambdas that are
911 // partially processed) and perhaps during instantiation of function templates
912 // that contain lambda expressions that need to be transformed BUT not
913 // necessarily during instantiation of a nested generic lambda's function call
914 // operator (which might even be instantiated at the end of the TU) - at which
915 // time the DeclContext tree is mature enough to query capture information
916 // reliably - we use a two pronged approach to walk through all the lexically
917 // enclosing lambda expressions:
918 //
919 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
920 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
921 // enclosed by the call-operator of the LSI below it on the stack (while
922 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
923 // the stack represents the innermost lambda.
924 //
925 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
926 // represents a lambda's call operator. If it does, we must be instantiating
927 // a generic lambda's call operator (represented by the Current LSI, and
928 // should be the only scenario where an inconsistency between the LSI and the
929 // DeclContext should occur), so climb out the DeclContexts if they
930 // represent lambdas, while querying the corresponding closure types
931 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000932
Faisal Vali999f27e2017-05-02 20:56:34 +0000933 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000934 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000935 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
936 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
937 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000938 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
939 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000940
941 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000942 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000943
Faisal Vali67b04462016-06-11 16:41:54 +0000944 auto C = CurLSI->getCXXThisCapture();
945
946 if (C.isCopyCapture()) {
947 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
948 if (CurLSI->CallOperator->isConst())
949 ClassType.addConst();
950 return ASTCtx.getPointerType(ClassType);
951 }
952 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000953
954 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
955 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000956 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +0000957 assert(CurLSI && "While computing 'this' capture-type for a generic "
958 "lambda, we must have a corresponding LambdaScopeInfo");
959 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
960 "While computing 'this' capture-type for a generic lambda, when we "
961 "run out of enclosing LSI's, yet the enclosing DC is a "
962 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
963 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +0000964 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000965
Faisal Vali67b04462016-06-11 16:41:54 +0000966 auto IsThisCaptured =
967 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
968 IsConst = false;
969 IsByCopy = false;
970 for (auto &&C : Closure->captures()) {
971 if (C.capturesThis()) {
972 if (C.getCaptureKind() == LCK_StarThis)
973 IsByCopy = true;
974 if (Closure->getLambdaCallOperator()->isConst())
975 IsConst = true;
976 return true;
977 }
978 }
979 return false;
980 };
981
982 bool IsByCopyCapture = false;
983 bool IsConstCapture = false;
984 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
985 while (Closure &&
986 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
987 if (IsByCopyCapture) {
988 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
989 if (IsConstCapture)
990 ClassType.addConst();
991 return ASTCtx.getPointerType(ClassType);
992 }
993 Closure = isLambdaCallOperator(Closure->getParent())
994 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
995 : nullptr;
996 }
997 }
998 return ASTCtx.getPointerType(ClassType);
999}
1000
Eli Friedman73a04092012-01-07 04:59:52 +00001001QualType Sema::getCurrentThisType() {
1002 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001003 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001004
Richard Smith938f40b2011-06-11 17:19:42 +00001005 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1006 if (method && method->isInstance())
1007 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001008 }
Faisal Validc6b5962016-03-21 09:25:37 +00001009
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001010 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001011 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001012
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001013 assert(isa<CXXRecordDecl>(DC) &&
1014 "Trying to get 'this' type from static method?");
1015
1016 // This is a lambda call operator that is being instantiated as a default
1017 // initializer. DC must point to the enclosing class type, so we can recover
1018 // the 'this' type from it.
1019
1020 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1021 // There are no cv-qualifiers for 'this' within default initializers,
1022 // per [expr.prim.general]p4.
1023 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001024 }
Faisal Vali67b04462016-06-11 16:41:54 +00001025
1026 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1027 // might need to be adjusted if the lambda or any of its enclosing lambda's
1028 // captures '*this' by copy.
1029 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1030 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1031 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001032 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001033}
1034
Simon Pilgrim75c26882016-09-30 14:25:09 +00001035Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001036 Decl *ContextDecl,
1037 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001038 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001039 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1040{
1041 if (!Enabled || !ContextDecl)
1042 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001043
1044 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001045 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1046 Record = Template->getTemplatedDecl();
1047 else
1048 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001049
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001050 // We care only for CVR qualifiers here, so cut everything else.
1051 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001052 S.CXXThisTypeOverride
1053 = S.Context.getPointerType(
1054 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001055
Douglas Gregor3024f072012-04-16 07:05:22 +00001056 this->Enabled = true;
1057}
1058
1059
1060Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1061 if (Enabled) {
1062 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1063 }
1064}
1065
Faisal Validc6b5962016-03-21 09:25:37 +00001066static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1067 QualType ThisTy, SourceLocation Loc,
1068 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001069
Faisal Vali67b04462016-06-11 16:41:54 +00001070 QualType AdjustedThisTy = ThisTy;
1071 // The type of the corresponding data member (not a 'this' pointer if 'by
1072 // copy').
1073 QualType CaptureThisFieldTy = ThisTy;
1074 if (ByCopy) {
1075 // If we are capturing the object referred to by '*this' by copy, ignore any
1076 // cv qualifiers inherited from the type of the member function for the type
1077 // of the closure-type's corresponding data member and any use of 'this'.
1078 CaptureThisFieldTy = ThisTy->getPointeeType();
1079 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1080 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1081 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001082
Faisal Vali67b04462016-06-11 16:41:54 +00001083 FieldDecl *Field = FieldDecl::Create(
1084 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1085 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1086 ICIS_NoInit);
1087
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001088 Field->setImplicit(true);
1089 Field->setAccess(AS_private);
1090 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001091 Expr *This =
1092 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001093 if (ByCopy) {
1094 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1095 UO_Deref,
1096 This).get();
1097 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001098 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001099 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1100 InitializationSequence Init(S, Entity, InitKind, StarThis);
1101 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1102 if (ER.isInvalid()) return nullptr;
1103 return ER.get();
1104 }
1105 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001106}
1107
Simon Pilgrim75c26882016-09-30 14:25:09 +00001108bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001109 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1110 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001111 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001112 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001113 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001114
Faisal Validc6b5962016-03-21 09:25:37 +00001115 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001116
Faisal Valia17d19f2013-11-07 05:17:06 +00001117 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001118 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001119
Simon Pilgrim75c26882016-09-30 14:25:09 +00001120 // Check that we can capture the *enclosing object* (referred to by '*this')
1121 // by the capturing-entity/closure (lambda/block/etc) at
1122 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1123
1124 // Note: The *enclosing object* can only be captured by-value by a
1125 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001126 // [*this] { ... }.
1127 // Every other capture of the *enclosing object* results in its by-reference
1128 // capture.
1129
1130 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1131 // stack), we can capture the *enclosing object* only if:
1132 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1133 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001134 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001135 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001136 // -- or, there is some enclosing closure 'E' that has already captured the
1137 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001138 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001139 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001140 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001141
1142
Faisal Validc6b5962016-03-21 09:25:37 +00001143 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001144 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001145 if (CapturingScopeInfo *CSI =
1146 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1147 if (CSI->CXXThisCaptureIndex != 0) {
1148 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001149 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001150 break;
1151 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001152 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1153 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1154 // This context can't implicitly capture 'this'; fail out.
1155 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001156 Diag(Loc, diag::err_this_capture)
1157 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001158 return true;
1159 }
Eli Friedman20139d32012-01-11 02:36:31 +00001160 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001161 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001162 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001163 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001164 (Explicit && idx == MaxFunctionScopesIndex)) {
1165 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1166 // iteration through can be an explicit capture, all enclosing closures,
1167 // if any, must perform implicit captures.
1168
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001169 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001170 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001171 continue;
1172 }
Eli Friedman20139d32012-01-11 02:36:31 +00001173 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001174 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001175 Diag(Loc, diag::err_this_capture)
1176 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001177 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001178 }
Eli Friedman73a04092012-01-07 04:59:52 +00001179 break;
1180 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001181 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001182
1183 // If we got here, then the closure at MaxFunctionScopesIndex on the
1184 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1185 // (including implicit by-reference captures in any enclosing closures).
1186
1187 // In the loop below, respect the ByCopy flag only for the closure requesting
1188 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001189 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001190 // implicitly capturing the *enclosing object* by reference (see loop
1191 // above)).
1192 assert((!ByCopy ||
1193 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1194 "Only a lambda can capture the enclosing object (referred to by "
1195 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001196 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1197 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001198 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001199 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001200 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001202 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001203
Faisal Validc6b5962016-03-21 09:25:37 +00001204 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1205 // For lambda expressions, build a field and an initializing expression,
1206 // and capture the *enclosing object* by copy only if this is the first
1207 // iteration.
1208 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1209 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001210
Faisal Validc6b5962016-03-21 09:25:37 +00001211 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001212 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001213 ThisExpr =
1214 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1215 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001216
Faisal Validc6b5962016-03-21 09:25:37 +00001217 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001218 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001219 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001220 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001221}
1222
Richard Smith938f40b2011-06-11 17:19:42 +00001223ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001224 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1225 /// is a non-lvalue expression whose value is the address of the object for
1226 /// which the function is called.
1227
Douglas Gregor09deffa2011-10-18 16:47:30 +00001228 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001229 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001230
Eli Friedman73a04092012-01-07 04:59:52 +00001231 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001232 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001233}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001234
Douglas Gregor3024f072012-04-16 07:05:22 +00001235bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1236 // If we're outside the body of a member function, then we'll have a specified
1237 // type for 'this'.
1238 if (CXXThisTypeOverride.isNull())
1239 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001240
Douglas Gregor3024f072012-04-16 07:05:22 +00001241 // Determine whether we're looking into a class that's currently being
1242 // defined.
1243 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1244 return Class && Class->isBeingDefined();
1245}
1246
John McCalldadc5752010-08-24 06:29:42 +00001247ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001248Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001249 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001250 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001251 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001252 if (!TypeRep)
1253 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
John McCall97513962010-01-15 18:39:57 +00001255 TypeSourceInfo *TInfo;
1256 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1257 if (!TInfo)
1258 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001259
Richard Smithb8c414c2016-06-30 20:24:30 +00001260 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1261 // Avoid creating a non-type-dependent expression that contains typos.
1262 // Non-type-dependent expressions are liable to be discarded without
1263 // checking for embedded typos.
1264 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1265 !Result.get()->isTypeDependent())
1266 Result = CorrectDelayedTyposInExpr(Result.get());
1267 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001268}
1269
1270/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1271/// Can be interpreted either as function-style casting ("int(x)")
1272/// or class type construction ("ClassType(x,y,z)")
1273/// or creation of a value-initialized type ("int()").
1274ExprResult
1275Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1276 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001277 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001278 SourceLocation RParenLoc) {
1279 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001280 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001281
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001282 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001283 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1284 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001285 }
1286
Sebastian Redld74dd492012-02-12 18:41:05 +00001287 bool ListInitialization = LParenLoc.isInvalid();
Richard Smith600b5262017-01-26 20:40:47 +00001288 assert((!ListInitialization ||
1289 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1290 "List initialization must have initializer list as expression.");
Sebastian Redld74dd492012-02-12 18:41:05 +00001291 SourceRange FullRange = SourceRange(TyBeginLoc,
1292 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1293
Richard Smith60437622017-02-09 19:17:44 +00001294 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1295 InitializationKind Kind =
1296 Exprs.size()
1297 ? ListInitialization
1298 ? InitializationKind::CreateDirectList(TyBeginLoc)
1299 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1300 RParenLoc)
1301 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1302
1303 // C++1z [expr.type.conv]p1:
1304 // If the type is a placeholder for a deduced class type, [...perform class
1305 // template argument deduction...]
1306 DeducedType *Deduced = Ty->getContainedDeducedType();
1307 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1308 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1309 Kind, Exprs);
1310 if (Ty.isNull())
1311 return ExprError();
1312 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1313 }
1314
Douglas Gregordd04d332009-01-16 18:33:17 +00001315 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001316 // If the expression list is a parenthesized single expression, the type
1317 // conversion expression is equivalent (in definedness, and if defined in
1318 // meaning) to the corresponding cast expression.
1319 if (Exprs.size() == 1 && !ListInitialization &&
1320 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001321 Expr *Arg = Exprs[0];
Richard Smith60437622017-02-09 19:17:44 +00001322 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001323 }
1324
Richard Smith49a6b6e2017-03-24 01:14:25 +00001325 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001326 QualType ElemTy = Ty;
1327 if (Ty->isArrayType()) {
1328 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001329 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1330 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001331 ElemTy = Context.getBaseElementType(Ty);
1332 }
1333
Richard Smith49a6b6e2017-03-24 01:14:25 +00001334 // There doesn't seem to be an explicit rule against this but sanity demands
1335 // we only construct objects with object types.
1336 if (Ty->isFunctionType())
1337 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1338 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001339
Richard Smith49a6b6e2017-03-24 01:14:25 +00001340 // C++17 [expr.type.conv]p2:
1341 // If the type is cv void and the initializer is (), the expression is a
1342 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001343 if (!Ty->isVoidType() &&
1344 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001345 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001346 return ExprError();
1347
Richard Smith49a6b6e2017-03-24 01:14:25 +00001348 // Otherwise, the expression is a prvalue of the specified type whose
1349 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001350 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1351 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001352
Richard Smith49a6b6e2017-03-24 01:14:25 +00001353 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001354 return Result;
1355
1356 Expr *Inner = Result.get();
1357 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1358 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001359 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1360 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001361 // If we created a CXXTemporaryObjectExpr, that node also represents the
1362 // functional cast. Otherwise, create an explicit cast to represent
1363 // the syntactic form of a functional-style cast that was used here.
1364 //
1365 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1366 // would give a more consistent AST representation than using a
1367 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1368 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001369 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001370 Result = CXXFunctionalCastExpr::Create(
Richard Smith60437622017-02-09 19:17:44 +00001371 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001372 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001373 }
1374
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001375 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001376}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001377
Richard Smithb2f0f052016-10-10 18:54:32 +00001378/// \brief Determine whether the given function is a non-placement
1379/// deallocation function.
1380static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1382 return Method->isUsualDeallocationFunction();
1383
1384 if (FD->getOverloadedOperator() != OO_Delete &&
1385 FD->getOverloadedOperator() != OO_Array_Delete)
1386 return false;
1387
1388 unsigned UsualParams = 1;
1389
1390 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1391 S.Context.hasSameUnqualifiedType(
1392 FD->getParamDecl(UsualParams)->getType(),
1393 S.Context.getSizeType()))
1394 ++UsualParams;
1395
1396 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1397 S.Context.hasSameUnqualifiedType(
1398 FD->getParamDecl(UsualParams)->getType(),
1399 S.Context.getTypeDeclType(S.getStdAlignValT())))
1400 ++UsualParams;
1401
1402 return UsualParams == FD->getNumParams();
1403}
1404
1405namespace {
1406 struct UsualDeallocFnInfo {
1407 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001408 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001409 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001410 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001411 // A function template declaration is never a usual deallocation function.
1412 if (!FD)
1413 return;
1414 if (FD->getNumParams() == 3)
1415 HasAlignValT = HasSizeT = true;
1416 else if (FD->getNumParams() == 2) {
1417 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1418 HasAlignValT = !HasSizeT;
1419 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001420
1421 // In CUDA, determine how much we'd like / dislike to call this.
1422 if (S.getLangOpts().CUDA)
1423 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1424 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001425 }
1426
1427 operator bool() const { return FD; }
1428
Richard Smithf75dcbe2016-10-11 00:21:10 +00001429 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1430 bool WantAlign) const {
1431 // C++17 [expr.delete]p10:
1432 // If the type has new-extended alignment, a function with a parameter
1433 // of type std::align_val_t is preferred; otherwise a function without
1434 // such a parameter is preferred
1435 if (HasAlignValT != Other.HasAlignValT)
1436 return HasAlignValT == WantAlign;
1437
1438 if (HasSizeT != Other.HasSizeT)
1439 return HasSizeT == WantSize;
1440
1441 // Use CUDA call preference as a tiebreaker.
1442 return CUDAPref > Other.CUDAPref;
1443 }
1444
Richard Smithb2f0f052016-10-10 18:54:32 +00001445 DeclAccessPair Found;
1446 FunctionDecl *FD;
1447 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001448 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001449 };
1450}
1451
1452/// Determine whether a type has new-extended alignment. This may be called when
1453/// the type is incomplete (for a delete-expression with an incomplete pointee
1454/// type), in which case it will conservatively return false if the alignment is
1455/// not known.
1456static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1457 return S.getLangOpts().AlignedAllocation &&
1458 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1459 S.getASTContext().getTargetInfo().getNewAlign();
1460}
1461
1462/// Select the correct "usual" deallocation function to use from a selection of
1463/// deallocation functions (either global or class-scope).
1464static UsualDeallocFnInfo resolveDeallocationOverload(
1465 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1466 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1467 UsualDeallocFnInfo Best;
1468
Richard Smithb2f0f052016-10-10 18:54:32 +00001469 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001470 UsualDeallocFnInfo Info(S, I.getPair());
1471 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1472 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001473 continue;
1474
1475 if (!Best) {
1476 Best = Info;
1477 if (BestFns)
1478 BestFns->push_back(Info);
1479 continue;
1480 }
1481
Richard Smithf75dcbe2016-10-11 00:21:10 +00001482 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001483 continue;
1484
1485 // If more than one preferred function is found, all non-preferred
1486 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001487 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001488 BestFns->clear();
1489
1490 Best = Info;
1491 if (BestFns)
1492 BestFns->push_back(Info);
1493 }
1494
1495 return Best;
1496}
1497
1498/// Determine whether a given type is a class for which 'delete[]' would call
1499/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1500/// we need to store the array size (even if the type is
1501/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001502static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1503 QualType allocType) {
1504 const RecordType *record =
1505 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1506 if (!record) return false;
1507
1508 // Try to find an operator delete[] in class scope.
1509
1510 DeclarationName deleteName =
1511 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1512 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1513 S.LookupQualifiedName(ops, record->getDecl());
1514
1515 // We're just doing this for information.
1516 ops.suppressDiagnostics();
1517
1518 // Very likely: there's no operator delete[].
1519 if (ops.empty()) return false;
1520
1521 // If it's ambiguous, it should be illegal to call operator delete[]
1522 // on this thing, so it doesn't matter if we allocate extra space or not.
1523 if (ops.isAmbiguous()) return false;
1524
Richard Smithb2f0f052016-10-10 18:54:32 +00001525 // C++17 [expr.delete]p10:
1526 // If the deallocation functions have class scope, the one without a
1527 // parameter of type std::size_t is selected.
1528 auto Best = resolveDeallocationOverload(
1529 S, ops, /*WantSize*/false,
1530 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1531 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001532}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001533
Sebastian Redld74dd492012-02-12 18:41:05 +00001534/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001535///
Sebastian Redld74dd492012-02-12 18:41:05 +00001536/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001537/// @code new (memory) int[size][4] @endcode
1538/// or
1539/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001540///
1541/// \param StartLoc The first location of the expression.
1542/// \param UseGlobal True if 'new' was prefixed with '::'.
1543/// \param PlacementLParen Opening paren of the placement arguments.
1544/// \param PlacementArgs Placement new arguments.
1545/// \param PlacementRParen Closing paren of the placement arguments.
1546/// \param TypeIdParens If the type is in parens, the source range.
1547/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001548/// \param Initializer The initializing expression or initializer-list, or null
1549/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001550ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001551Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001552 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001554 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001555 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001556 // If the specified type is an array, unwrap it and save the expression.
1557 if (D.getNumTypeObjects() > 0 &&
1558 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001559 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001560 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001561 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1562 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001563 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001564 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1565 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001566 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001567 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1568 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001569
Sebastian Redl351bb782008-12-02 14:43:59 +00001570 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001571 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001572 }
1573
Douglas Gregor73341c42009-09-11 00:18:58 +00001574 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001575 if (ArraySize) {
1576 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001577 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1578 break;
1579
1580 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1581 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001582 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001583 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001584 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1585 // shall be a converted constant expression (5.19) of type std::size_t
1586 // and shall evaluate to a strictly positive value.
1587 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1588 assert(IntWidth && "Builtin type of size 0?");
1589 llvm::APSInt Value(IntWidth);
1590 Array.NumElts
1591 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1592 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001593 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001594 } else {
1595 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001596 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001597 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001598 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001599 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001600 if (!Array.NumElts)
1601 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001602 }
1603 }
1604 }
1605 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001606
Craig Topperc3ec1492014-05-26 06:22:03 +00001607 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001608 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001609 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001610 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001611
Sebastian Redl6047f072012-02-16 12:22:20 +00001612 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001613 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001614 DirectInitRange = List->getSourceRange();
1615
David Blaikie7b97aef2012-11-07 00:12:38 +00001616 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001617 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001618 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001619 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001620 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001621 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001622 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001623 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001624 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001625 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001626}
1627
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001628static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1629 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001630 if (!Init)
1631 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001632 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1633 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001634 if (isa<ImplicitValueInitExpr>(Init))
1635 return true;
1636 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1637 return !CCE->isListInitialization() &&
1638 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001639 else if (Style == CXXNewExpr::ListInit) {
1640 assert(isa<InitListExpr>(Init) &&
1641 "Shouldn't create list CXXConstructExprs for arrays.");
1642 return true;
1643 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001644 return false;
1645}
1646
Akira Hatanakacae83f72017-06-29 18:48:40 +00001647// Emit a diagnostic if an aligned allocation/deallocation function that is not
1648// implemented in the standard library is selected.
1649static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1650 SourceLocation Loc, bool IsDelete,
1651 Sema &S) {
1652 if (!S.getLangOpts().AlignedAllocationUnavailable)
1653 return;
1654
1655 // Return if there is a definition.
1656 if (FD.isDefined())
1657 return;
1658
1659 bool IsAligned = false;
1660 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001661 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1662 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1663 S.getASTContext().getTargetInfo().getPlatformName());
1664
Akira Hatanakacae83f72017-06-29 18:48:40 +00001665 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001666 << IsDelete << FD.getType().getAsString() << OSName
1667 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001668 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1669 }
1670}
1671
John McCalldadc5752010-08-24 06:29:42 +00001672ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001673Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001674 SourceLocation PlacementLParen,
1675 MultiExprArg PlacementArgs,
1676 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001677 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001678 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001679 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001680 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001681 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001682 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001683 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001684 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001685
Sebastian Redl6047f072012-02-16 12:22:20 +00001686 CXXNewExpr::InitializationStyle initStyle;
1687 if (DirectInitRange.isValid()) {
1688 assert(Initializer && "Have parens but no initializer.");
1689 initStyle = CXXNewExpr::CallInit;
1690 } else if (Initializer && isa<InitListExpr>(Initializer))
1691 initStyle = CXXNewExpr::ListInit;
1692 else {
1693 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1694 isa<CXXConstructExpr>(Initializer)) &&
1695 "Initializer expression that cannot have been implicitly created.");
1696 initStyle = CXXNewExpr::NoInit;
1697 }
1698
1699 Expr **Inits = &Initializer;
1700 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001701 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1702 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1703 Inits = List->getExprs();
1704 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001705 }
1706
Richard Smith60437622017-02-09 19:17:44 +00001707 // C++11 [expr.new]p15:
1708 // A new-expression that creates an object of type T initializes that
1709 // object as follows:
1710 InitializationKind Kind
1711 // - If the new-initializer is omitted, the object is default-
1712 // initialized (8.5); if no initialization is performed,
1713 // the object has indeterminate value
1714 = initStyle == CXXNewExpr::NoInit
1715 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1716 // - Otherwise, the new-initializer is interpreted according to the
1717 // initialization rules of 8.5 for direct-initialization.
1718 : initStyle == CXXNewExpr::ListInit
1719 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1720 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1721 DirectInitRange.getBegin(),
1722 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001723
Richard Smith60437622017-02-09 19:17:44 +00001724 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1725 auto *Deduced = AllocType->getContainedDeducedType();
1726 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1727 if (ArraySize)
1728 return ExprError(Diag(ArraySize->getExprLoc(),
1729 diag::err_deduced_class_template_compound_type)
1730 << /*array*/ 2 << ArraySize->getSourceRange());
1731
1732 InitializedEntity Entity
1733 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1734 AllocType = DeduceTemplateSpecializationFromInitializer(
1735 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1736 if (AllocType.isNull())
1737 return ExprError();
1738 } else if (Deduced) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001739 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001740 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1741 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001742 if (initStyle == CXXNewExpr::ListInit ||
1743 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001744 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001745 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001746 << AllocType << TypeRange);
1747 if (NumInits > 1) {
1748 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001749 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001750 diag::err_auto_new_ctor_multiple_expressions)
1751 << AllocType << TypeRange);
1752 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001753 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001754 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001755 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001756 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001757 << AllocType << Deduce->getType()
1758 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001759 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001760 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001761 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001762 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001763
Douglas Gregorcda95f42010-05-16 16:01:03 +00001764 // Per C++0x [expr.new]p5, the type being constructed may be a
1765 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001766 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001767 if (const ConstantArrayType *Array
1768 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001769 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1770 Context.getSizeType(),
1771 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001772 AllocType = Array->getElementType();
1773 }
1774 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001775
Douglas Gregor3999e152010-10-06 16:00:31 +00001776 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1777 return ExprError();
1778
Craig Topperc3ec1492014-05-26 06:22:03 +00001779 if (initStyle == CXXNewExpr::ListInit &&
1780 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001781 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1782 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001783 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001784 }
1785
Simon Pilgrim75c26882016-09-30 14:25:09 +00001786 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001787 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001788 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1789 AllocType->isObjCLifetimeType()) {
1790 AllocType = Context.getLifetimeQualifiedType(AllocType,
1791 AllocType->getObjCARCImplicitLifetime());
1792 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001793
John McCall31168b02011-06-15 23:02:42 +00001794 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001795
John McCall5e77d762013-04-16 07:28:30 +00001796 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1797 ExprResult result = CheckPlaceholderExpr(ArraySize);
1798 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001799 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001800 }
Richard Smith8dd34252012-02-04 07:07:42 +00001801 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1802 // integral or enumeration type with a non-negative value."
1803 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1804 // enumeration type, or a class type for which a single non-explicit
1805 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001806 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001807 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001808 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001809 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001810 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001811 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001812 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1813
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001814 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1815 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001816
Simon Pilgrim75c26882016-09-30 14:25:09 +00001817 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001818 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001819 // Diagnose the compatibility of this conversion.
1820 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1821 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001822 } else {
1823 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1824 protected:
1825 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001826
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001827 public:
1828 SizeConvertDiagnoser(Expr *ArraySize)
1829 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1830 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001831
1832 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1833 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001834 return S.Diag(Loc, diag::err_array_size_not_integral)
1835 << S.getLangOpts().CPlusPlus11 << T;
1836 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001837
1838 SemaDiagnosticBuilder diagnoseIncomplete(
1839 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001840 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1841 << T << ArraySize->getSourceRange();
1842 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001843
1844 SemaDiagnosticBuilder diagnoseExplicitConv(
1845 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001846 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1847 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001848
1849 SemaDiagnosticBuilder noteExplicitConv(
1850 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001851 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1852 << ConvTy->isEnumeralType() << ConvTy;
1853 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001854
1855 SemaDiagnosticBuilder diagnoseAmbiguous(
1856 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001857 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1858 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001859
1860 SemaDiagnosticBuilder noteAmbiguous(
1861 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001862 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1863 << ConvTy->isEnumeralType() << ConvTy;
1864 }
Richard Smithccc11812013-05-21 19:05:48 +00001865
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001866 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1867 QualType T,
1868 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001869 return S.Diag(Loc,
1870 S.getLangOpts().CPlusPlus11
1871 ? diag::warn_cxx98_compat_array_size_conversion
1872 : diag::ext_array_size_conversion)
1873 << T << ConvTy->isEnumeralType() << ConvTy;
1874 }
1875 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001876
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001877 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1878 SizeDiagnoser);
1879 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001880 if (ConvertedSize.isInvalid())
1881 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001882
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001883 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001884 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001885
Douglas Gregor0bf31402010-10-08 23:50:27 +00001886 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001887 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001889 // C++98 [expr.new]p7:
1890 // The expression in a direct-new-declarator shall have integral type
1891 // with a non-negative value.
1892 //
Richard Smith0511d232016-10-05 22:41:02 +00001893 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1894 // per CWG1464. Otherwise, if it's not a constant, we must have an
1895 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001896 if (!ArraySize->isValueDependent()) {
1897 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001898 // We've already performed any required implicit conversion to integer or
1899 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001900 // FIXME: Per CWG1464, we are required to check the value prior to
1901 // converting to size_t. This will never find a negative array size in
1902 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001903 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001904 if (Value.isSigned() && Value.isNegative()) {
1905 return ExprError(Diag(ArraySize->getLocStart(),
1906 diag::err_typecheck_negative_array_size)
1907 << ArraySize->getSourceRange());
1908 }
1909
1910 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001911 unsigned ActiveSizeBits =
1912 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001913 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1914 return ExprError(Diag(ArraySize->getLocStart(),
1915 diag::err_array_too_large)
1916 << Value.toString(10)
1917 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001918 }
Richard Smith0511d232016-10-05 22:41:02 +00001919
1920 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001921 } else if (TypeIdParens.isValid()) {
1922 // Can't have dynamic array size when the type-id is in parentheses.
1923 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1924 << ArraySize->getSourceRange()
1925 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1926 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927
Douglas Gregorf2753b32010-07-13 15:54:32 +00001928 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001929 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001931
John McCall036f2f62011-05-15 07:14:44 +00001932 // Note that we do *not* convert the argument in any way. It can
1933 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001934 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001935
Craig Topperc3ec1492014-05-26 06:22:03 +00001936 FunctionDecl *OperatorNew = nullptr;
1937 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001938 unsigned Alignment =
1939 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1940 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1941 bool PassAlignment = getLangOpts().AlignedAllocation &&
1942 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001944 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001945 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001946 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001947 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001948 UseGlobal, AllocType, ArraySize, PassAlignment,
1949 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001950 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001951
1952 // If this is an array allocation, compute whether the usual array
1953 // deallocation function for the type has a size_t parameter.
1954 bool UsualArrayDeleteWantsSize = false;
1955 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001956 UsualArrayDeleteWantsSize =
1957 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001958
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001959 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001960 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001962 OperatorNew->getType()->getAs<FunctionProtoType>();
1963 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1964 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
Richard Smithd6f9e732014-05-13 19:56:21 +00001966 // We've already converted the placement args, just fill in any default
1967 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001968 // argument. Skip the second parameter too if we're passing in the
1969 // alignment; we've already filled it in.
1970 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1971 PassAlignment ? 2 : 1, PlacementArgs,
1972 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001973 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001974
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001975 if (!AllPlaceArgs.empty())
1976 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001977
Richard Smithd6f9e732014-05-13 19:56:21 +00001978 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001979 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001980
1981 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Richard Smithb2f0f052016-10-10 18:54:32 +00001983 // Warn if the type is over-aligned and is being allocated by (unaligned)
1984 // global operator new.
1985 if (PlacementArgs.empty() && !PassAlignment &&
1986 (OperatorNew->isImplicit() ||
1987 (OperatorNew->getLocStart().isValid() &&
1988 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1989 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001990 Diag(StartLoc, diag::warn_overaligned_type)
1991 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001992 << unsigned(Alignment / Context.getCharWidth())
1993 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001994 }
1995 }
1996
Sebastian Redl6047f072012-02-16 12:22:20 +00001997 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001998 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1999 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002000 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2001 SourceRange InitRange(Inits[0]->getLocStart(),
2002 Inits[NumInits - 1]->getLocEnd());
2003 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2004 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002005 }
2006
Richard Smithdd2ca572012-11-26 08:32:48 +00002007 // If we can perform the initialization, and we've not already done so,
2008 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002009 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002010 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002011 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002012 // The type we initialize is the complete type, including the array bound.
2013 QualType InitType;
2014 if (KnownArraySize)
2015 InitType = Context.getConstantArrayType(
2016 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2017 *KnownArraySize),
2018 ArrayType::Normal, 0);
2019 else if (ArraySize)
2020 InitType =
2021 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2022 else
2023 InitType = AllocType;
2024
Douglas Gregor85dabae2009-12-16 01:38:02 +00002025 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002026 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002027 InitializationSequence InitSeq(*this, Entity, Kind,
2028 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002030 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002031 if (FullInit.isInvalid())
2032 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033
Sebastian Redl6047f072012-02-16 12:22:20 +00002034 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2035 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002036 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002037 if (CXXBindTemporaryExpr *Binder =
2038 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002039 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002041 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043
Douglas Gregor6642ca22010-02-26 05:06:18 +00002044 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002045 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002046 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2047 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002048 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002049 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002050 }
2051 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002052 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2053 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002054 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002055 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002056 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002057
John McCall928a2572011-07-13 20:12:57 +00002058 // C++0x [expr.new]p17:
2059 // If the new expression creates an array of objects of class type,
2060 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002061 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2062 if (ArraySize && !BaseAllocType->isDependentType()) {
2063 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2064 if (CXXDestructorDecl *dtor = LookupDestructor(
2065 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2066 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002067 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002068 PDiag(diag::err_access_dtor)
2069 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002070 if (DiagnoseUseOfDecl(dtor, StartLoc))
2071 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002072 }
John McCall928a2572011-07-13 20:12:57 +00002073 }
2074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002076 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002077 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002078 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2079 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2080 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002081}
2082
Sebastian Redl6047f072012-02-16 12:22:20 +00002083/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002084/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002085bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002086 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002087 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2088 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002089 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002090 return Diag(Loc, diag::err_bad_new_type)
2091 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002092 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002093 return Diag(Loc, diag::err_bad_new_type)
2094 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002095 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002096 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002097 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002098 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002099 diag::err_allocation_of_abstract_type))
2100 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002101 else if (AllocType->isVariablyModifiedType())
2102 return Diag(Loc, diag::err_variably_modified_new_type)
2103 << AllocType;
Yaxun Liub34ec822017-04-11 17:24:23 +00002104 else if (AllocType.getAddressSpace())
Douglas Gregor39d1a092011-04-15 19:46:20 +00002105 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002106 << AllocType.getUnqualifiedType()
2107 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002108 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002109 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2110 QualType BaseAllocType = Context.getBaseElementType(AT);
2111 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2112 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002113 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002114 << BaseAllocType;
2115 }
2116 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002117
Sebastian Redlbd150f42008-11-21 19:14:01 +00002118 return false;
2119}
2120
Richard Smithb2f0f052016-10-10 18:54:32 +00002121static bool
2122resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2123 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2124 FunctionDecl *&Operator,
2125 OverloadCandidateSet *AlignedCandidates = nullptr,
2126 Expr *AlignArg = nullptr) {
2127 OverloadCandidateSet Candidates(R.getNameLoc(),
2128 OverloadCandidateSet::CSK_Normal);
2129 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2130 Alloc != AllocEnd; ++Alloc) {
2131 // Even member operator new/delete are implicitly treated as
2132 // static, so don't use AddMemberCandidate.
2133 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2134
2135 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2136 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2137 /*ExplicitTemplateArgs=*/nullptr, Args,
2138 Candidates,
2139 /*SuppressUserConversions=*/false);
2140 continue;
2141 }
2142
2143 FunctionDecl *Fn = cast<FunctionDecl>(D);
2144 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2145 /*SuppressUserConversions=*/false);
2146 }
2147
2148 // Do the resolution.
2149 OverloadCandidateSet::iterator Best;
2150 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2151 case OR_Success: {
2152 // Got one!
2153 FunctionDecl *FnDecl = Best->Function;
2154 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2155 Best->FoundDecl) == Sema::AR_inaccessible)
2156 return true;
2157
2158 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002159 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002160 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002161
Richard Smithb2f0f052016-10-10 18:54:32 +00002162 case OR_No_Viable_Function:
2163 // C++17 [expr.new]p13:
2164 // If no matching function is found and the allocated object type has
2165 // new-extended alignment, the alignment argument is removed from the
2166 // argument list, and overload resolution is performed again.
2167 if (PassAlignment) {
2168 PassAlignment = false;
2169 AlignArg = Args[1];
2170 Args.erase(Args.begin() + 1);
2171 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2172 Operator, &Candidates, AlignArg);
2173 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002174
Richard Smithb2f0f052016-10-10 18:54:32 +00002175 // MSVC will fall back on trying to find a matching global operator new
2176 // if operator new[] cannot be found. Also, MSVC will leak by not
2177 // generating a call to operator delete or operator delete[], but we
2178 // will not replicate that bug.
2179 // FIXME: Find out how this interacts with the std::align_val_t fallback
2180 // once MSVC implements it.
2181 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2182 S.Context.getLangOpts().MSVCCompat) {
2183 R.clear();
2184 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2185 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2186 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2187 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2188 Operator, nullptr);
2189 }
Richard Smith1cdec012013-09-29 04:40:38 +00002190
Richard Smithb2f0f052016-10-10 18:54:32 +00002191 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2192 << R.getLookupName() << Range;
2193
2194 // If we have aligned candidates, only note the align_val_t candidates
2195 // from AlignedCandidates and the non-align_val_t candidates from
2196 // Candidates.
2197 if (AlignedCandidates) {
2198 auto IsAligned = [](OverloadCandidate &C) {
2199 return C.Function->getNumParams() > 1 &&
2200 C.Function->getParamDecl(1)->getType()->isAlignValT();
2201 };
2202 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2203
2204 // This was an overaligned allocation, so list the aligned candidates
2205 // first.
2206 Args.insert(Args.begin() + 1, AlignArg);
2207 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2208 R.getNameLoc(), IsAligned);
2209 Args.erase(Args.begin() + 1);
2210 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2211 IsUnaligned);
2212 } else {
2213 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2214 }
Richard Smith1cdec012013-09-29 04:40:38 +00002215 return true;
2216
Richard Smithb2f0f052016-10-10 18:54:32 +00002217 case OR_Ambiguous:
2218 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2219 << R.getLookupName() << Range;
2220 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2221 return true;
2222
2223 case OR_Deleted: {
2224 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2225 << Best->Function->isDeleted()
2226 << R.getLookupName()
2227 << S.getDeletedOrUnavailableSuffix(Best->Function)
2228 << Range;
2229 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2230 return true;
2231 }
2232 }
2233 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002234}
2235
Richard Smithb2f0f052016-10-10 18:54:32 +00002236
Sebastian Redlfaf68082008-12-03 20:26:15 +00002237/// FindAllocationFunctions - Finds the overloads of operator new and delete
2238/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002239bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2240 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002241 bool IsArray, bool &PassAlignment,
2242 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002243 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002244 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002245 // --- Choosing an allocation function ---
2246 // C++ 5.3.4p8 - 14 & 18
2247 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2248 // in the scope of the allocated class.
2249 // 2) If an array size is given, look for operator new[], else look for
2250 // operator new.
2251 // 3) The first argument is always size_t. Append the arguments from the
2252 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002253
Richard Smithb2f0f052016-10-10 18:54:32 +00002254 SmallVector<Expr*, 8> AllocArgs;
2255 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2256
2257 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002258 // FIXME: Should the Sema create the expression and embed it in the syntax
2259 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002260 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002261 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002262 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002263 Context.getSizeType(),
2264 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002265 AllocArgs.push_back(&Size);
2266
2267 QualType AlignValT = Context.VoidTy;
2268 if (PassAlignment) {
2269 DeclareGlobalNewDelete();
2270 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2271 }
2272 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2273 if (PassAlignment)
2274 AllocArgs.push_back(&Align);
2275
2276 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002277
Douglas Gregor6642ca22010-02-26 05:06:18 +00002278 // C++ [expr.new]p8:
2279 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002280 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002281 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002282 // type, the allocation function's name is operator new[] and the
2283 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002284 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002285 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002286
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002287 QualType AllocElemType = Context.getBaseElementType(AllocType);
2288
Richard Smithb2f0f052016-10-10 18:54:32 +00002289 // Find the allocation function.
2290 {
2291 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2292
2293 // C++1z [expr.new]p9:
2294 // If the new-expression begins with a unary :: operator, the allocation
2295 // function's name is looked up in the global scope. Otherwise, if the
2296 // allocated type is a class type T or array thereof, the allocation
2297 // function's name is looked up in the scope of T.
2298 if (AllocElemType->isRecordType() && !UseGlobal)
2299 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2300
2301 // We can see ambiguity here if the allocation function is found in
2302 // multiple base classes.
2303 if (R.isAmbiguous())
2304 return true;
2305
2306 // If this lookup fails to find the name, or if the allocated type is not
2307 // a class type, the allocation function's name is looked up in the
2308 // global scope.
2309 if (R.empty())
2310 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2311
2312 assert(!R.empty() && "implicitly declared allocation functions not found");
2313 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2314
2315 // We do our own custom access checks below.
2316 R.suppressDiagnostics();
2317
2318 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2319 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002320 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002321 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002322
Richard Smithb2f0f052016-10-10 18:54:32 +00002323 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002324 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002325 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002326 return false;
2327 }
2328
Richard Smithb2f0f052016-10-10 18:54:32 +00002329 // Note, the name of OperatorNew might have been changed from array to
2330 // non-array by resolveAllocationOverload.
2331 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2332 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2333 ? OO_Array_Delete
2334 : OO_Delete);
2335
Douglas Gregor6642ca22010-02-26 05:06:18 +00002336 // C++ [expr.new]p19:
2337 //
2338 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002339 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002340 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002341 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002342 // the scope of T. If this lookup fails to find the name, or if
2343 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002344 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002345 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002346 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002347 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002348 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002349 LookupQualifiedName(FoundDelete, RD);
2350 }
John McCallfb6f5262010-03-18 08:19:33 +00002351 if (FoundDelete.isAmbiguous())
2352 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002353
Richard Smithb2f0f052016-10-10 18:54:32 +00002354 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002355 if (FoundDelete.empty()) {
2356 DeclareGlobalNewDelete();
2357 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2358 }
2359
2360 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002361
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002362 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002363
John McCalld3be2c82010-09-14 21:34:24 +00002364 // Whether we're looking for a placement operator delete is dictated
2365 // by whether we selected a placement operator new, not by whether
2366 // we had explicit placement arguments. This matters for things like
2367 // struct A { void *operator new(size_t, int = 0); ... };
2368 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002369 //
2370 // We don't have any definition for what a "placement allocation function"
2371 // is, but we assume it's any allocation function whose
2372 // parameter-declaration-clause is anything other than (size_t).
2373 //
2374 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2375 // This affects whether an exception from the constructor of an overaligned
2376 // type uses the sized or non-sized form of aligned operator delete.
2377 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2378 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002379
2380 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002381 // C++ [expr.new]p20:
2382 // A declaration of a placement deallocation function matches the
2383 // declaration of a placement allocation function if it has the
2384 // same number of parameters and, after parameter transformations
2385 // (8.3.5), all parameter types except the first are
2386 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002388 // To perform this comparison, we compute the function type that
2389 // the deallocation function should have, and use that type both
2390 // for template argument deduction and for comparison purposes.
2391 QualType ExpectedFunctionType;
2392 {
2393 const FunctionProtoType *Proto
2394 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002395
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002396 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002397 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002398 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2399 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002400
John McCalldb40c7f2010-12-14 08:05:40 +00002401 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002402 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002403 EPI.Variadic = Proto->isVariadic();
2404
Douglas Gregor6642ca22010-02-26 05:06:18 +00002405 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002406 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002407 }
2408
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002409 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002410 DEnd = FoundDelete.end();
2411 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002412 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002413 if (FunctionTemplateDecl *FnTmpl =
2414 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002415 // Perform template argument deduction to try to match the
2416 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002417 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002418 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2419 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002420 continue;
2421 } else
2422 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2423
Richard Smithbaa47832016-12-01 02:11:49 +00002424 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2425 ExpectedFunctionType,
2426 /*AdjustExcpetionSpec*/true),
2427 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002428 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002429 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002430
Richard Smithb2f0f052016-10-10 18:54:32 +00002431 if (getLangOpts().CUDA)
2432 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2433 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002434 // C++1y [expr.new]p22:
2435 // For a non-placement allocation function, the normal deallocation
2436 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002437 //
2438 // Per [expr.delete]p10, this lookup prefers a member operator delete
2439 // without a size_t argument, but prefers a non-member operator delete
2440 // with a size_t where possible (which it always is in this case).
2441 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2442 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2443 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2444 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2445 &BestDeallocFns);
2446 if (Selected)
2447 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2448 else {
2449 // If we failed to select an operator, all remaining functions are viable
2450 // but ambiguous.
2451 for (auto Fn : BestDeallocFns)
2452 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002453 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002454 }
2455
2456 // C++ [expr.new]p20:
2457 // [...] If the lookup finds a single matching deallocation
2458 // function, that function will be called; otherwise, no
2459 // deallocation function will be called.
2460 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002461 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002462
Richard Smithb2f0f052016-10-10 18:54:32 +00002463 // C++1z [expr.new]p23:
2464 // If the lookup finds a usual deallocation function (3.7.4.2)
2465 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002466 // as a placement deallocation function, would have been
2467 // selected as a match for the allocation function, the program
2468 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002469 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002470 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002471 UsualDeallocFnInfo Info(*this,
2472 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002473 // Core issue, per mail to core reflector, 2016-10-09:
2474 // If this is a member operator delete, and there is a corresponding
2475 // non-sized member operator delete, this isn't /really/ a sized
2476 // deallocation function, it just happens to have a size_t parameter.
2477 bool IsSizedDelete = Info.HasSizeT;
2478 if (IsSizedDelete && !FoundGlobalDelete) {
2479 auto NonSizedDelete =
2480 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2481 /*WantAlign*/Info.HasAlignValT);
2482 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2483 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2484 IsSizedDelete = false;
2485 }
2486
2487 if (IsSizedDelete) {
2488 SourceRange R = PlaceArgs.empty()
2489 ? SourceRange()
2490 : SourceRange(PlaceArgs.front()->getLocStart(),
2491 PlaceArgs.back()->getLocEnd());
2492 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2493 if (!OperatorDelete->isImplicit())
2494 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2495 << DeleteName;
2496 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002497 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002498
2499 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2500 Matches[0].first);
2501 } else if (!Matches.empty()) {
2502 // We found multiple suitable operators. Per [expr.new]p20, that means we
2503 // call no 'operator delete' function, but we should at least warn the user.
2504 // FIXME: Suppress this warning if the construction cannot throw.
2505 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2506 << DeleteName << AllocElemType;
2507
2508 for (auto &Match : Matches)
2509 Diag(Match.second->getLocation(),
2510 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002511 }
2512
Sebastian Redlfaf68082008-12-03 20:26:15 +00002513 return false;
2514}
2515
2516/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2517/// delete. These are:
2518/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002519/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002520/// void* operator new(std::size_t) throw(std::bad_alloc);
2521/// void* operator new[](std::size_t) throw(std::bad_alloc);
2522/// void operator delete(void *) throw();
2523/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002524/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002525/// void* operator new(std::size_t);
2526/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002527/// void operator delete(void *) noexcept;
2528/// void operator delete[](void *) noexcept;
2529/// // C++1y:
2530/// void* operator new(std::size_t);
2531/// void* operator new[](std::size_t);
2532/// void operator delete(void *) noexcept;
2533/// void operator delete[](void *) noexcept;
2534/// void operator delete(void *, std::size_t) noexcept;
2535/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002536/// @endcode
2537/// Note that the placement and nothrow forms of new are *not* implicitly
2538/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002539void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002540 if (GlobalNewDeleteDeclared)
2541 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542
Douglas Gregor87f54062009-09-15 22:30:29 +00002543 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544 // [...] The following allocation and deallocation functions (18.4) are
2545 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002546 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002547 //
Sebastian Redl37588092011-03-14 18:08:30 +00002548 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002549 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002550 // void* operator new[](std::size_t) throw(std::bad_alloc);
2551 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002552 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002553 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002554 // void* operator new(std::size_t);
2555 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002556 // void operator delete(void*) noexcept;
2557 // void operator delete[](void*) noexcept;
2558 // C++1y:
2559 // void* operator new(std::size_t);
2560 // void* operator new[](std::size_t);
2561 // void operator delete(void*) noexcept;
2562 // void operator delete[](void*) noexcept;
2563 // void operator delete(void*, std::size_t) noexcept;
2564 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002565 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002567 // new, operator new[], operator delete, operator delete[].
2568 //
2569 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2570 // "std" or "bad_alloc" as necessary to form the exception specification.
2571 // However, we do not make these implicit declarations visible to name
2572 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002573 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002574 // The "std::bad_alloc" class has not yet been declared, so build it
2575 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2577 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002578 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002580 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002581 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002582 }
Richard Smith59139022016-09-30 22:41:36 +00002583 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002584 // The "std::align_val_t" enum class has not yet been declared, so build it
2585 // implicitly.
2586 auto *AlignValT = EnumDecl::Create(
2587 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2588 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2589 AlignValT->setIntegerType(Context.getSizeType());
2590 AlignValT->setPromotionType(Context.getSizeType());
2591 AlignValT->setImplicit(true);
2592 StdAlignValT = AlignValT;
2593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002594
Sebastian Redlfaf68082008-12-03 20:26:15 +00002595 GlobalNewDeleteDeclared = true;
2596
2597 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2598 QualType SizeT = Context.getSizeType();
2599
Richard Smith96269c52016-09-29 22:49:46 +00002600 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2601 QualType Return, QualType Param) {
2602 llvm::SmallVector<QualType, 3> Params;
2603 Params.push_back(Param);
2604
2605 // Create up to four variants of the function (sized/aligned).
2606 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2607 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002608 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002609
2610 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2611 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2612 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002613 if (Sized)
2614 Params.push_back(SizeT);
2615
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002616 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002617 if (Aligned)
2618 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2619
2620 DeclareGlobalAllocationFunction(
2621 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2622
2623 if (Aligned)
2624 Params.pop_back();
2625 }
2626 }
2627 };
2628
2629 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2630 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2631 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2632 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002633}
2634
2635/// DeclareGlobalAllocationFunction - Declares a single implicit global
2636/// allocation function if it doesn't already exist.
2637void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002638 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002639 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002640 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2641
2642 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002643 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2644 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2645 Alloc != AllocEnd; ++Alloc) {
2646 // Only look at non-template functions, as it is the predefined,
2647 // non-templated allocation function we are trying to declare here.
2648 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002649 if (Func->getNumParams() == Params.size()) {
2650 llvm::SmallVector<QualType, 3> FuncParams;
2651 for (auto *P : Func->parameters())
2652 FuncParams.push_back(
2653 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2654 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002655 // Make the function visible to name lookup, even if we found it in
2656 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002657 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002658 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002659 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002660 }
Chandler Carruth93538422010-02-03 11:02:14 +00002661 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002662 }
2663 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002664
Richard Smithc015bc22014-02-07 22:39:53 +00002665 FunctionProtoType::ExtProtoInfo EPI;
2666
Richard Smithf8b417c2014-02-08 00:42:45 +00002667 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002669 = (Name.getCXXOverloadedOperator() == OO_New ||
2670 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002671 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002672 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002673 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002674 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002675 EPI.ExceptionSpec.Type = EST_Dynamic;
2676 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002677 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002678 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002679 EPI.ExceptionSpec =
2680 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682
Artem Belevich07db5cf2016-10-21 20:34:05 +00002683 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2684 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2685 FunctionDecl *Alloc = FunctionDecl::Create(
2686 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2687 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2688 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002689 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002690 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002691
Artem Belevich07db5cf2016-10-21 20:34:05 +00002692 // Implicit sized deallocation functions always have default visibility.
2693 Alloc->addAttr(
2694 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Artem Belevich07db5cf2016-10-21 20:34:05 +00002696 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2697 for (QualType T : Params) {
2698 ParamDecls.push_back(ParmVarDecl::Create(
2699 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2700 /*TInfo=*/nullptr, SC_None, nullptr));
2701 ParamDecls.back()->setImplicit();
2702 }
2703 Alloc->setParams(ParamDecls);
2704 if (ExtraAttr)
2705 Alloc->addAttr(ExtraAttr);
2706 Context.getTranslationUnitDecl()->addDecl(Alloc);
2707 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2708 };
2709
2710 if (!LangOpts.CUDA)
2711 CreateAllocationFunctionDecl(nullptr);
2712 else {
2713 // Host and device get their own declaration so each can be
2714 // defined or re-declared independently.
2715 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2716 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002717 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002718}
2719
Richard Smith1cdec012013-09-29 04:40:38 +00002720FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2721 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002722 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002723 DeclarationName Name) {
2724 DeclareGlobalNewDelete();
2725
2726 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2727 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2728
Richard Smithb2f0f052016-10-10 18:54:32 +00002729 // FIXME: It's possible for this to result in ambiguity, through a
2730 // user-declared variadic operator delete or the enable_if attribute. We
2731 // should probably not consider those cases to be usual deallocation
2732 // functions. But for now we just make an arbitrary choice in that case.
2733 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2734 Overaligned);
2735 assert(Result.FD && "operator delete missing from global scope?");
2736 return Result.FD;
2737}
Richard Smith1cdec012013-09-29 04:40:38 +00002738
Richard Smithb2f0f052016-10-10 18:54:32 +00002739FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2740 CXXRecordDecl *RD) {
2741 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002742
Richard Smithb2f0f052016-10-10 18:54:32 +00002743 FunctionDecl *OperatorDelete = nullptr;
2744 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2745 return nullptr;
2746 if (OperatorDelete)
2747 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002748
Richard Smithb2f0f052016-10-10 18:54:32 +00002749 // If there's no class-specific operator delete, look up the global
2750 // non-array delete.
2751 return FindUsualDeallocationFunction(
2752 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2753 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002754}
2755
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002756bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2757 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002758 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002759 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002760 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002761 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762
John McCall27b18f82009-11-17 02:14:36 +00002763 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002764 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002765
Chandler Carruthb6f99172010-06-28 00:30:51 +00002766 Found.suppressDiagnostics();
2767
Richard Smithb2f0f052016-10-10 18:54:32 +00002768 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002769
Richard Smithb2f0f052016-10-10 18:54:32 +00002770 // C++17 [expr.delete]p10:
2771 // If the deallocation functions have class scope, the one without a
2772 // parameter of type std::size_t is selected.
2773 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2774 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2775 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002776
Richard Smithb2f0f052016-10-10 18:54:32 +00002777 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002778 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002779 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002780
Richard Smithb2f0f052016-10-10 18:54:32 +00002781 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002782 if (Operator->isDeleted()) {
2783 if (Diagnose) {
2784 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002785 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002786 }
2787 return true;
2788 }
2789
Richard Smith921bd202012-02-26 09:11:52 +00002790 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002791 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002792 return true;
2793
John McCall66a87592010-08-04 00:31:26 +00002794 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002795 }
John McCall66a87592010-08-04 00:31:26 +00002796
Richard Smithb2f0f052016-10-10 18:54:32 +00002797 // We found multiple suitable operators; complain about the ambiguity.
2798 // FIXME: The standard doesn't say to do this; it appears that the intent
2799 // is that this should never happen.
2800 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002801 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002802 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2803 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002804 for (auto &Match : Matches)
2805 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002806 }
John McCall66a87592010-08-04 00:31:26 +00002807 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002808 }
2809
2810 // We did find operator delete/operator delete[] declarations, but
2811 // none of them were suitable.
2812 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002813 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002814 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2815 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816
Richard Smithb2f0f052016-10-10 18:54:32 +00002817 for (NamedDecl *D : Found)
2818 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002819 diag::note_member_declared_here) << Name;
2820 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002821 return true;
2822 }
2823
Craig Topperc3ec1492014-05-26 06:22:03 +00002824 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002825 return false;
2826}
2827
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002828namespace {
2829/// \brief Checks whether delete-expression, and new-expression used for
2830/// initializing deletee have the same array form.
2831class MismatchingNewDeleteDetector {
2832public:
2833 enum MismatchResult {
2834 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2835 NoMismatch,
2836 /// Indicates that variable is initialized with mismatching form of \a new.
2837 VarInitMismatches,
2838 /// Indicates that member is initialized with mismatching form of \a new.
2839 MemberInitMismatches,
2840 /// Indicates that 1 or more constructors' definitions could not been
2841 /// analyzed, and they will be checked again at the end of translation unit.
2842 AnalyzeLater
2843 };
2844
2845 /// \param EndOfTU True, if this is the final analysis at the end of
2846 /// translation unit. False, if this is the initial analysis at the point
2847 /// delete-expression was encountered.
2848 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002849 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002850 HasUndefinedConstructors(false) {}
2851
2852 /// \brief Checks whether pointee of a delete-expression is initialized with
2853 /// matching form of new-expression.
2854 ///
2855 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2856 /// point where delete-expression is encountered, then a warning will be
2857 /// issued immediately. If return value is \c AnalyzeLater at the point where
2858 /// delete-expression is seen, then member will be analyzed at the end of
2859 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2860 /// couldn't be analyzed. If at least one constructor initializes the member
2861 /// with matching type of new, the return value is \c NoMismatch.
2862 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2863 /// \brief Analyzes a class member.
2864 /// \param Field Class member to analyze.
2865 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2866 /// for deleting the \p Field.
2867 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002868 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002869 /// List of mismatching new-expressions used for initialization of the pointee
2870 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2871 /// Indicates whether delete-expression was in array form.
2872 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002873
2874private:
2875 const bool EndOfTU;
2876 /// \brief Indicates that there is at least one constructor without body.
2877 bool HasUndefinedConstructors;
2878 /// \brief Returns \c CXXNewExpr from given initialization expression.
2879 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002880 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002881 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2882 /// \brief Returns whether member is initialized with mismatching form of
2883 /// \c new either by the member initializer or in-class initialization.
2884 ///
2885 /// If bodies of all constructors are not visible at the end of translation
2886 /// unit or at least one constructor initializes member with the matching
2887 /// form of \c new, mismatch cannot be proven, and this function will return
2888 /// \c NoMismatch.
2889 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2890 /// \brief Returns whether variable is initialized with mismatching form of
2891 /// \c new.
2892 ///
2893 /// If variable is initialized with matching form of \c new or variable is not
2894 /// initialized with a \c new expression, this function will return true.
2895 /// If variable is initialized with mismatching form of \c new, returns false.
2896 /// \param D Variable to analyze.
2897 bool hasMatchingVarInit(const DeclRefExpr *D);
2898 /// \brief Checks whether the constructor initializes pointee with mismatching
2899 /// form of \c new.
2900 ///
2901 /// Returns true, if member is initialized with matching form of \c new in
2902 /// member initializer list. Returns false, if member is initialized with the
2903 /// matching form of \c new in this constructor's initializer or given
2904 /// constructor isn't defined at the point where delete-expression is seen, or
2905 /// member isn't initialized by the constructor.
2906 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2907 /// \brief Checks whether member is initialized with matching form of
2908 /// \c new in member initializer list.
2909 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2910 /// Checks whether member is initialized with mismatching form of \c new by
2911 /// in-class initializer.
2912 MismatchResult analyzeInClassInitializer();
2913};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002914}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002915
2916MismatchingNewDeleteDetector::MismatchResult
2917MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2918 NewExprs.clear();
2919 assert(DE && "Expected delete-expression");
2920 IsArrayForm = DE->isArrayForm();
2921 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2922 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2923 return analyzeMemberExpr(ME);
2924 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2925 if (!hasMatchingVarInit(D))
2926 return VarInitMismatches;
2927 }
2928 return NoMismatch;
2929}
2930
2931const CXXNewExpr *
2932MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2933 assert(E != nullptr && "Expected a valid initializer expression");
2934 E = E->IgnoreParenImpCasts();
2935 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2936 if (ILE->getNumInits() == 1)
2937 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2938 }
2939
2940 return dyn_cast_or_null<const CXXNewExpr>(E);
2941}
2942
2943bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2944 const CXXCtorInitializer *CI) {
2945 const CXXNewExpr *NE = nullptr;
2946 if (Field == CI->getMember() &&
2947 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2948 if (NE->isArray() == IsArrayForm)
2949 return true;
2950 else
2951 NewExprs.push_back(NE);
2952 }
2953 return false;
2954}
2955
2956bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2957 const CXXConstructorDecl *CD) {
2958 if (CD->isImplicit())
2959 return false;
2960 const FunctionDecl *Definition = CD;
2961 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2962 HasUndefinedConstructors = true;
2963 return EndOfTU;
2964 }
2965 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2966 if (hasMatchingNewInCtorInit(CI))
2967 return true;
2968 }
2969 return false;
2970}
2971
2972MismatchingNewDeleteDetector::MismatchResult
2973MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2974 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002975 const Expr *InitExpr = Field->getInClassInitializer();
2976 if (!InitExpr)
2977 return EndOfTU ? NoMismatch : AnalyzeLater;
2978 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002979 if (NE->isArray() != IsArrayForm) {
2980 NewExprs.push_back(NE);
2981 return MemberInitMismatches;
2982 }
2983 }
2984 return NoMismatch;
2985}
2986
2987MismatchingNewDeleteDetector::MismatchResult
2988MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2989 bool DeleteWasArrayForm) {
2990 assert(Field != nullptr && "Analysis requires a valid class member.");
2991 this->Field = Field;
2992 IsArrayForm = DeleteWasArrayForm;
2993 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2994 for (const auto *CD : RD->ctors()) {
2995 if (hasMatchingNewInCtor(CD))
2996 return NoMismatch;
2997 }
2998 if (HasUndefinedConstructors)
2999 return EndOfTU ? NoMismatch : AnalyzeLater;
3000 if (!NewExprs.empty())
3001 return MemberInitMismatches;
3002 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3003 : NoMismatch;
3004}
3005
3006MismatchingNewDeleteDetector::MismatchResult
3007MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3008 assert(ME != nullptr && "Expected a member expression");
3009 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3010 return analyzeField(F, IsArrayForm);
3011 return NoMismatch;
3012}
3013
3014bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3015 const CXXNewExpr *NE = nullptr;
3016 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3017 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3018 NE->isArray() != IsArrayForm) {
3019 NewExprs.push_back(NE);
3020 }
3021 }
3022 return NewExprs.empty();
3023}
3024
3025static void
3026DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3027 const MismatchingNewDeleteDetector &Detector) {
3028 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3029 FixItHint H;
3030 if (!Detector.IsArrayForm)
3031 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3032 else {
3033 SourceLocation RSquare = Lexer::findLocationAfterToken(
3034 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3035 SemaRef.getLangOpts(), true);
3036 if (RSquare.isValid())
3037 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3038 }
3039 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3040 << Detector.IsArrayForm << H;
3041
3042 for (const auto *NE : Detector.NewExprs)
3043 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3044 << Detector.IsArrayForm;
3045}
3046
3047void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3048 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3049 return;
3050 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3051 switch (Detector.analyzeDeleteExpr(DE)) {
3052 case MismatchingNewDeleteDetector::VarInitMismatches:
3053 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3054 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3055 break;
3056 }
3057 case MismatchingNewDeleteDetector::AnalyzeLater: {
3058 DeleteExprs[Detector.Field].push_back(
3059 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3060 break;
3061 }
3062 case MismatchingNewDeleteDetector::NoMismatch:
3063 break;
3064 }
3065}
3066
3067void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3068 bool DeleteWasArrayForm) {
3069 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3070 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3071 case MismatchingNewDeleteDetector::VarInitMismatches:
3072 llvm_unreachable("This analysis should have been done for class members.");
3073 case MismatchingNewDeleteDetector::AnalyzeLater:
3074 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3075 "translation unit.");
3076 case MismatchingNewDeleteDetector::MemberInitMismatches:
3077 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3078 break;
3079 case MismatchingNewDeleteDetector::NoMismatch:
3080 break;
3081 }
3082}
3083
Sebastian Redlbd150f42008-11-21 19:14:01 +00003084/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3085/// @code ::delete ptr; @endcode
3086/// or
3087/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003088ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003089Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003090 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003091 // C++ [expr.delete]p1:
3092 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003093 // non-explicit conversion function to a pointer type. The result has type
3094 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003095 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003096 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3097
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003098 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003099 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003100 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003101 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003102
John Wiegley01296292011-04-08 18:41:53 +00003103 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003104 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003105 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003106 if (Ex.isInvalid())
3107 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003108
John Wiegley01296292011-04-08 18:41:53 +00003109 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003110
Richard Smithccc11812013-05-21 19:05:48 +00003111 class DeleteConverter : public ContextualImplicitConverter {
3112 public:
3113 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114
Craig Toppere14c0f82014-03-12 04:55:44 +00003115 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003116 // FIXME: If we have an operator T* and an operator void*, we must pick
3117 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003118 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003119 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003120 return true;
3121 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003122 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003123
Richard Smithccc11812013-05-21 19:05:48 +00003124 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003125 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003126 return S.Diag(Loc, diag::err_delete_operand) << T;
3127 }
3128
3129 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003130 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003131 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3132 }
3133
3134 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003135 QualType T,
3136 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003137 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3138 }
3139
3140 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003141 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003142 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3143 << ConvTy;
3144 }
3145
3146 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003147 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003148 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3149 }
3150
3151 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003152 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003153 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3154 << ConvTy;
3155 }
3156
3157 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003158 QualType T,
3159 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003160 llvm_unreachable("conversion functions are permitted");
3161 }
3162 } Converter;
3163
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003164 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003165 if (Ex.isInvalid())
3166 return ExprError();
3167 Type = Ex.get()->getType();
3168 if (!Converter.match(Type))
3169 // FIXME: PerformContextualImplicitConversion should return ExprError
3170 // itself in this case.
3171 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003172
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003173 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003174 QualType PointeeElem = Context.getBaseElementType(Pointee);
3175
Yaxun Liub34ec822017-04-11 17:24:23 +00003176 if (Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003177 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003178 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003179 << Pointee.getUnqualifiedType()
3180 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003181
Craig Topperc3ec1492014-05-26 06:22:03 +00003182 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003183 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003185 // effectively bans deletion of "void*". However, most compilers support
3186 // this, so we treat it as a warning unless we're in a SFINAE context.
3187 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003188 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003189 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003190 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003191 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003192 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003193 // FIXME: This can result in errors if the definition was imported from a
3194 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003195 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003196 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003197 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3198 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3199 }
3200 }
3201
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003202 if (Pointee->isArrayType() && !ArrayForm) {
3203 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003204 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003205 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003206 ArrayForm = true;
3207 }
3208
Anders Carlssona471db02009-08-16 20:29:29 +00003209 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3210 ArrayForm ? OO_Array_Delete : OO_Delete);
3211
Eli Friedmanae4280f2011-07-26 22:25:31 +00003212 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003214 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3215 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003216 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003217
John McCall284c48f2011-01-27 09:37:56 +00003218 // If we're allocating an array of records, check whether the
3219 // usual operator delete[] has a size_t parameter.
3220 if (ArrayForm) {
3221 // If the user specifically asked to use the global allocator,
3222 // we'll need to do the lookup into the class.
3223 if (UseGlobal)
3224 UsualArrayDeleteWantsSize =
3225 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3226
3227 // Otherwise, the usual operator delete[] should be the
3228 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003229 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003230 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003231 UsualDeallocFnInfo(*this,
3232 DeclAccessPair::make(OperatorDelete, AS_public))
3233 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003234 }
3235
Richard Smitheec915d62012-02-18 04:13:32 +00003236 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003237 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003238 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003239 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003240 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3241 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003242 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003243
Nico Weber5a9259c2016-01-15 21:45:31 +00003244 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3245 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3246 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3247 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003249
Richard Smithb2f0f052016-10-10 18:54:32 +00003250 if (!OperatorDelete) {
3251 bool IsComplete = isCompleteType(StartLoc, Pointee);
3252 bool CanProvideSize =
3253 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3254 Pointee.isDestructedType());
3255 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3256
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003257 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003258 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3259 Overaligned, DeleteName);
3260 }
Mike Stump11289f42009-09-09 15:08:12 +00003261
Eli Friedmanfa0df832012-02-02 03:46:19 +00003262 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003263
Douglas Gregorfa778132011-02-01 15:50:11 +00003264 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003265 if (PointeeRD) {
3266 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003267 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003268 PDiag(diag::err_access_dtor) << PointeeElem);
3269 }
3270 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003271
3272 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3273 *this);
Sebastian Redlbd150f42008-11-21 19:14:01 +00003274 }
3275
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003276 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003277 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3278 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003279 AnalyzeDeleteExprMismatch(Result);
3280 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003281}
3282
Nico Weber5a9259c2016-01-15 21:45:31 +00003283void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3284 bool IsDelete, bool CallCanBeVirtual,
3285 bool WarnOnNonAbstractTypes,
3286 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003287 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003288 return;
3289
3290 // C++ [expr.delete]p3:
3291 // In the first alternative (delete object), if the static type of the
3292 // object to be deleted is different from its dynamic type, the static
3293 // type shall be a base class of the dynamic type of the object to be
3294 // deleted and the static type shall have a virtual destructor or the
3295 // behavior is undefined.
3296 //
3297 const CXXRecordDecl *PointeeRD = dtor->getParent();
3298 // Note: a final class cannot be derived from, no issue there
3299 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3300 return;
3301
Nico Weberbf2260c2017-08-31 06:17:08 +00003302 // If the superclass is in a system header, there's nothing that can be done.
3303 // The `delete` (where we emit the warning) can be in a system header,
3304 // what matters for this warning is where the deleted type is defined.
3305 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3306 return;
3307
Nico Weber5a9259c2016-01-15 21:45:31 +00003308 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3309 if (PointeeRD->isAbstract()) {
3310 // If the class is abstract, we warn by default, because we're
3311 // sure the code has undefined behavior.
3312 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3313 << ClassType;
3314 } else if (WarnOnNonAbstractTypes) {
3315 // Otherwise, if this is not an array delete, it's a bit suspect,
3316 // but not necessarily wrong.
3317 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3318 << ClassType;
3319 }
3320 if (!IsDelete) {
3321 std::string TypeStr;
3322 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3323 Diag(DtorLoc, diag::note_delete_non_virtual)
3324 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3325 }
3326}
3327
Richard Smith03a4aa32016-06-23 19:02:52 +00003328Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3329 SourceLocation StmtLoc,
3330 ConditionKind CK) {
3331 ExprResult E =
3332 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3333 if (E.isInvalid())
3334 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003335 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3336 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003337}
3338
Douglas Gregor633caca2009-11-23 23:44:04 +00003339/// \brief Check the use of the given variable as a C++ condition in an if,
3340/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003341ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003342 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003343 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003344 if (ConditionVar->isInvalidDecl())
3345 return ExprError();
3346
Douglas Gregor633caca2009-11-23 23:44:04 +00003347 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348
Douglas Gregor633caca2009-11-23 23:44:04 +00003349 // C++ [stmt.select]p2:
3350 // The declarator shall not specify a function or an array.
3351 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003353 diag::err_invalid_use_of_function_type)
3354 << ConditionVar->getSourceRange());
3355 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003357 diag::err_invalid_use_of_array_type)
3358 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003360 ExprResult Condition = DeclRefExpr::Create(
3361 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3362 /*enclosing*/ false, ConditionVar->getLocation(),
3363 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003364
Eli Friedmanfa0df832012-02-02 03:46:19 +00003365 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003366
Richard Smith03a4aa32016-06-23 19:02:52 +00003367 switch (CK) {
3368 case ConditionKind::Boolean:
3369 return CheckBooleanCondition(StmtLoc, Condition.get());
3370
Richard Smithb130fe72016-06-23 19:16:49 +00003371 case ConditionKind::ConstexprIf:
3372 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3373
Richard Smith03a4aa32016-06-23 19:02:52 +00003374 case ConditionKind::Switch:
3375 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377
Richard Smith03a4aa32016-06-23 19:02:52 +00003378 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003379}
3380
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003381/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003382ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003383 // C++ 6.4p4:
3384 // The value of a condition that is an initialized declaration in a statement
3385 // other than a switch statement is the value of the declared variable
3386 // implicitly converted to type bool. If that conversion is ill-formed, the
3387 // program is ill-formed.
3388 // The value of a condition that is an expression is the value of the
3389 // expression, implicitly converted to bool.
3390 //
Richard Smithb130fe72016-06-23 19:16:49 +00003391 // FIXME: Return this value to the caller so they don't need to recompute it.
3392 llvm::APSInt Value(/*BitWidth*/1);
3393 return (IsConstexpr && !CondExpr->isValueDependent())
3394 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3395 CCEK_ConstexprIf)
3396 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003397}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003398
3399/// Helper function to determine whether this is the (deprecated) C++
3400/// conversion from a string literal to a pointer to non-const char or
3401/// non-const wchar_t (for narrow and wide string literals,
3402/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003403bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003404Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3405 // Look inside the implicit cast, if it exists.
3406 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3407 From = Cast->getSubExpr();
3408
3409 // A string literal (2.13.4) that is not a wide string literal can
3410 // be converted to an rvalue of type "pointer to char"; a wide
3411 // string literal can be converted to an rvalue of type "pointer
3412 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003413 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003414 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003415 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003416 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003417 // This conversion is considered only when there is an
3418 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003419 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3420 switch (StrLit->getKind()) {
3421 case StringLiteral::UTF8:
3422 case StringLiteral::UTF16:
3423 case StringLiteral::UTF32:
3424 // We don't allow UTF literals to be implicitly converted
3425 break;
3426 case StringLiteral::Ascii:
3427 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3428 ToPointeeType->getKind() == BuiltinType::Char_S);
3429 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003430 return Context.typesAreCompatible(Context.getWideCharType(),
3431 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003432 }
3433 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003434 }
3435
3436 return false;
3437}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003438
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003440 SourceLocation CastLoc,
3441 QualType Ty,
3442 CastKind Kind,
3443 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003444 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003445 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003446 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003447 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003448 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003449 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003450 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003451 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Richard Smith72d74052013-07-20 19:41:36 +00003453 if (S.RequireNonAbstractType(CastLoc, Ty,
3454 diag::err_allocation_of_abstract_type))
3455 return ExprError();
3456
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003457 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003458 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Richard Smith5179eb72016-06-28 19:03:57 +00003460 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3461 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003462 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003463 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003464
Richard Smithf8adcdc2014-07-17 05:12:35 +00003465 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003466 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003467 ConstructorArgs, HadMultipleCandidates,
3468 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3469 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003470 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003471 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003473 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
John McCalle3027922010-08-25 11:45:40 +00003476 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003477 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
Richard Smithd3f2d322015-02-24 21:16:19 +00003479 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003480 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003481 return ExprError();
3482
Douglas Gregora4253922010-04-16 22:17:36 +00003483 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003484 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3485 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003486 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003487 if (Result.isInvalid())
3488 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003489 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003490 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3491 CK_UserDefinedConversion, Result.get(),
3492 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
Douglas Gregor668443e2011-01-20 00:18:04 +00003494 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003495 }
3496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497}
Douglas Gregora4253922010-04-16 22:17:36 +00003498
Douglas Gregor5fb53972009-01-14 15:45:31 +00003499/// PerformImplicitConversion - Perform an implicit conversion of the
3500/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003501/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003502/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003503/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003504ExprResult
3505Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003506 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003507 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003508 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003509 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003510 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003511 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3512 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003513 if (Res.isInvalid())
3514 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003515 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003516 break;
John Wiegley01296292011-04-08 18:41:53 +00003517 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003518
Anders Carlsson110b07b2009-09-15 06:28:28 +00003519 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003521 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003522 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003523 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003524 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003525 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003526 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527
Anders Carlsson110b07b2009-09-15 06:28:28 +00003528 // If the user-defined conversion is specified by a conversion function,
3529 // the initial standard conversion sequence converts the source type to
3530 // the implicit object parameter of the conversion function.
3531 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003532 } else {
3533 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003534 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003535 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003536 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003538 // initial standard conversion sequence converts the source type to
3539 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003540 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542 }
Richard Smith72d74052013-07-20 19:41:36 +00003543 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003544 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003545 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003546 PerformImplicitConversion(From, BeforeToType,
3547 ICS.UserDefined.Before, AA_Converting,
3548 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003549 if (Res.isInvalid())
3550 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003551 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553
3554 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003555 = BuildCXXCastArgument(*this,
3556 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003557 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003558 CastKind, cast<CXXMethodDecl>(FD),
3559 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003560 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003561 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003562
3563 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003564 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003565
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003566 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003567
Richard Smith507840d2011-11-29 22:48:16 +00003568 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3569 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003570 }
John McCall0d1da222010-01-12 00:44:57 +00003571
3572 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003573 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003574 PDiag(diag::err_typecheck_ambiguous_condition)
3575 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003576 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577
Douglas Gregor39c16d42008-10-24 04:54:22 +00003578 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003579 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003580
3581 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003582 bool Diagnosed =
3583 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3584 From->getType(), From, Action);
3585 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003586 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003587 }
3588
3589 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003590 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003591}
3592
Richard Smith507840d2011-11-29 22:48:16 +00003593/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003594/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003595/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003596/// expression. Flavor is the context in which we're performing this
3597/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003598ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003599Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003600 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003601 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003602 CheckedConversionKind CCK) {
3603 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003604
Mike Stump87c57ac2009-05-16 07:39:55 +00003605 // Overall FIXME: we are recomputing too many types here and doing far too
3606 // much extra work. What this means is that we need to keep track of more
3607 // information that is computed when we try the implicit conversion initially,
3608 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003609 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003610
Douglas Gregor2fe98832008-11-03 19:09:14 +00003611 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003612 // FIXME: When can ToType be a reference type?
3613 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003614 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003615 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003616 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003617 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003618 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003619 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003620 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003621 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3622 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003623 ConstructorArgs, /*HadMultipleCandidates*/ false,
3624 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3625 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003626 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003627 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003628 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3629 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003630 From, /*HadMultipleCandidates*/ false,
3631 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3632 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003633 }
3634
Douglas Gregor980fb162010-04-29 18:24:40 +00003635 // Resolve overloaded function references.
3636 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3637 DeclAccessPair Found;
3638 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3639 true, Found);
3640 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003641 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003642
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003643 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003644 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregor980fb162010-04-29 18:24:40 +00003646 From = FixOverloadedFunctionReference(From, Found, Fn);
3647 FromType = From->getType();
3648 }
3649
Richard Smitha23ab512013-05-23 00:30:41 +00003650 // If we're converting to an atomic type, first convert to the corresponding
3651 // non-atomic type.
3652 QualType ToAtomicType;
3653 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3654 ToAtomicType = ToType;
3655 ToType = ToAtomic->getValueType();
3656 }
3657
George Burgess IV8d141e02015-12-14 22:00:49 +00003658 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003659 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003660 switch (SCS.First) {
3661 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003662 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3663 FromType = FromAtomic->getValueType().getUnqualifiedType();
3664 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3665 From, /*BasePath=*/nullptr, VK_RValue);
3666 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003667 break;
3668
Eli Friedman946b7b52012-01-24 22:51:26 +00003669 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003670 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003671 ExprResult FromRes = DefaultLvalueConversion(From);
3672 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003673 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003674 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003675 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003676 }
John McCall34376a62010-12-04 03:47:34 +00003677
Douglas Gregor39c16d42008-10-24 04:54:22 +00003678 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003679 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003680 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003681 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003682 break;
3683
3684 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003685 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003686 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003687 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003688 break;
3689
3690 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003691 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003692 }
3693
Richard Smith507840d2011-11-29 22:48:16 +00003694 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003695 switch (SCS.Second) {
3696 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003697 // C++ [except.spec]p5:
3698 // [For] assignment to and initialization of pointers to functions,
3699 // pointers to member functions, and references to functions: the
3700 // target entity shall allow at least the exceptions allowed by the
3701 // source value in the assignment or initialization.
3702 switch (Action) {
3703 case AA_Assigning:
3704 case AA_Initializing:
3705 // Note, function argument passing and returning are initialization.
3706 case AA_Passing:
3707 case AA_Returning:
3708 case AA_Sending:
3709 case AA_Passing_CFAudited:
3710 if (CheckExceptionSpecCompatibility(From, ToType))
3711 return ExprError();
3712 break;
3713
3714 case AA_Casting:
3715 case AA_Converting:
3716 // Casts and implicit conversions are not initialization, so are not
3717 // checked for exception specification mismatches.
3718 break;
3719 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003720 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003721 break;
3722
3723 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003724 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003725 if (ToType->isBooleanType()) {
3726 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3727 SCS.Second == ICK_Integral_Promotion &&
3728 "only enums with fixed underlying type can promote to bool");
3729 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003730 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003731 } else {
3732 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003733 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003734 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003735 break;
3736
3737 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003738 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003739 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003740 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003741 break;
3742
3743 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003744 case ICK_Complex_Conversion: {
3745 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3746 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3747 CastKind CK;
3748 if (FromEl->isRealFloatingType()) {
3749 if (ToEl->isRealFloatingType())
3750 CK = CK_FloatingComplexCast;
3751 else
3752 CK = CK_FloatingComplexToIntegralComplex;
3753 } else if (ToEl->isRealFloatingType()) {
3754 CK = CK_IntegralComplexToFloatingComplex;
3755 } else {
3756 CK = CK_IntegralComplexCast;
3757 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003758 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003759 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003760 break;
John McCall8cb679e2010-11-15 09:13:47 +00003761 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003762
Douglas Gregor39c16d42008-10-24 04:54:22 +00003763 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003764 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003765 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003766 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003767 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003768 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003769 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003770 break;
3771
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003772 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003773 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003774 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003775 break;
3776
John McCall31168b02011-06-15 23:02:42 +00003777 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003778 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003779 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003780 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003781 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003782 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003783 diag::ext_typecheck_convert_incompatible_pointer)
3784 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003785 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003786 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003787 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003788 diag::ext_typecheck_convert_incompatible_pointer)
3789 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003790 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003791
Douglas Gregor33823722011-06-11 01:09:30 +00003792 if (From->getType()->isObjCObjectPointerType() &&
3793 ToType->isObjCObjectPointerType())
3794 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00003795 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3796 !CheckObjCARCUnavailableWeakConversion(ToType,
3797 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003798 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003799 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003800 diag::err_arc_weak_unavailable_assign);
3801 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003802 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003803 diag::err_arc_convesion_of_weak_unavailable)
3804 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003805 << From->getSourceRange();
3806 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003807
John McCall8cb679e2010-11-15 09:13:47 +00003808 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003809 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003810 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003811 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003812
3813 // Make sure we extend blocks if necessary.
3814 // FIXME: doing this here is really ugly.
3815 if (Kind == CK_BlockPointerToObjCPointerCast) {
3816 ExprResult E = From;
3817 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003818 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003819 }
Brian Kelley11352a82017-03-29 18:09:02 +00003820 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3821 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003822 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003823 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003824 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003827 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003828 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003829 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003830 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003831 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003832 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003833 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003834
3835 // We may not have been able to figure out what this member pointer resolved
3836 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003837 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003838 (void)isCompleteType(From->getExprLoc(), From->getType());
3839 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003840 }
David Majnemerd96b9972014-08-08 00:10:39 +00003841
Richard Smith507840d2011-11-29 22:48:16 +00003842 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003843 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003844 break;
3845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003847 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003848 // Perform half-to-boolean conversion via float.
3849 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003850 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003851 FromType = Context.FloatTy;
3852 }
3853
Richard Smith507840d2011-11-29 22:48:16 +00003854 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003855 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003856 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003857 break;
3858
Douglas Gregor88d292c2010-05-13 16:44:06 +00003859 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003860 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003862 ToType.getNonReferenceType(),
3863 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003865 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003866 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003867 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003868
Richard Smith507840d2011-11-29 22:48:16 +00003869 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3870 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003871 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003872 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003873 }
3874
Douglas Gregor46188682010-05-18 22:42:18 +00003875 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003876 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003877 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003878 break;
3879
George Burgess IVdf1ed002016-01-13 01:52:39 +00003880 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003881 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003882 Expr *Elem = prepareVectorSplat(ToType, From).get();
3883 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3884 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003885 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Douglas Gregor46188682010-05-18 22:42:18 +00003888 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003889 // Case 1. x -> _Complex y
3890 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3891 QualType ElType = ToComplex->getElementType();
3892 bool isFloatingComplex = ElType->isRealFloatingType();
3893
3894 // x -> y
3895 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3896 // do nothing
3897 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003898 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003899 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003900 } else {
3901 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003902 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003903 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003904 }
3905 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003906 From = ImpCastExprToType(From, ToType,
3907 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003908 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003909
3910 // Case 2. _Complex x -> y
3911 } else {
3912 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3913 assert(FromComplex);
3914
3915 QualType ElType = FromComplex->getElementType();
3916 bool isFloatingComplex = ElType->isRealFloatingType();
3917
3918 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003919 From = ImpCastExprToType(From, ElType,
3920 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003921 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003922 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003923
3924 // x -> y
3925 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3926 // do nothing
3927 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003928 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003929 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003930 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003931 } else {
3932 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003933 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003934 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003935 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003936 }
3937 }
Douglas Gregor46188682010-05-18 22:42:18 +00003938 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003939
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003940 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003941 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003942 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003943 break;
3944 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003945
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003946 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003947 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003948 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003949 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3950 if (FromRes.isInvalid())
3951 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003952 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003953 assert ((ConvTy == Sema::Compatible) &&
3954 "Improper transparent union conversion");
3955 (void)ConvTy;
3956 break;
3957 }
3958
Guy Benyei259f9f42013-02-07 16:05:33 +00003959 case ICK_Zero_Event_Conversion:
3960 From = ImpCastExprToType(From, ToType,
3961 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003962 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003963 break;
3964
Egor Churaev89831422016-12-23 14:55:49 +00003965 case ICK_Zero_Queue_Conversion:
3966 From = ImpCastExprToType(From, ToType,
3967 CK_ZeroToOCLQueue,
3968 From->getValueKind()).get();
3969 break;
3970
Douglas Gregor46188682010-05-18 22:42:18 +00003971 case ICK_Lvalue_To_Rvalue:
3972 case ICK_Array_To_Pointer:
3973 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003974 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003975 case ICK_Qualification:
3976 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003977 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003978 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003979 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003980 }
3981
3982 switch (SCS.Third) {
3983 case ICK_Identity:
3984 // Nothing to do.
3985 break;
3986
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003987 case ICK_Function_Conversion:
3988 // If both sides are functions (or pointers/references to them), there could
3989 // be incompatible exception declarations.
3990 if (CheckExceptionSpecCompatibility(From, ToType))
3991 return ExprError();
3992
3993 From = ImpCastExprToType(From, ToType, CK_NoOp,
3994 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3995 break;
3996
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003997 case ICK_Qualification: {
3998 // The qualification keeps the category of the inner expression, unless the
3999 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004000 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004001 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004002 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004003 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004004
Douglas Gregore981bb02011-03-14 16:13:32 +00004005 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004006 !getLangOpts().WritableStrings) {
4007 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4008 ? diag::ext_deprecated_string_literal_conversion
4009 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004010 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004011 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004012
Douglas Gregor39c16d42008-10-24 04:54:22 +00004013 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004014 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004015
Douglas Gregor39c16d42008-10-24 04:54:22 +00004016 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004017 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004018 }
4019
Douglas Gregor298f43d2012-04-12 20:42:30 +00004020 // If this conversion sequence involved a scalar -> atomic conversion, perform
4021 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004022 if (!ToAtomicType.isNull()) {
4023 assert(Context.hasSameType(
4024 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4025 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004026 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004027 }
4028
George Burgess IV8d141e02015-12-14 22:00:49 +00004029 // If this conversion sequence succeeded and involved implicitly converting a
4030 // _Nullable type to a _Nonnull one, complain.
4031 if (CCK == CCK_ImplicitConversion)
4032 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4033 From->getLocStart());
4034
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004035 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004036}
4037
Chandler Carruth8e172c62011-05-01 06:51:22 +00004038/// \brief Check the completeness of a type in a unary type trait.
4039///
4040/// If the particular type trait requires a complete type, tries to complete
4041/// it. If completing the type fails, a diagnostic is emitted and false
4042/// returned. If completing the type succeeds or no completion was required,
4043/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004044static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004045 SourceLocation Loc,
4046 QualType ArgTy) {
4047 // C++0x [meta.unary.prop]p3:
4048 // For all of the class templates X declared in this Clause, instantiating
4049 // that template with a template argument that is a class template
4050 // specialization may result in the implicit instantiation of the template
4051 // argument if and only if the semantics of X require that the argument
4052 // must be a complete type.
4053 // We apply this rule to all the type trait expressions used to implement
4054 // these class templates. We also try to follow any GCC documented behavior
4055 // in these expressions to ensure portability of standard libraries.
4056 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004057 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004058 // is_complete_type somewhat obviously cannot require a complete type.
4059 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004060 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004061
4062 // These traits are modeled on the type predicates in C++0x
4063 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4064 // requiring a complete type, as whether or not they return true cannot be
4065 // impacted by the completeness of the type.
4066 case UTT_IsVoid:
4067 case UTT_IsIntegral:
4068 case UTT_IsFloatingPoint:
4069 case UTT_IsArray:
4070 case UTT_IsPointer:
4071 case UTT_IsLvalueReference:
4072 case UTT_IsRvalueReference:
4073 case UTT_IsMemberFunctionPointer:
4074 case UTT_IsMemberObjectPointer:
4075 case UTT_IsEnum:
4076 case UTT_IsUnion:
4077 case UTT_IsClass:
4078 case UTT_IsFunction:
4079 case UTT_IsReference:
4080 case UTT_IsArithmetic:
4081 case UTT_IsFundamental:
4082 case UTT_IsObject:
4083 case UTT_IsScalar:
4084 case UTT_IsCompound:
4085 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004086 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004087
4088 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4089 // which requires some of its traits to have the complete type. However,
4090 // the completeness of the type cannot impact these traits' semantics, and
4091 // so they don't require it. This matches the comments on these traits in
4092 // Table 49.
4093 case UTT_IsConst:
4094 case UTT_IsVolatile:
4095 case UTT_IsSigned:
4096 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004097
4098 // This type trait always returns false, checking the type is moot.
4099 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004100 return true;
4101
David Majnemer213bea32015-11-16 06:58:51 +00004102 // C++14 [meta.unary.prop]:
4103 // If T is a non-union class type, T shall be a complete type.
4104 case UTT_IsEmpty:
4105 case UTT_IsPolymorphic:
4106 case UTT_IsAbstract:
4107 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4108 if (!RD->isUnion())
4109 return !S.RequireCompleteType(
4110 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4111 return true;
4112
4113 // C++14 [meta.unary.prop]:
4114 // If T is a class type, T shall be a complete type.
4115 case UTT_IsFinal:
4116 case UTT_IsSealed:
4117 if (ArgTy->getAsCXXRecordDecl())
4118 return !S.RequireCompleteType(
4119 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4120 return true;
4121
Richard Smithf03e9082017-06-01 00:28:16 +00004122 // C++1z [meta.unary.prop]:
4123 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004124 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004125 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004126 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004127 case UTT_IsStandardLayout:
4128 case UTT_IsPOD:
4129 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004130 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4131 // or an array of unknown bound. But GCC actually imposes the same constraints
4132 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004133 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004134 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004135 case UTT_HasNothrowConstructor:
4136 case UTT_HasNothrowCopy:
4137 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004138 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004139 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004140 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004141 case UTT_HasTrivialCopy:
4142 case UTT_HasTrivialDestructor:
4143 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004144 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4145 LLVM_FALLTHROUGH;
4146
4147 // C++1z [meta.unary.prop]:
4148 // T shall be a complete type, cv void, or an array of unknown bound.
4149 case UTT_IsDestructible:
4150 case UTT_IsNothrowDestructible:
4151 case UTT_IsTriviallyDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004152 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004153 return true;
4154
4155 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004156 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004157 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004158}
4159
Joao Matosc9523d42013-03-27 01:34:16 +00004160static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4161 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004162 bool (CXXRecordDecl::*HasTrivial)() const,
4163 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004164 bool (CXXMethodDecl::*IsDesiredOp)() const)
4165{
4166 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4167 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4168 return true;
4169
4170 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4171 DeclarationNameInfo NameInfo(Name, KeyLoc);
4172 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4173 if (Self.LookupQualifiedName(Res, RD)) {
4174 bool FoundOperator = false;
4175 Res.suppressDiagnostics();
4176 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4177 Op != OpEnd; ++Op) {
4178 if (isa<FunctionTemplateDecl>(*Op))
4179 continue;
4180
4181 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4182 if((Operator->*IsDesiredOp)()) {
4183 FoundOperator = true;
4184 const FunctionProtoType *CPT =
4185 Operator->getType()->getAs<FunctionProtoType>();
4186 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004187 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004188 return false;
4189 }
4190 }
4191 return FoundOperator;
4192 }
4193 return false;
4194}
4195
Alp Toker95e7ff22014-01-01 05:57:51 +00004196static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004197 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004198 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004199
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004200 ASTContext &C = Self.Context;
4201 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004202 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004203 // Type trait expressions corresponding to the primary type category
4204 // predicates in C++0x [meta.unary.cat].
4205 case UTT_IsVoid:
4206 return T->isVoidType();
4207 case UTT_IsIntegral:
4208 return T->isIntegralType(C);
4209 case UTT_IsFloatingPoint:
4210 return T->isFloatingType();
4211 case UTT_IsArray:
4212 return T->isArrayType();
4213 case UTT_IsPointer:
4214 return T->isPointerType();
4215 case UTT_IsLvalueReference:
4216 return T->isLValueReferenceType();
4217 case UTT_IsRvalueReference:
4218 return T->isRValueReferenceType();
4219 case UTT_IsMemberFunctionPointer:
4220 return T->isMemberFunctionPointerType();
4221 case UTT_IsMemberObjectPointer:
4222 return T->isMemberDataPointerType();
4223 case UTT_IsEnum:
4224 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004225 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004226 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004227 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004228 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004229 case UTT_IsFunction:
4230 return T->isFunctionType();
4231
4232 // Type trait expressions which correspond to the convenient composition
4233 // predicates in C++0x [meta.unary.comp].
4234 case UTT_IsReference:
4235 return T->isReferenceType();
4236 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004237 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004238 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004239 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004240 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004241 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004242 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004243 // Note: semantic analysis depends on Objective-C lifetime types to be
4244 // considered scalar types. However, such types do not actually behave
4245 // like scalar types at run time (since they may require retain/release
4246 // operations), so we report them as non-scalar.
4247 if (T->isObjCLifetimeType()) {
4248 switch (T.getObjCLifetime()) {
4249 case Qualifiers::OCL_None:
4250 case Qualifiers::OCL_ExplicitNone:
4251 return true;
4252
4253 case Qualifiers::OCL_Strong:
4254 case Qualifiers::OCL_Weak:
4255 case Qualifiers::OCL_Autoreleasing:
4256 return false;
4257 }
4258 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004259
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004260 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004261 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004262 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004263 case UTT_IsMemberPointer:
4264 return T->isMemberPointerType();
4265
4266 // Type trait expressions which correspond to the type property predicates
4267 // in C++0x [meta.unary.prop].
4268 case UTT_IsConst:
4269 return T.isConstQualified();
4270 case UTT_IsVolatile:
4271 return T.isVolatileQualified();
4272 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004273 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004274 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004275 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004276 case UTT_IsStandardLayout:
4277 return T->isStandardLayoutType();
4278 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004279 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004280 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004281 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004282 case UTT_IsEmpty:
4283 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4284 return !RD->isUnion() && RD->isEmpty();
4285 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004286 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004287 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004288 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004289 return false;
4290 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004291 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004292 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004293 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004294 case UTT_IsAggregate:
4295 // Report vector extensions and complex types as aggregates because they
4296 // support aggregate initialization. GCC mirrors this behavior for vectors
4297 // but not _Complex.
4298 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4299 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004300 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4301 // even then only when it is used with the 'interface struct ...' syntax
4302 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004303 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004304 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004305 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004306 case UTT_IsSealed:
4307 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004308 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004309 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004310 case UTT_IsSigned:
4311 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004312 case UTT_IsUnsigned:
4313 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004314
4315 // Type trait expressions which query classes regarding their construction,
4316 // destruction, and copying. Rather than being based directly on the
4317 // related type predicates in the standard, they are specified by both
4318 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4319 // specifications.
4320 //
4321 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4322 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004323 //
4324 // Note that these builtins do not behave as documented in g++: if a class
4325 // has both a trivial and a non-trivial special member of a particular kind,
4326 // they return false! For now, we emulate this behavior.
4327 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4328 // does not correctly compute triviality in the presence of multiple special
4329 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004330 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004331 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4332 // If __is_pod (type) is true then the trait is true, else if type is
4333 // a cv class or union type (or array thereof) with a trivial default
4334 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004335 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004336 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004337 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4338 return RD->hasTrivialDefaultConstructor() &&
4339 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004340 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004341 case UTT_HasTrivialMoveConstructor:
4342 // This trait is implemented by MSVC 2012 and needed to parse the
4343 // standard library headers. Specifically this is used as the logic
4344 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004345 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004346 return true;
4347 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4348 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4349 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004350 case UTT_HasTrivialCopy:
4351 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4352 // If __is_pod (type) is true or type is a reference type then
4353 // the trait is true, else if type is a cv class or union type
4354 // with a trivial copy constructor ([class.copy]) then the trait
4355 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004356 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004357 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004358 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4359 return RD->hasTrivialCopyConstructor() &&
4360 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004361 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004362 case UTT_HasTrivialMoveAssign:
4363 // This trait is implemented by MSVC 2012 and needed to parse the
4364 // standard library headers. Specifically it is used as the logic
4365 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004366 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004367 return true;
4368 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4369 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4370 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004371 case UTT_HasTrivialAssign:
4372 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4373 // If type is const qualified or is a reference type then the
4374 // trait is false. Otherwise if __is_pod (type) is true then the
4375 // trait is true, else if type is a cv class or union type with
4376 // a trivial copy assignment ([class.copy]) then the trait is
4377 // true, else it is false.
4378 // Note: the const and reference restrictions are interesting,
4379 // given that const and reference members don't prevent a class
4380 // from having a trivial copy assignment operator (but do cause
4381 // errors if the copy assignment operator is actually used, q.v.
4382 // [class.copy]p12).
4383
Richard Smith92f241f2012-12-08 02:53:02 +00004384 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004385 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004386 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004387 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004388 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4389 return RD->hasTrivialCopyAssignment() &&
4390 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004391 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004392 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004393 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004394 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004395 // C++14 [meta.unary.prop]:
4396 // For reference types, is_destructible<T>::value is true.
4397 if (T->isReferenceType())
4398 return true;
4399
4400 // Objective-C++ ARC: autorelease types don't require destruction.
4401 if (T->isObjCLifetimeType() &&
4402 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4403 return true;
4404
4405 // C++14 [meta.unary.prop]:
4406 // For incomplete types and function types, is_destructible<T>::value is
4407 // false.
4408 if (T->isIncompleteType() || T->isFunctionType())
4409 return false;
4410
Richard Smithf03e9082017-06-01 00:28:16 +00004411 // A type that requires destruction (via a non-trivial destructor or ARC
4412 // lifetime semantics) is not trivially-destructible.
4413 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4414 return false;
4415
David Majnemerac73de92015-08-11 03:03:28 +00004416 // C++14 [meta.unary.prop]:
4417 // For object types and given U equal to remove_all_extents_t<T>, if the
4418 // expression std::declval<U&>().~U() is well-formed when treated as an
4419 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4420 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4421 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4422 if (!Destructor)
4423 return false;
4424 // C++14 [dcl.fct.def.delete]p2:
4425 // A program that refers to a deleted function implicitly or
4426 // explicitly, other than to declare it, is ill-formed.
4427 if (Destructor->isDeleted())
4428 return false;
4429 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4430 return false;
4431 if (UTT == UTT_IsNothrowDestructible) {
4432 const FunctionProtoType *CPT =
4433 Destructor->getType()->getAs<FunctionProtoType>();
4434 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4435 if (!CPT || !CPT->isNothrow(C))
4436 return false;
4437 }
4438 }
4439 return true;
4440
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004441 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004442 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004443 // If __is_pod (type) is true or type is a reference type
4444 // then the trait is true, else if type is a cv class or union
4445 // type (or array thereof) with a trivial destructor
4446 // ([class.dtor]) then the trait is true, else it is
4447 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004448 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004449 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004450
John McCall31168b02011-06-15 23:02:42 +00004451 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004452 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004453 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4454 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004455
Richard Smith92f241f2012-12-08 02:53:02 +00004456 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4457 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004458 return false;
4459 // TODO: Propagate nothrowness for implicitly declared special members.
4460 case UTT_HasNothrowAssign:
4461 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4462 // If type is const qualified or is a reference type then the
4463 // trait is false. Otherwise if __has_trivial_assign (type)
4464 // is true then the trait is true, else if type is a cv class
4465 // or union type with copy assignment operators that are known
4466 // not to throw an exception then the trait is true, else it is
4467 // false.
4468 if (C.getBaseElementType(T).isConstQualified())
4469 return false;
4470 if (T->isReferenceType())
4471 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004472 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004473 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004474
Joao Matosc9523d42013-03-27 01:34:16 +00004475 if (const RecordType *RT = T->getAs<RecordType>())
4476 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4477 &CXXRecordDecl::hasTrivialCopyAssignment,
4478 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4479 &CXXMethodDecl::isCopyAssignmentOperator);
4480 return false;
4481 case UTT_HasNothrowMoveAssign:
4482 // This trait is implemented by MSVC 2012 and needed to parse the
4483 // standard library headers. Specifically this is used as the logic
4484 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004485 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004486 return true;
4487
4488 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4489 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4490 &CXXRecordDecl::hasTrivialMoveAssignment,
4491 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4492 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004493 return false;
4494 case UTT_HasNothrowCopy:
4495 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4496 // If __has_trivial_copy (type) is true then the trait is true, else
4497 // if type is a cv class or union type with copy constructors that are
4498 // known not to throw an exception then the trait is true, else it is
4499 // false.
John McCall31168b02011-06-15 23:02:42 +00004500 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004501 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004502 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4503 if (RD->hasTrivialCopyConstructor() &&
4504 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004505 return true;
4506
4507 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004508 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004509 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004510 // A template constructor is never a copy constructor.
4511 // FIXME: However, it may actually be selected at the actual overload
4512 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004513 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004514 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004515 // UsingDecl itself is not a constructor
4516 if (isa<UsingDecl>(ND))
4517 continue;
4518 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004519 if (Constructor->isCopyConstructor(FoundTQs)) {
4520 FoundConstructor = true;
4521 const FunctionProtoType *CPT
4522 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004523 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4524 if (!CPT)
4525 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004526 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004527 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004528 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004529 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004530 }
4531 }
4532
Richard Smith938f40b2011-06-11 17:19:42 +00004533 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004534 }
4535 return false;
4536 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004537 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004538 // If __has_trivial_constructor (type) is true then the trait is
4539 // true, else if type is a cv class or union type (or array
4540 // thereof) with a default constructor that is known not to
4541 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004542 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004543 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004544 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4545 if (RD->hasTrivialDefaultConstructor() &&
4546 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004547 return true;
4548
Alp Tokerb4bca412014-01-20 00:23:47 +00004549 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004550 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004551 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004552 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004553 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004554 // UsingDecl itself is not a constructor
4555 if (isa<UsingDecl>(ND))
4556 continue;
4557 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004558 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004559 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004560 const FunctionProtoType *CPT
4561 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004562 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4563 if (!CPT)
4564 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004565 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004566 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004567 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004568 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004569 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004570 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004571 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004572 }
4573 return false;
4574 case UTT_HasVirtualDestructor:
4575 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4576 // If type is a class type with a virtual destructor ([class.dtor])
4577 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004578 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004579 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004580 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004581 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004582
4583 // These type trait expressions are modeled on the specifications for the
4584 // Embarcadero C++0x type trait functions:
4585 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4586 case UTT_IsCompleteType:
4587 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4588 // Returns True if and only if T is a complete type at the point of the
4589 // function call.
4590 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004591 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004592}
Sebastian Redl5822f082009-02-07 20:10:22 +00004593
Alp Tokercbb90342013-12-13 20:49:58 +00004594static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4595 QualType RhsT, SourceLocation KeyLoc);
4596
Douglas Gregor29c42f22012-02-24 07:38:34 +00004597static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4598 ArrayRef<TypeSourceInfo *> Args,
4599 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004600 if (Kind <= UTT_Last)
4601 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4602
Alp Tokercbb90342013-12-13 20:49:58 +00004603 if (Kind <= BTT_Last)
4604 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4605 Args[1]->getType(), RParenLoc);
4606
Douglas Gregor29c42f22012-02-24 07:38:34 +00004607 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004608 case clang::TT_IsConstructible:
4609 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004610 case clang::TT_IsTriviallyConstructible: {
4611 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004612 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004613 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004614 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004615 // definition for is_constructible, as defined below, is known to call
4616 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004617 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004618 // The predicate condition for a template specialization
4619 // is_constructible<T, Args...> shall be satisfied if and only if the
4620 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004621 // variable t:
4622 //
4623 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004624 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004625
4626 // Precondition: T and all types in the parameter pack Args shall be
4627 // complete types, (possibly cv-qualified) void, or arrays of
4628 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004629 for (const auto *TSI : Args) {
4630 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004631 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004632 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004633
Simon Pilgrim75c26882016-09-30 14:25:09 +00004634 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004635 diag::err_incomplete_type_used_in_type_trait_expr))
4636 return false;
4637 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004638
David Majnemer9658ecc2015-11-13 05:32:43 +00004639 // Make sure the first argument is not incomplete nor a function type.
4640 QualType T = Args[0]->getType();
4641 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004642 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004643
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004644 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004645 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004646 if (RD && RD->isAbstract())
4647 return false;
4648
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004649 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4650 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004651 ArgExprs.reserve(Args.size() - 1);
4652 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004653 QualType ArgTy = Args[I]->getType();
4654 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4655 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004656 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004657 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4658 ArgTy.getNonLValueExprType(S.Context),
4659 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004660 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004661 for (Expr &E : OpaqueArgExprs)
4662 ArgExprs.push_back(&E);
4663
Simon Pilgrim75c26882016-09-30 14:25:09 +00004664 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004665 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004666 EnterExpressionEvaluationContext Unevaluated(
4667 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004668 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4669 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4670 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4671 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4672 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004673 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004674 if (Init.Failed())
4675 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004676
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004677 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004678 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4679 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004680
Alp Toker73287bf2014-01-20 00:24:09 +00004681 if (Kind == clang::TT_IsConstructible)
4682 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004683
Alp Toker73287bf2014-01-20 00:24:09 +00004684 if (Kind == clang::TT_IsNothrowConstructible)
4685 return S.canThrow(Result.get()) == CT_Cannot;
4686
4687 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004688 // Under Objective-C ARC and Weak, if the destination has non-trivial
4689 // Objective-C lifetime, this is a non-trivial construction.
4690 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004691 return false;
4692
4693 // The initialization succeeded; now make sure there are no non-trivial
4694 // calls.
4695 return !Result.get()->hasNonTrivialCall(S.Context);
4696 }
4697
4698 llvm_unreachable("unhandled type trait");
4699 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004700 }
Alp Tokercbb90342013-12-13 20:49:58 +00004701 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004702 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004703
Douglas Gregor29c42f22012-02-24 07:38:34 +00004704 return false;
4705}
4706
Simon Pilgrim75c26882016-09-30 14:25:09 +00004707ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4708 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004709 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004710 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004711
Alp Toker95e7ff22014-01-01 05:57:51 +00004712 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4713 *this, Kind, KWLoc, Args[0]->getType()))
4714 return ExprError();
4715
Douglas Gregor29c42f22012-02-24 07:38:34 +00004716 bool Dependent = false;
4717 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4718 if (Args[I]->getType()->isDependentType()) {
4719 Dependent = true;
4720 break;
4721 }
4722 }
Alp Tokercbb90342013-12-13 20:49:58 +00004723
4724 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004725 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004726 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4727
4728 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4729 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004730}
4731
Alp Toker88f64e62013-12-13 21:19:30 +00004732ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4733 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004734 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004735 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004736 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004737
Douglas Gregor29c42f22012-02-24 07:38:34 +00004738 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4739 TypeSourceInfo *TInfo;
4740 QualType T = GetTypeFromParser(Args[I], &TInfo);
4741 if (!TInfo)
4742 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004743
4744 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004745 }
Alp Tokercbb90342013-12-13 20:49:58 +00004746
Douglas Gregor29c42f22012-02-24 07:38:34 +00004747 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4748}
4749
Alp Tokercbb90342013-12-13 20:49:58 +00004750static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4751 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004752 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4753 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004754
4755 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004756 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004757 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004758 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004759 // Base and Derived are not unions and name the same class type without
4760 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004761
John McCall388ef532011-01-28 22:02:36 +00004762 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004763 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004764 if (!rhsRecord || !lhsRecord) {
4765 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4766 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4767 if (!LHSObjTy || !RHSObjTy)
4768 return false;
4769
4770 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4771 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4772 if (!BaseInterface || !DerivedInterface)
4773 return false;
4774
4775 if (Self.RequireCompleteType(
4776 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4777 return false;
4778
4779 return BaseInterface->isSuperClassOf(DerivedInterface);
4780 }
John McCall388ef532011-01-28 22:02:36 +00004781
4782 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4783 == (lhsRecord == rhsRecord));
4784
4785 if (lhsRecord == rhsRecord)
4786 return !lhsRecord->getDecl()->isUnion();
4787
4788 // C++0x [meta.rel]p2:
4789 // If Base and Derived are class types and are different types
4790 // (ignoring possible cv-qualifiers) then Derived shall be a
4791 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004792 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004793 diag::err_incomplete_type_used_in_type_trait_expr))
4794 return false;
4795
4796 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4797 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4798 }
John Wiegley65497cc2011-04-27 23:09:49 +00004799 case BTT_IsSame:
4800 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004801 case BTT_TypeCompatible:
4802 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4803 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004804 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004805 case BTT_IsConvertibleTo: {
4806 // C++0x [meta.rel]p4:
4807 // Given the following function prototype:
4808 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004809 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004810 // typename add_rvalue_reference<T>::type create();
4811 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004812 // the predicate condition for a template specialization
4813 // is_convertible<From, To> shall be satisfied if and only if
4814 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004815 // well-formed, including any implicit conversions to the return
4816 // type of the function:
4817 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004818 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004819 // return create<From>();
4820 // }
4821 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004822 // Access checking is performed as if in a context unrelated to To and
4823 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004824 // of the return-statement (including conversions to the return type)
4825 // is considered.
4826 //
4827 // We model the initialization as a copy-initialization of a temporary
4828 // of the appropriate type, which for this expression is identical to the
4829 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004830
4831 // Functions aren't allowed to return function or array types.
4832 if (RhsT->isFunctionType() || RhsT->isArrayType())
4833 return false;
4834
4835 // A return statement in a void function must have void type.
4836 if (RhsT->isVoidType())
4837 return LhsT->isVoidType();
4838
4839 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004840 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004841 return false;
4842
4843 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004844 if (LhsT->isObjectType() || LhsT->isFunctionType())
4845 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004846
4847 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004848 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004849 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004850 Expr::getValueKindForType(LhsT));
4851 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004852 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004853 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004854
4855 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004856 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004857 EnterExpressionEvaluationContext Unevaluated(
4858 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004859 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4860 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004861 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004862 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004863 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004864
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004865 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004866 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4867 }
Alp Toker73287bf2014-01-20 00:24:09 +00004868
David Majnemerb3d96882016-05-23 17:21:55 +00004869 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004870 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004871 case BTT_IsTriviallyAssignable: {
4872 // C++11 [meta.unary.prop]p3:
4873 // is_trivially_assignable is defined as:
4874 // is_assignable<T, U>::value is true and the assignment, as defined by
4875 // is_assignable, is known to call no operation that is not trivial
4876 //
4877 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004878 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004879 // treated as an unevaluated operand (Clause 5).
4880 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004881 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004882 // void, or arrays of unknown bound.
4883 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004884 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004885 diag::err_incomplete_type_used_in_type_trait_expr))
4886 return false;
4887 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004888 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004889 diag::err_incomplete_type_used_in_type_trait_expr))
4890 return false;
4891
4892 // cv void is never assignable.
4893 if (LhsT->isVoidType() || RhsT->isVoidType())
4894 return false;
4895
Simon Pilgrim75c26882016-09-30 14:25:09 +00004896 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004897 // declval<U>().
4898 if (LhsT->isObjectType() || LhsT->isFunctionType())
4899 LhsT = Self.Context.getRValueReferenceType(LhsT);
4900 if (RhsT->isObjectType() || RhsT->isFunctionType())
4901 RhsT = Self.Context.getRValueReferenceType(RhsT);
4902 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4903 Expr::getValueKindForType(LhsT));
4904 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4905 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004906
4907 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004908 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004909 EnterExpressionEvaluationContext Unevaluated(
4910 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004911 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4912 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004913 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4914 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004915 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4916 return false;
4917
David Majnemerb3d96882016-05-23 17:21:55 +00004918 if (BTT == BTT_IsAssignable)
4919 return true;
4920
Alp Toker73287bf2014-01-20 00:24:09 +00004921 if (BTT == BTT_IsNothrowAssignable)
4922 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004923
Alp Toker73287bf2014-01-20 00:24:09 +00004924 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004925 // Under Objective-C ARC and Weak, if the destination has non-trivial
4926 // Objective-C lifetime, this is a non-trivial assignment.
4927 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004928 return false;
4929
4930 return !Result.get()->hasNonTrivialCall(Self.Context);
4931 }
4932
4933 llvm_unreachable("unhandled type trait");
4934 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004935 }
Alp Tokercbb90342013-12-13 20:49:58 +00004936 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004937 }
4938 llvm_unreachable("Unknown type trait or not implemented");
4939}
4940
John Wiegley6242b6a2011-04-28 00:16:57 +00004941ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4942 SourceLocation KWLoc,
4943 ParsedType Ty,
4944 Expr* DimExpr,
4945 SourceLocation RParen) {
4946 TypeSourceInfo *TSInfo;
4947 QualType T = GetTypeFromParser(Ty, &TSInfo);
4948 if (!TSInfo)
4949 TSInfo = Context.getTrivialTypeSourceInfo(T);
4950
4951 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4952}
4953
4954static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4955 QualType T, Expr *DimExpr,
4956 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004957 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004958
4959 switch(ATT) {
4960 case ATT_ArrayRank:
4961 if (T->isArrayType()) {
4962 unsigned Dim = 0;
4963 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4964 ++Dim;
4965 T = AT->getElementType();
4966 }
4967 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004968 }
John Wiegleyd3522222011-04-28 02:06:46 +00004969 return 0;
4970
John Wiegley6242b6a2011-04-28 00:16:57 +00004971 case ATT_ArrayExtent: {
4972 llvm::APSInt Value;
4973 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004974 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004975 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004976 false).isInvalid())
4977 return 0;
4978 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004979 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4980 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004981 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004982 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004983 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004984
4985 if (T->isArrayType()) {
4986 unsigned D = 0;
4987 bool Matched = false;
4988 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4989 if (Dim == D) {
4990 Matched = true;
4991 break;
4992 }
4993 ++D;
4994 T = AT->getElementType();
4995 }
4996
John Wiegleyd3522222011-04-28 02:06:46 +00004997 if (Matched && T->isArrayType()) {
4998 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4999 return CAT->getSize().getLimitedValue();
5000 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005001 }
John Wiegleyd3522222011-04-28 02:06:46 +00005002 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005003 }
5004 }
5005 llvm_unreachable("Unknown type trait or not implemented");
5006}
5007
5008ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5009 SourceLocation KWLoc,
5010 TypeSourceInfo *TSInfo,
5011 Expr* DimExpr,
5012 SourceLocation RParen) {
5013 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005014
Chandler Carruthc5276e52011-05-01 08:48:21 +00005015 // FIXME: This should likely be tracked as an APInt to remove any host
5016 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005017 uint64_t Value = 0;
5018 if (!T->isDependentType())
5019 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5020
Chandler Carruthc5276e52011-05-01 08:48:21 +00005021 // While the specification for these traits from the Embarcadero C++
5022 // compiler's documentation says the return type is 'unsigned int', Clang
5023 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5024 // compiler, there is no difference. On several other platforms this is an
5025 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005026 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5027 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005028}
5029
John Wiegleyf9f65842011-04-25 06:54:41 +00005030ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005031 SourceLocation KWLoc,
5032 Expr *Queried,
5033 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005034 // If error parsing the expression, ignore.
5035 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005036 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005037
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005038 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005039
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005040 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005041}
5042
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005043static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5044 switch (ET) {
5045 case ET_IsLValueExpr: return E->isLValue();
5046 case ET_IsRValueExpr: return E->isRValue();
5047 }
5048 llvm_unreachable("Expression trait not covered by switch");
5049}
5050
John Wiegleyf9f65842011-04-25 06:54:41 +00005051ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005052 SourceLocation KWLoc,
5053 Expr *Queried,
5054 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005055 if (Queried->isTypeDependent()) {
5056 // Delay type-checking for type-dependent expressions.
5057 } else if (Queried->getType()->isPlaceholderType()) {
5058 ExprResult PE = CheckPlaceholderExpr(Queried);
5059 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005060 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005061 }
5062
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005063 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005064
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005065 return new (Context)
5066 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005067}
5068
Richard Trieu82402a02011-09-15 21:56:47 +00005069QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005070 ExprValueKind &VK,
5071 SourceLocation Loc,
5072 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005073 assert(!LHS.get()->getType()->isPlaceholderType() &&
5074 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005075 "placeholders should have been weeded out by now");
5076
Richard Smith4baaa5a2016-12-03 01:14:32 +00005077 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5078 // temporary materialization conversion otherwise.
5079 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005080 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005081 else if (LHS.get()->isRValue())
5082 LHS = TemporaryMaterializationConversion(LHS.get());
5083 if (LHS.isInvalid())
5084 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005085
5086 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005087 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005088 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005089
Sebastian Redl5822f082009-02-07 20:10:22 +00005090 const char *OpSpelling = isIndirect ? "->*" : ".*";
5091 // C++ 5.5p2
5092 // The binary operator .* [p3: ->*] binds its second operand, which shall
5093 // be of type "pointer to member of T" (where T is a completely-defined
5094 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005095 QualType RHSType = RHS.get()->getType();
5096 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005097 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005098 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005099 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005100 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005101 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005102
Sebastian Redl5822f082009-02-07 20:10:22 +00005103 QualType Class(MemPtr->getClass(), 0);
5104
Douglas Gregord07ba342010-10-13 20:41:14 +00005105 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5106 // member pointer points must be completely-defined. However, there is no
5107 // reason for this semantic distinction, and the rule is not enforced by
5108 // other compilers. Therefore, we do not check this property, as it is
5109 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005110
Sebastian Redl5822f082009-02-07 20:10:22 +00005111 // C++ 5.5p2
5112 // [...] to its first operand, which shall be of class T or of a class of
5113 // which T is an unambiguous and accessible base class. [p3: a pointer to
5114 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005115 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005116 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005117 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5118 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005119 else {
5120 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005121 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005122 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005123 return QualType();
5124 }
5125 }
5126
Richard Trieu82402a02011-09-15 21:56:47 +00005127 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005128 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005129 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5130 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005131 return QualType();
5132 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005133
Richard Smith0f59cb32015-12-18 21:45:41 +00005134 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005135 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005136 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005137 return QualType();
5138 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005139
5140 CXXCastPath BasePath;
5141 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5142 SourceRange(LHS.get()->getLocStart(),
5143 RHS.get()->getLocEnd()),
5144 &BasePath))
5145 return QualType();
5146
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005147 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005148 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5149 if (isIndirect)
5150 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005151 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005152 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005153 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005154 }
5155
Richard Trieu82402a02011-09-15 21:56:47 +00005156 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005157 // Diagnose use of pointer-to-member type which when used as
5158 // the functional cast in a pointer-to-member expression.
5159 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5160 return QualType();
5161 }
John McCall7decc9e2010-11-18 06:31:45 +00005162
Sebastian Redl5822f082009-02-07 20:10:22 +00005163 // C++ 5.5p2
5164 // The result is an object or a function of the type specified by the
5165 // second operand.
5166 // The cv qualifiers are the union of those in the pointer and the left side,
5167 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005168 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005169 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005170
Douglas Gregor1d042092011-01-26 16:40:18 +00005171 // C++0x [expr.mptr.oper]p6:
5172 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173 // ill-formed if the second operand is a pointer to member function with
5174 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5175 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005176 // is a pointer to member function with ref-qualifier &&.
5177 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5178 switch (Proto->getRefQualifier()) {
5179 case RQ_None:
5180 // Do nothing
5181 break;
5182
5183 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005184 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5185 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5186 if (Proto->isConst())
5187 Diag(Loc, getLangOpts().CPlusPlus2a
5188 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5189 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5190 else
5191 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5192 << RHSType << 1 << LHS.get()->getSourceRange();
5193 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005194 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
Douglas Gregor1d042092011-01-26 16:40:18 +00005196 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005197 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005198 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005199 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005200 break;
5201 }
5202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203
John McCall7decc9e2010-11-18 06:31:45 +00005204 // C++ [expr.mptr.oper]p6:
5205 // The result of a .* expression whose second operand is a pointer
5206 // to a data member is of the same value category as its
5207 // first operand. The result of a .* expression whose second
5208 // operand is a pointer to a member function is a prvalue. The
5209 // result of an ->* expression is an lvalue if its second operand
5210 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005211 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005212 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005213 return Context.BoundMemberTy;
5214 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005215 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005216 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005217 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005218 }
John McCall7decc9e2010-11-18 06:31:45 +00005219
Sebastian Redl5822f082009-02-07 20:10:22 +00005220 return Result;
5221}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005222
Richard Smith2414bca2016-04-25 19:30:37 +00005223/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005224///
5225/// This is part of the parameter validation for the ? operator. If either
5226/// value operand is a class type, the two operands are attempted to be
5227/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005228/// It returns true if the program is ill-formed and has already been diagnosed
5229/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005230static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5231 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005232 bool &HaveConversion,
5233 QualType &ToType) {
5234 HaveConversion = false;
5235 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005236
5237 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005238 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005239 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005240 // The process for determining whether an operand expression E1 of type T1
5241 // can be converted to match an operand expression E2 of type T2 is defined
5242 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005243 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5244 // implicitly converted to type "lvalue reference to T2", subject to the
5245 // constraint that in the conversion the reference must bind directly to
5246 // an lvalue.
5247 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5248 // implicitly conveted to the type "rvalue reference to R2", subject to
5249 // the constraint that the reference must bind directly.
5250 if (To->isLValue() || To->isXValue()) {
5251 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5252 : Self.Context.getRValueReferenceType(ToType);
5253
Douglas Gregor838fcc32010-03-26 20:14:36 +00005254 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005256 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005257 if (InitSeq.isDirectReferenceBinding()) {
5258 ToType = T;
5259 HaveConversion = true;
5260 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262
Douglas Gregor838fcc32010-03-26 20:14:36 +00005263 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005264 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005265 }
John McCall65eb8792010-02-25 01:37:24 +00005266
Sebastian Redl1a99f442009-04-16 17:51:27 +00005267 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5268 // -- if E1 and E2 have class type, and the underlying class types are
5269 // the same or one is a base class of the other:
5270 QualType FTy = From->getType();
5271 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005272 const RecordType *FRec = FTy->getAs<RecordType>();
5273 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005275 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5276 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5277 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005278 // E1 can be converted to match E2 if the class of T2 is the
5279 // same type as, or a base class of, the class of T1, and
5280 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005281 if (FRec == TRec || FDerivedFromT) {
5282 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005283 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005284 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005285 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005286 HaveConversion = true;
5287 return false;
5288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005289
Douglas Gregor838fcc32010-03-26 20:14:36 +00005290 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005291 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005292 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005294
Douglas Gregor838fcc32010-03-26 20:14:36 +00005295 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005296 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005297
Douglas Gregor838fcc32010-03-26 20:14:36 +00005298 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5299 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005300 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005301 // an rvalue).
5302 //
5303 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5304 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005305 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
Douglas Gregor838fcc32010-03-26 20:14:36 +00005307 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005308 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005309 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005310 ToType = TTy;
5311 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005312 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005313
Sebastian Redl1a99f442009-04-16 17:51:27 +00005314 return false;
5315}
5316
5317/// \brief Try to find a common type for two according to C++0x 5.16p5.
5318///
5319/// This is part of the parameter validation for the ? operator. If either
5320/// value operand is a class type, overload resolution is used to find a
5321/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005322static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005323 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005324 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005325 OverloadCandidateSet CandidateSet(QuestionLoc,
5326 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005327 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005328 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005329
5330 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005331 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005332 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005333 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005334 ExprResult LHSRes = Self.PerformImplicitConversion(
5335 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5336 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005337 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005338 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005339 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005340
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005341 ExprResult RHSRes = Self.PerformImplicitConversion(
5342 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5343 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005344 if (RHSRes.isInvalid())
5345 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005346 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005347 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005348 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005349 return false;
John Wiegley01296292011-04-08 18:41:53 +00005350 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005351
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005352 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005353
5354 // Emit a better diagnostic if one of the expressions is a null pointer
5355 // constant and the other is a pointer type. In this case, the user most
5356 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005357 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005358 return true;
5359
5360 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005361 << LHS.get()->getType() << RHS.get()->getType()
5362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005363 return true;
5364
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005365 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005366 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005367 << LHS.get()->getType() << RHS.get()->getType()
5368 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005369 // FIXME: Print the possible common types by printing the return types of
5370 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005371 break;
5372
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005373 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005374 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005375 }
5376 return true;
5377}
5378
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005379/// \brief Perform an "extended" implicit conversion as returned by
5380/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005381static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005382 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005383 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005384 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005385 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005386 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005387 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005388 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005389 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005390
John Wiegley01296292011-04-08 18:41:53 +00005391 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005392 return false;
5393}
5394
Sebastian Redl1a99f442009-04-16 17:51:27 +00005395/// \brief Check the operands of ?: under C++ semantics.
5396///
5397/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5398/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005399QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5400 ExprResult &RHS, ExprValueKind &VK,
5401 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005402 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005403 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5404 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005405
Richard Smith45edb702012-08-07 22:06:48 +00005406 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005407 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005408 //
5409 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5410 // a is that of a integer vector with the same number of elements and
5411 // size as the vectors of b and c. If one of either b or c is a scalar
5412 // it is implicitly converted to match the type of the vector.
5413 // Otherwise the expression is ill-formed. If both b and c are scalars,
5414 // then b and c are checked and converted to the type of a if possible.
5415 // Unlike the OpenCL ?: operator, the expression is evaluated as
5416 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005417 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005418 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005419 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005420 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005421 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005422 }
5423
John McCall7decc9e2010-11-18 06:31:45 +00005424 // Assume r-value.
5425 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005426 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005427
Sebastian Redl1a99f442009-04-16 17:51:27 +00005428 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005429 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005430 return Context.DependentTy;
5431
Richard Smith45edb702012-08-07 22:06:48 +00005432 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005433 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005434 QualType LTy = LHS.get()->getType();
5435 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005436 bool LVoid = LTy->isVoidType();
5437 bool RVoid = RTy->isVoidType();
5438 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005439 // ... one of the following shall hold:
5440 // -- The second or the third operand (but not both) is a (possibly
5441 // parenthesized) throw-expression; the result is of the type
5442 // and value category of the other.
5443 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5444 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5445 if (LThrow != RThrow) {
5446 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5447 VK = NonThrow->getValueKind();
5448 // DR (no number yet): the result is a bit-field if the
5449 // non-throw-expression operand is a bit-field.
5450 OK = NonThrow->getObjectKind();
5451 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005452 }
5453
Sebastian Redl1a99f442009-04-16 17:51:27 +00005454 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005455 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005456 if (LVoid && RVoid)
5457 return Context.VoidTy;
5458
5459 // Neither holds, error.
5460 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5461 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005462 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005463 return QualType();
5464 }
5465
5466 // Neither is void.
5467
Richard Smithf2b084f2012-08-08 06:13:49 +00005468 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005469 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005470 // either has (cv) class type [...] an attempt is made to convert each of
5471 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005473 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005474 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005475 QualType L2RType, R2LType;
5476 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005477 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005478 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005479 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005480 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
Sebastian Redl1a99f442009-04-16 17:51:27 +00005482 // If both can be converted, [...] the program is ill-formed.
5483 if (HaveL2R && HaveR2L) {
5484 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005485 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005486 return QualType();
5487 }
5488
5489 // If exactly one conversion is possible, that conversion is applied to
5490 // the chosen operand and the converted operands are used in place of the
5491 // original operands for the remainder of this section.
5492 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005493 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005494 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005495 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005496 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005497 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005498 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005499 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005500 }
5501 }
5502
Richard Smithf2b084f2012-08-08 06:13:49 +00005503 // C++11 [expr.cond]p3
5504 // if both are glvalues of the same value category and the same type except
5505 // for cv-qualification, an attempt is made to convert each of those
5506 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005507 // FIXME:
5508 // Resolving a defect in P0012R1: we extend this to cover all cases where
5509 // one of the operands is reference-compatible with the other, in order
5510 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005511 ExprValueKind LVK = LHS.get()->getValueKind();
5512 ExprValueKind RVK = RHS.get()->getValueKind();
5513 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005514 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005515 // DerivedToBase was already handled by the class-specific case above.
5516 // FIXME: Should we allow ObjC conversions here?
5517 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5518 if (CompareReferenceRelationship(
5519 QuestionLoc, LTy, RTy, DerivedToBase,
5520 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005521 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5522 // [...] subject to the constraint that the reference must bind
5523 // directly [...]
5524 !RHS.get()->refersToBitField() &&
5525 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005526 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005527 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005528 } else if (CompareReferenceRelationship(
5529 QuestionLoc, RTy, LTy, DerivedToBase,
5530 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005531 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5532 !LHS.get()->refersToBitField() &&
5533 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005534 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5535 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005536 }
5537 }
5538
5539 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005540 // If the second and third operands are glvalues of the same value
5541 // category and have the same type, the result is of that type and
5542 // value category and it is a bit-field if the second or the third
5543 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005544 // We only extend this to bitfields, not to the crazy other kinds of
5545 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005546 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005547 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005548 LHS.get()->isOrdinaryOrBitFieldObject() &&
5549 RHS.get()->isOrdinaryOrBitFieldObject()) {
5550 VK = LHS.get()->getValueKind();
5551 if (LHS.get()->getObjectKind() == OK_BitField ||
5552 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005553 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005554
5555 // If we have function pointer types, unify them anyway to unify their
5556 // exception specifications, if any.
5557 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5558 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005559 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005560 /*ConvertArgs*/false);
5561 LTy = Context.getQualifiedType(LTy, Qs);
5562
5563 assert(!LTy.isNull() && "failed to find composite pointer type for "
5564 "canonically equivalent function ptr types");
5565 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5566 }
5567
John McCall7decc9e2010-11-18 06:31:45 +00005568 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005569 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005570
Richard Smithf2b084f2012-08-08 06:13:49 +00005571 // C++11 [expr.cond]p5
5572 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005573 // do not have the same type, and either has (cv) class type, ...
5574 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5575 // ... overload resolution is used to determine the conversions (if any)
5576 // to be applied to the operands. If the overload resolution fails, the
5577 // program is ill-formed.
5578 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5579 return QualType();
5580 }
5581
Richard Smithf2b084f2012-08-08 06:13:49 +00005582 // C++11 [expr.cond]p6
5583 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005584 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005585 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5586 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005587 if (LHS.isInvalid() || RHS.isInvalid())
5588 return QualType();
5589 LTy = LHS.get()->getType();
5590 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005591
5592 // After those conversions, one of the following shall hold:
5593 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005594 // is of that type. If the operands have class type, the result
5595 // is a prvalue temporary of the result type, which is
5596 // copy-initialized from either the second operand or the third
5597 // operand depending on the value of the first operand.
5598 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5599 if (LTy->isRecordType()) {
5600 // The operands have class type. Make a temporary copy.
5601 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005602
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005603 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5604 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005605 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005606 if (LHSCopy.isInvalid())
5607 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
5609 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5610 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005611 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005612 if (RHSCopy.isInvalid())
5613 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005614
John Wiegley01296292011-04-08 18:41:53 +00005615 LHS = LHSCopy;
5616 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005617 }
5618
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005619 // If we have function pointer types, unify them anyway to unify their
5620 // exception specifications, if any.
5621 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5622 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5623 assert(!LTy.isNull() && "failed to find composite pointer type for "
5624 "canonically equivalent function ptr types");
5625 }
5626
Sebastian Redl1a99f442009-04-16 17:51:27 +00005627 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005628 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005629
Douglas Gregor46188682010-05-18 22:42:18 +00005630 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005631 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005632 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5633 /*AllowBothBool*/true,
5634 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005635
Sebastian Redl1a99f442009-04-16 17:51:27 +00005636 // -- The second and third operands have arithmetic or enumeration type;
5637 // the usual arithmetic conversions are performed to bring them to a
5638 // common type, and the result is of that type.
5639 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005640 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005641 if (LHS.isInvalid() || RHS.isInvalid())
5642 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005643 if (ResTy.isNull()) {
5644 Diag(QuestionLoc,
5645 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5646 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5647 return QualType();
5648 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005649
5650 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5651 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5652
5653 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005654 }
5655
5656 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005657 // type and the other is a null pointer constant, or both are null
5658 // pointer constants, at least one of which is non-integral; pointer
5659 // conversions and qualification conversions are performed to bring them
5660 // to their composite pointer type. The result is of the composite
5661 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005662 // -- The second and third operands have pointer to member type, or one has
5663 // pointer to member type and the other is a null pointer constant;
5664 // pointer to member conversions and qualification conversions are
5665 // performed to bring them to a common type, whose cv-qualification
5666 // shall match the cv-qualification of either the second or the third
5667 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005668 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5669 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005670 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
Douglas Gregor697a3912010-04-01 22:47:07 +00005672 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005673 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5674 if (!Composite.isNull())
5675 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005676
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005677 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005678 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005679 return QualType();
5680
Sebastian Redl1a99f442009-04-16 17:51:27 +00005681 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005682 << LHS.get()->getType() << RHS.get()->getType()
5683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005684 return QualType();
5685}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005686
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005687static FunctionProtoType::ExceptionSpecInfo
5688mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5689 FunctionProtoType::ExceptionSpecInfo ESI2,
5690 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5691 ExceptionSpecificationType EST1 = ESI1.Type;
5692 ExceptionSpecificationType EST2 = ESI2.Type;
5693
5694 // If either of them can throw anything, that is the result.
5695 if (EST1 == EST_None) return ESI1;
5696 if (EST2 == EST_None) return ESI2;
5697 if (EST1 == EST_MSAny) return ESI1;
5698 if (EST2 == EST_MSAny) return ESI2;
5699
5700 // If either of them is non-throwing, the result is the other.
5701 if (EST1 == EST_DynamicNone) return ESI2;
5702 if (EST2 == EST_DynamicNone) return ESI1;
5703 if (EST1 == EST_BasicNoexcept) return ESI2;
5704 if (EST2 == EST_BasicNoexcept) return ESI1;
5705
5706 // If either of them is a non-value-dependent computed noexcept, that
5707 // determines the result.
5708 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5709 !ESI2.NoexceptExpr->isValueDependent())
5710 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5711 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5712 !ESI1.NoexceptExpr->isValueDependent())
5713 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5714 // If we're left with value-dependent computed noexcept expressions, we're
5715 // stuck. Before C++17, we can just drop the exception specification entirely,
5716 // since it's not actually part of the canonical type. And this should never
5717 // happen in C++17, because it would mean we were computing the composite
5718 // pointer type of dependent types, which should never happen.
5719 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5720 assert(!S.getLangOpts().CPlusPlus1z &&
5721 "computing composite pointer type of dependent types");
5722 return FunctionProtoType::ExceptionSpecInfo();
5723 }
5724
5725 // Switch over the possibilities so that people adding new values know to
5726 // update this function.
5727 switch (EST1) {
5728 case EST_None:
5729 case EST_DynamicNone:
5730 case EST_MSAny:
5731 case EST_BasicNoexcept:
5732 case EST_ComputedNoexcept:
5733 llvm_unreachable("handled above");
5734
5735 case EST_Dynamic: {
5736 // This is the fun case: both exception specifications are dynamic. Form
5737 // the union of the two lists.
5738 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5739 llvm::SmallPtrSet<QualType, 8> Found;
5740 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5741 for (QualType E : Exceptions)
5742 if (Found.insert(S.Context.getCanonicalType(E)).second)
5743 ExceptionTypeStorage.push_back(E);
5744
5745 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5746 Result.Exceptions = ExceptionTypeStorage;
5747 return Result;
5748 }
5749
5750 case EST_Unevaluated:
5751 case EST_Uninstantiated:
5752 case EST_Unparsed:
5753 llvm_unreachable("shouldn't see unresolved exception specifications here");
5754 }
5755
5756 llvm_unreachable("invalid ExceptionSpecificationType");
5757}
5758
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005759/// \brief Find a merged pointer type and convert the two expressions to it.
5760///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005761/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005762/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005763/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005764/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005765///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005766/// \param Loc The location of the operator requiring these two expressions to
5767/// be converted to the composite pointer type.
5768///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005769/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005771 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005772 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005773 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005774
5775 // C++1z [expr]p14:
5776 // The composite pointer type of two operands p1 and p2 having types T1
5777 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005778 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005779
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005780 // where at least one is a pointer or pointer to member type or
5781 // std::nullptr_t is:
5782 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5783 T1->isNullPtrType();
5784 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5785 T2->isNullPtrType();
5786 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005787 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005788
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005789 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5790 // This can't actually happen, following the standard, but we also use this
5791 // to implement the end of [expr.conv], which hits this case.
5792 //
5793 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5794 if (T1IsPointerLike &&
5795 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005796 if (ConvertArgs)
5797 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5798 ? CK_NullToMemberPointer
5799 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005800 return T1;
5801 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005802 if (T2IsPointerLike &&
5803 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005804 if (ConvertArgs)
5805 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5806 ? CK_NullToMemberPointer
5807 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005808 return T2;
5809 }
Mike Stump11289f42009-09-09 15:08:12 +00005810
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005811 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005812 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005813 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005814 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5815 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005816
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005817 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5818 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5819 // the union of cv1 and cv2;
5820 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5821 // "pointer to function", where the function types are otherwise the same,
5822 // "pointer to function";
5823 // FIXME: This rule is defective: it should also permit removing noexcept
5824 // from a pointer to member function. As a Clang extension, we also
5825 // permit removing 'noreturn', so we generalize this rule to;
5826 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5827 // "pointer to member function" and the pointee types can be unified
5828 // by a function pointer conversion, that conversion is applied
5829 // before checking the following rules.
5830 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5831 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5832 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5833 // respectively;
5834 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5835 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5836 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5837 // T1 or the cv-combined type of T1 and T2, respectively;
5838 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5839 // T2;
5840 //
5841 // If looked at in the right way, these bullets all do the same thing.
5842 // What we do here is, we build the two possible cv-combined types, and try
5843 // the conversions in both directions. If only one works, or if the two
5844 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005845 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005846 //
5847 // Note that this will fail to find a composite pointer type for "pointer
5848 // to void" and "pointer to function". We can't actually perform the final
5849 // conversion in this case, even though a composite pointer type formally
5850 // exists.
5851 SmallVector<unsigned, 4> QualifierUnion;
5852 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005853 QualType Composite1 = T1;
5854 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005855 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005856 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005857 const PointerType *Ptr1, *Ptr2;
5858 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5859 (Ptr2 = Composite2->getAs<PointerType>())) {
5860 Composite1 = Ptr1->getPointeeType();
5861 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005863 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005864 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005865 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005866 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005867
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005868 QualifierUnion.push_back(
5869 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005870 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005871 continue;
5872 }
Mike Stump11289f42009-09-09 15:08:12 +00005873
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005874 const MemberPointerType *MemPtr1, *MemPtr2;
5875 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5876 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5877 Composite1 = MemPtr1->getPointeeType();
5878 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005879
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005880 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005881 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005882 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005883 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005884
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005885 QualifierUnion.push_back(
5886 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5887 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5888 MemPtr2->getClass()));
5889 continue;
5890 }
Mike Stump11289f42009-09-09 15:08:12 +00005891
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005892 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005893
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005894 // Cannot unwrap any more types.
5895 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005896 }
Mike Stump11289f42009-09-09 15:08:12 +00005897
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005898 // Apply the function pointer conversion to unify the types. We've already
5899 // unwrapped down to the function types, and we want to merge rather than
5900 // just convert, so do this ourselves rather than calling
5901 // IsFunctionConversion.
5902 //
5903 // FIXME: In order to match the standard wording as closely as possible, we
5904 // currently only do this under a single level of pointers. Ideally, we would
5905 // allow this in general, and set NeedConstBefore to the relevant depth on
5906 // the side(s) where we changed anything.
5907 if (QualifierUnion.size() == 1) {
5908 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5909 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5910 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5911 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5912
5913 // The result is noreturn if both operands are.
5914 bool Noreturn =
5915 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5916 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5917 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5918
5919 // The result is nothrow if both operands are.
5920 SmallVector<QualType, 8> ExceptionTypeStorage;
5921 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5922 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5923 ExceptionTypeStorage);
5924
5925 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5926 FPT1->getParamTypes(), EPI1);
5927 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5928 FPT2->getParamTypes(), EPI2);
5929 }
5930 }
5931 }
5932
Richard Smith5e9746f2016-10-21 22:00:42 +00005933 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005934 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005936 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005937 for (unsigned I = 0; I != NeedConstBefore; ++I)
5938 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005939 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005941
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005942 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005943 auto MOC = MemberOfClass.rbegin();
5944 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5945 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5946 auto Classes = *MOC++;
5947 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005948 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005949 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005950 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005951 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005952 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005953 } else {
5954 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005955 Composite1 =
5956 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5957 Composite2 =
5958 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005959 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005960 }
5961
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005962 struct Conversion {
5963 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005964 Expr *&E1, *&E2;
5965 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005966 InitializedEntity Entity;
5967 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005968 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005969 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005970
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005971 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5972 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005973 : S(S), E1(E1), E2(E2), Composite(Composite),
5974 Entity(InitializedEntity::InitializeTemporary(Composite)),
5975 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5976 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5977 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005978
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005979 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005980 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5981 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005982 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005983 E1 = E1Result.getAs<Expr>();
5984
5985 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5986 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005987 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005988 E2 = E2Result.getAs<Expr>();
5989
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005990 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005991 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005992 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005993
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005994 // Try to convert to each composite pointer type.
5995 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005996 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5997 if (ConvertArgs && C1.perform())
5998 return QualType();
5999 return C1.Composite;
6000 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006001 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006002
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006003 if (C1.Viable == C2.Viable) {
6004 // Either Composite1 and Composite2 are viable and are different, or
6005 // neither is viable.
6006 // FIXME: How both be viable and different?
6007 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006008 }
6009
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006010 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006011 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6012 return QualType();
6013
6014 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006015}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006016
John McCalldadc5752010-08-24 06:29:42 +00006017ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006018 if (!E)
6019 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006020
John McCall31168b02011-06-15 23:02:42 +00006021 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6022
6023 // If the result is a glvalue, we shouldn't bind it.
6024 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006025 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006026
John McCall31168b02011-06-15 23:02:42 +00006027 // In ARC, calls that return a retainable type can return retained,
6028 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006029 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006030 E->getType()->isObjCRetainableType()) {
6031
6032 bool ReturnsRetained;
6033
6034 // For actual calls, we compute this by examining the type of the
6035 // called value.
6036 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6037 Expr *Callee = Call->getCallee()->IgnoreParens();
6038 QualType T = Callee->getType();
6039
6040 if (T == Context.BoundMemberTy) {
6041 // Handle pointer-to-members.
6042 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6043 T = BinOp->getRHS()->getType();
6044 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6045 T = Mem->getMemberDecl()->getType();
6046 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006047
John McCall31168b02011-06-15 23:02:42 +00006048 if (const PointerType *Ptr = T->getAs<PointerType>())
6049 T = Ptr->getPointeeType();
6050 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6051 T = Ptr->getPointeeType();
6052 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6053 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006054
John McCall31168b02011-06-15 23:02:42 +00006055 const FunctionType *FTy = T->getAs<FunctionType>();
6056 assert(FTy && "call to value not of function type?");
6057 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6058
6059 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6060 // type always produce a +1 object.
6061 } else if (isa<StmtExpr>(E)) {
6062 ReturnsRetained = true;
6063
Ted Kremeneke65b0862012-03-06 20:05:56 +00006064 // We hit this case with the lambda conversion-to-block optimization;
6065 // we don't want any extra casts here.
6066 } else if (isa<CastExpr>(E) &&
6067 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006068 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006069
John McCall31168b02011-06-15 23:02:42 +00006070 // For message sends and property references, we try to find an
6071 // actual method. FIXME: we should infer retention by selector in
6072 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006073 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006074 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006075 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6076 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006077 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6078 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006079 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006080 // Don't do reclaims if we're using the zero-element array
6081 // constant.
6082 if (ArrayLit->getNumElements() == 0 &&
6083 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6084 return E;
6085
Ted Kremeneke65b0862012-03-06 20:05:56 +00006086 D = ArrayLit->getArrayWithObjectsMethod();
6087 } else if (ObjCDictionaryLiteral *DictLit
6088 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006089 // Don't do reclaims if we're using the zero-element dictionary
6090 // constant.
6091 if (DictLit->getNumElements() == 0 &&
6092 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6093 return E;
6094
Ted Kremeneke65b0862012-03-06 20:05:56 +00006095 D = DictLit->getDictWithObjectsMethod();
6096 }
John McCall31168b02011-06-15 23:02:42 +00006097
6098 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006099
6100 // Don't do reclaims on performSelector calls; despite their
6101 // return type, the invoked method doesn't necessarily actually
6102 // return an object.
6103 if (!ReturnsRetained &&
6104 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006105 return E;
John McCall31168b02011-06-15 23:02:42 +00006106 }
6107
John McCall16de4d22011-11-14 19:53:16 +00006108 // Don't reclaim an object of Class type.
6109 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006110 return E;
John McCall16de4d22011-11-14 19:53:16 +00006111
Tim Shen4a05bb82016-06-21 20:29:17 +00006112 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006113
John McCall2d637d22011-09-10 06:18:15 +00006114 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6115 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006116 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6117 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006118 }
6119
David Blaikiebbafb8a2012-03-11 07:00:24 +00006120 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006121 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006122
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006123 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6124 // a fast path for the common case that the type is directly a RecordType.
6125 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006126 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006127 while (!RT) {
6128 switch (T->getTypeClass()) {
6129 case Type::Record:
6130 RT = cast<RecordType>(T);
6131 break;
6132 case Type::ConstantArray:
6133 case Type::IncompleteArray:
6134 case Type::VariableArray:
6135 case Type::DependentSizedArray:
6136 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6137 break;
6138 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006139 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006140 }
6141 }
Mike Stump11289f42009-09-09 15:08:12 +00006142
Richard Smithfd555f62012-02-22 02:04:18 +00006143 // That should be enough to guarantee that this type is complete, if we're
6144 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006145 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006146 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006147 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006148
6149 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006150 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006151
John McCall31168b02011-06-15 23:02:42 +00006152 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006153 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006154 CheckDestructorAccess(E->getExprLoc(), Destructor,
6155 PDiag(diag::err_access_dtor_temp)
6156 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006157 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6158 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006159
Richard Smithfd555f62012-02-22 02:04:18 +00006160 // If destructor is trivial, we can avoid the extra copy.
6161 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006162 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006163
John McCall28fc7092011-11-10 05:35:25 +00006164 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006165 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006166 }
Richard Smitheec915d62012-02-18 04:13:32 +00006167
6168 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006169 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6170
6171 if (IsDecltype)
6172 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6173
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006174 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006175}
6176
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006177ExprResult
John McCall5d413782010-12-06 08:20:24 +00006178Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006179 if (SubExpr.isInvalid())
6180 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006181
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006182 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006183}
6184
John McCall28fc7092011-11-10 05:35:25 +00006185Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006186 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006187
Eli Friedman3bda6b12012-02-02 23:15:15 +00006188 CleanupVarDeclMarking();
6189
John McCall28fc7092011-11-10 05:35:25 +00006190 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6191 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006192 assert(Cleanup.exprNeedsCleanups() ||
6193 ExprCleanupObjects.size() == FirstCleanup);
6194 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006195 return SubExpr;
6196
Craig Topper5fc8fc22014-08-27 06:28:36 +00006197 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6198 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006199
Tim Shen4a05bb82016-06-21 20:29:17 +00006200 auto *E = ExprWithCleanups::Create(
6201 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006202 DiscardCleanupsInEvaluationContext();
6203
6204 return E;
6205}
6206
John McCall5d413782010-12-06 08:20:24 +00006207Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006208 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006209
Eli Friedman3bda6b12012-02-02 23:15:15 +00006210 CleanupVarDeclMarking();
6211
Tim Shen4a05bb82016-06-21 20:29:17 +00006212 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006213 return SubStmt;
6214
6215 // FIXME: In order to attach the temporaries, wrap the statement into
6216 // a StmtExpr; currently this is only used for asm statements.
6217 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6218 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006219 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006220 SourceLocation(),
6221 SourceLocation());
6222 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6223 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006224 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006225}
6226
Richard Smithfd555f62012-02-22 02:04:18 +00006227/// Process the expression contained within a decltype. For such expressions,
6228/// certain semantic checks on temporaries are delayed until this point, and
6229/// are omitted for the 'topmost' call in the decltype expression. If the
6230/// topmost call bound a temporary, strip that temporary off the expression.
6231ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006232 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006233
6234 // C++11 [expr.call]p11:
6235 // If a function call is a prvalue of object type,
6236 // -- if the function call is either
6237 // -- the operand of a decltype-specifier, or
6238 // -- the right operand of a comma operator that is the operand of a
6239 // decltype-specifier,
6240 // a temporary object is not introduced for the prvalue.
6241
6242 // Recursively rebuild ParenExprs and comma expressions to strip out the
6243 // outermost CXXBindTemporaryExpr, if any.
6244 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6245 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6246 if (SubExpr.isInvalid())
6247 return ExprError();
6248 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006249 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006250 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006251 }
6252 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6253 if (BO->getOpcode() == BO_Comma) {
6254 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6255 if (RHS.isInvalid())
6256 return ExprError();
6257 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006258 return E;
6259 return new (Context) BinaryOperator(
6260 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006261 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006262 }
6263 }
6264
6265 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006266 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6267 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006268 if (TopCall)
6269 E = TopCall;
6270 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006271 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006272
6273 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006274 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006275
Richard Smithf86b0ae2012-07-28 19:54:11 +00006276 // In MS mode, don't perform any extra checking of call return types within a
6277 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006278 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006279 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006280
Richard Smithfd555f62012-02-22 02:04:18 +00006281 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006282 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6283 I != N; ++I) {
6284 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006285 if (Call == TopCall)
6286 continue;
6287
David Majnemerced8bdf2015-02-25 17:36:15 +00006288 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006289 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006290 Call, Call->getDirectCallee()))
6291 return ExprError();
6292 }
6293
6294 // Now all relevant types are complete, check the destructors are accessible
6295 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006296 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6297 I != N; ++I) {
6298 CXXBindTemporaryExpr *Bind =
6299 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006300 if (Bind == TopBind)
6301 continue;
6302
6303 CXXTemporary *Temp = Bind->getTemporary();
6304
6305 CXXRecordDecl *RD =
6306 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6307 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6308 Temp->setDestructor(Destructor);
6309
Richard Smith7d847b12012-05-11 22:20:10 +00006310 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6311 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006312 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006313 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006314 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6315 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006316
6317 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006318 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006319 }
6320
6321 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006322 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006323}
6324
Richard Smith79c927b2013-11-06 19:31:51 +00006325/// Note a set of 'operator->' functions that were used for a member access.
6326static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006327 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006328 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6329 // FIXME: Make this configurable?
6330 unsigned Limit = 9;
6331 if (OperatorArrows.size() > Limit) {
6332 // Produce Limit-1 normal notes and one 'skipping' note.
6333 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6334 SkipCount = OperatorArrows.size() - (Limit - 1);
6335 }
6336
6337 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6338 if (I == SkipStart) {
6339 S.Diag(OperatorArrows[I]->getLocation(),
6340 diag::note_operator_arrows_suppressed)
6341 << SkipCount;
6342 I += SkipCount;
6343 } else {
6344 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6345 << OperatorArrows[I]->getCallResultType();
6346 ++I;
6347 }
6348 }
6349}
6350
Nico Weber964d3322015-02-16 22:35:45 +00006351ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6352 SourceLocation OpLoc,
6353 tok::TokenKind OpKind,
6354 ParsedType &ObjectType,
6355 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006356 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006357 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006358 if (Result.isInvalid()) return ExprError();
6359 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006360
John McCall526ab472011-10-25 17:37:35 +00006361 Result = CheckPlaceholderExpr(Base);
6362 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006363 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006364
John McCallb268a282010-08-23 23:25:46 +00006365 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006366 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006367 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006368 // If we have a pointer to a dependent type and are using the -> operator,
6369 // the object type is the type that the pointer points to. We might still
6370 // have enough information about that type to do something useful.
6371 if (OpKind == tok::arrow)
6372 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6373 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006374
John McCallba7bf592010-08-24 05:47:05 +00006375 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006376 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006377 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006378 }
Mike Stump11289f42009-09-09 15:08:12 +00006379
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006380 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006381 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006382 // returned, with the original second operand.
6383 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006384 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006385 bool NoArrowOperatorFound = false;
6386 bool FirstIteration = true;
6387 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006388 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006389 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006390 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006391 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006392
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006393 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006394 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6395 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006396 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006397 noteOperatorArrows(*this, OperatorArrows);
6398 Diag(OpLoc, diag::note_operator_arrow_depth)
6399 << getLangOpts().ArrowDepth;
6400 return ExprError();
6401 }
6402
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006403 Result = BuildOverloadedArrowExpr(
6404 S, Base, OpLoc,
6405 // When in a template specialization and on the first loop iteration,
6406 // potentially give the default diagnostic (with the fixit in a
6407 // separate note) instead of having the error reported back to here
6408 // and giving a diagnostic with a fixit attached to the error itself.
6409 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006410 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006411 : &NoArrowOperatorFound);
6412 if (Result.isInvalid()) {
6413 if (NoArrowOperatorFound) {
6414 if (FirstIteration) {
6415 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006416 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006417 << FixItHint::CreateReplacement(OpLoc, ".");
6418 OpKind = tok::period;
6419 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006420 }
6421 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6422 << BaseType << Base->getSourceRange();
6423 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006424 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006425 Diag(CD->getLocStart(),
6426 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006427 }
6428 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006429 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006430 }
John McCallb268a282010-08-23 23:25:46 +00006431 Base = Result.get();
6432 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006433 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006434 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006435 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006436 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006437 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6438 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006439 return ExprError();
6440 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006441 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006442 }
Mike Stump11289f42009-09-09 15:08:12 +00006443
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006444 if (OpKind == tok::arrow &&
6445 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006446 BaseType = BaseType->getPointeeType();
6447 }
Mike Stump11289f42009-09-09 15:08:12 +00006448
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006449 // Objective-C properties allow "." access on Objective-C pointer types,
6450 // so adjust the base type to the object type itself.
6451 if (BaseType->isObjCObjectPointerType())
6452 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006453
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006454 // C++ [basic.lookup.classref]p2:
6455 // [...] If the type of the object expression is of pointer to scalar
6456 // type, the unqualified-id is looked up in the context of the complete
6457 // postfix-expression.
6458 //
6459 // This also indicates that we could be parsing a pseudo-destructor-name.
6460 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006461 // expressions or normal member (ivar or property) access expressions, and
6462 // it's legal for the type to be incomplete if this is a pseudo-destructor
6463 // call. We'll do more incomplete-type checks later in the lookup process,
6464 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006465 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006466 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006467 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006468 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006469 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006470 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006471 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006472 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006473 }
Mike Stump11289f42009-09-09 15:08:12 +00006474
Douglas Gregor3024f072012-04-16 07:05:22 +00006475 // The object type must be complete (or dependent), or
6476 // C++11 [expr.prim.general]p3:
6477 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006478 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006479 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006480 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006481 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006482 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006483 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006485 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006486 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006487 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006488 // type C (or of pointer to a class type C), the unqualified-id is looked
6489 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006490 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006491 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006492}
6493
Simon Pilgrim75c26882016-09-30 14:25:09 +00006494static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006495 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006496 if (Base->hasPlaceholderType()) {
6497 ExprResult result = S.CheckPlaceholderExpr(Base);
6498 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006499 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006500 }
6501 ObjectType = Base->getType();
6502
David Blaikie1d578782011-12-16 16:03:09 +00006503 // C++ [expr.pseudo]p2:
6504 // The left-hand side of the dot operator shall be of scalar type. The
6505 // left-hand side of the arrow operator shall be of pointer to scalar type.
6506 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006507 // Note that this is rather different from the normal handling for the
6508 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006509 if (OpKind == tok::arrow) {
6510 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6511 ObjectType = Ptr->getPointeeType();
6512 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006513 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006514 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6515 << ObjectType << true
6516 << FixItHint::CreateReplacement(OpLoc, ".");
6517 if (S.isSFINAEContext())
6518 return true;
6519
6520 OpKind = tok::period;
6521 }
6522 }
6523
6524 return false;
6525}
6526
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006527/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6528/// pointer objects.
6529static bool
6530canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6531 QualType DestructedType) {
6532 // If this is a record type, check if its destructor is callable.
6533 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6534 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6535 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6536 return false;
6537 }
6538
6539 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6540 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6541 DestructedType->isVectorType();
6542}
6543
John McCalldadc5752010-08-24 06:29:42 +00006544ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006545 SourceLocation OpLoc,
6546 tok::TokenKind OpKind,
6547 const CXXScopeSpec &SS,
6548 TypeSourceInfo *ScopeTypeInfo,
6549 SourceLocation CCLoc,
6550 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006551 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006552 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006553
Eli Friedman0ce4de42012-01-25 04:35:06 +00006554 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006555 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6556 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006557
Douglas Gregorc5c57342012-09-10 14:57:06 +00006558 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6559 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006560 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006561 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006562 else {
Nico Weber58829272012-01-23 05:50:57 +00006563 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6564 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006565 return ExprError();
6566 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006567 }
6568
6569 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006570 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006571 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006572 if (DestructedTypeInfo) {
6573 QualType DestructedType = DestructedTypeInfo->getType();
6574 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006575 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006576 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6577 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006578 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6579 // Foo *foo;
6580 // foo.~Foo();
6581 if (OpKind == tok::period && ObjectType->isPointerType() &&
6582 Context.hasSameUnqualifiedType(DestructedType,
6583 ObjectType->getPointeeType())) {
6584 auto Diagnostic =
6585 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6586 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006587
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006588 // Issue a fixit only when the destructor is valid.
6589 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6590 *this, DestructedType))
6591 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6592
6593 // Recover by setting the object type to the destructed type and the
6594 // operator to '->'.
6595 ObjectType = DestructedType;
6596 OpKind = tok::arrow;
6597 } else {
6598 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6599 << ObjectType << DestructedType << Base->getSourceRange()
6600 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6601
6602 // Recover by setting the destructed type to the object type.
6603 DestructedType = ObjectType;
6604 DestructedTypeInfo =
6605 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6606 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6607 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006608 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006609 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006610
John McCall31168b02011-06-15 23:02:42 +00006611 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6612 // Okay: just pretend that the user provided the correctly-qualified
6613 // type.
6614 } else {
6615 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6616 << ObjectType << DestructedType << Base->getSourceRange()
6617 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6618 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006619
John McCall31168b02011-06-15 23:02:42 +00006620 // Recover by setting the destructed type to the object type.
6621 DestructedType = ObjectType;
6622 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6623 DestructedTypeStart);
6624 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6625 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006626 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006628
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006629 // C++ [expr.pseudo]p2:
6630 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6631 // form
6632 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006633 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006634 //
6635 // shall designate the same scalar type.
6636 if (ScopeTypeInfo) {
6637 QualType ScopeType = ScopeTypeInfo->getType();
6638 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006639 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006640
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006641 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006642 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006643 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006644 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006645
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006646 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006647 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006648 }
6649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
John McCallb268a282010-08-23 23:25:46 +00006651 Expr *Result
6652 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6653 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006654 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006655 ScopeTypeInfo,
6656 CCLoc,
6657 TildeLoc,
6658 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659
David Majnemerced8bdf2015-02-25 17:36:15 +00006660 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006661}
6662
John McCalldadc5752010-08-24 06:29:42 +00006663ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006664 SourceLocation OpLoc,
6665 tok::TokenKind OpKind,
6666 CXXScopeSpec &SS,
6667 UnqualifiedId &FirstTypeName,
6668 SourceLocation CCLoc,
6669 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006670 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006671 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6672 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6673 "Invalid first type name in pseudo-destructor");
6674 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6675 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6676 "Invalid second type name in pseudo-destructor");
6677
Eli Friedman0ce4de42012-01-25 04:35:06 +00006678 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006679 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6680 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006681
6682 // Compute the object type that we should use for name lookup purposes. Only
6683 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006684 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006685 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006686 if (ObjectType->isRecordType())
6687 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006688 else if (ObjectType->isDependentType())
6689 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006691
6692 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006693 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006694 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006695 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006696 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006697 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006698 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006699 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006700 S, &SS, true, false, ObjectTypePtrForLookup,
6701 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006703 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6704 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006705 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006706 // couldn't find anything useful in scope. Just store the identifier and
6707 // it's location, and we'll perform (qualified) name lookup again at
6708 // template instantiation time.
6709 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6710 SecondTypeName.StartLocation);
6711 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006713 diag::err_pseudo_dtor_destructor_non_type)
6714 << SecondTypeName.Identifier << ObjectType;
6715 if (isSFINAEContext())
6716 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006718 // Recover by assuming we had the right type all along.
6719 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006720 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006721 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006722 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006723 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006724 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006725 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006726 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006727 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006728 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006729 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006730 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006731 TemplateId->TemplateNameLoc,
6732 TemplateId->LAngleLoc,
6733 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006734 TemplateId->RAngleLoc,
6735 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006736 if (T.isInvalid() || !T.get()) {
6737 // Recover by assuming we had the right type all along.
6738 DestructedType = ObjectType;
6739 } else
6740 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006742
6743 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006744 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006745 if (!DestructedType.isNull()) {
6746 if (!DestructedTypeInfo)
6747 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006748 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006749 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006752 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006753 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006754 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006756 FirstTypeName.Identifier) {
6757 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006759 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006760 S, &SS, true, false, ObjectTypePtrForLookup,
6761 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006762 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006764 diag::err_pseudo_dtor_destructor_non_type)
6765 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006766
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006767 if (isSFINAEContext())
6768 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006769
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006770 // Just drop this type. It's unnecessary anyway.
6771 ScopeType = QualType();
6772 } else
6773 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006774 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006775 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006776 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006777 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006778 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006779 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006780 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006781 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006782 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006783 TemplateId->TemplateNameLoc,
6784 TemplateId->LAngleLoc,
6785 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006786 TemplateId->RAngleLoc,
6787 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006788 if (T.isInvalid() || !T.get()) {
6789 // Recover by dropping this type.
6790 ScopeType = QualType();
6791 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006793 }
6794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Douglas Gregor90ad9222010-02-24 23:02:30 +00006796 if (!ScopeType.isNull() && !ScopeTypeInfo)
6797 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6798 FirstTypeName.StartLocation);
6799
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
John McCallb268a282010-08-23 23:25:46 +00006801 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006802 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006803 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006804}
6805
David Blaikie1d578782011-12-16 16:03:09 +00006806ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6807 SourceLocation OpLoc,
6808 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006809 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006810 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006811 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006812 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6813 return ExprError();
6814
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006815 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6816 false);
David Blaikie1d578782011-12-16 16:03:09 +00006817
6818 TypeLocBuilder TLB;
6819 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6820 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6821 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6822 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6823
6824 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006825 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006826 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006827}
6828
John Wiegley01296292011-04-08 18:41:53 +00006829ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006830 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006831 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006832 if (Method->getParent()->isLambda() &&
6833 Method->getConversionType()->isBlockPointerType()) {
6834 // This is a lambda coversion to block pointer; check if the argument
6835 // is a LambdaExpr.
6836 Expr *SubE = E;
6837 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6838 if (CE && CE->getCastKind() == CK_NoOp)
6839 SubE = CE->getSubExpr();
6840 SubE = SubE->IgnoreParens();
6841 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6842 SubE = BE->getSubExpr();
6843 if (isa<LambdaExpr>(SubE)) {
6844 // For the conversion to block pointer on a lambda expression, we
6845 // construct a special BlockLiteral instead; this doesn't really make
6846 // a difference in ARC, but outside of ARC the resulting block literal
6847 // follows the normal lifetime rules for block literals instead of being
6848 // autoreleased.
6849 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00006850 PushExpressionEvaluationContext(
6851 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006852 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6853 E->getExprLoc(),
6854 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006855 PopExpressionEvaluationContext();
6856
Eli Friedman98b01ed2012-03-01 04:01:32 +00006857 if (Exp.isInvalid())
6858 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6859 return Exp;
6860 }
6861 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006862
Craig Topperc3ec1492014-05-26 06:22:03 +00006863 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006864 FoundDecl, Method);
6865 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006866 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006867
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006868 MemberExpr *ME = new (Context) MemberExpr(
6869 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6870 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006871 if (HadMultipleCandidates)
6872 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006873 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006874
Alp Toker314cc812014-01-25 16:55:45 +00006875 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006876 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6877 ResultType = ResultType.getNonLValueExprType(Context);
6878
Douglas Gregor27381f32009-11-23 12:27:39 +00006879 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006880 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006881 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006882
6883 if (CheckFunctionCall(Method, CE,
6884 Method->getType()->castAs<FunctionProtoType>()))
6885 return ExprError();
6886
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006887 return CE;
6888}
6889
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006890ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6891 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006892 // If the operand is an unresolved lookup expression, the expression is ill-
6893 // formed per [over.over]p1, because overloaded function names cannot be used
6894 // without arguments except in explicit contexts.
6895 ExprResult R = CheckPlaceholderExpr(Operand);
6896 if (R.isInvalid())
6897 return R;
6898
6899 // The operand may have been modified when checking the placeholder type.
6900 Operand = R.get();
6901
Richard Smith51ec0cf2017-02-21 01:17:38 +00006902 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006903 // The expression operand for noexcept is in an unevaluated expression
6904 // context, so side effects could result in unintended consequences.
6905 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6906 }
6907
Richard Smithf623c962012-04-17 00:58:00 +00006908 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006909 return new (Context)
6910 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006911}
6912
6913ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6914 Expr *Operand, SourceLocation RParen) {
6915 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006916}
6917
Eli Friedmanf798f652012-05-24 22:04:19 +00006918static bool IsSpecialDiscardedValue(Expr *E) {
6919 // In C++11, discarded-value expressions of a certain form are special,
6920 // according to [expr]p10:
6921 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6922 // expression is an lvalue of volatile-qualified type and it has
6923 // one of the following forms:
6924 E = E->IgnoreParens();
6925
Eli Friedmanc49c2262012-05-24 22:36:31 +00006926 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006927 if (isa<DeclRefExpr>(E))
6928 return true;
6929
Eli Friedmanc49c2262012-05-24 22:36:31 +00006930 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006931 if (isa<ArraySubscriptExpr>(E))
6932 return true;
6933
Eli Friedmanc49c2262012-05-24 22:36:31 +00006934 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006935 if (isa<MemberExpr>(E))
6936 return true;
6937
Eli Friedmanc49c2262012-05-24 22:36:31 +00006938 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006939 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6940 if (UO->getOpcode() == UO_Deref)
6941 return true;
6942
6943 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006944 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006945 if (BO->isPtrMemOp())
6946 return true;
6947
Eli Friedmanc49c2262012-05-24 22:36:31 +00006948 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006949 if (BO->getOpcode() == BO_Comma)
6950 return IsSpecialDiscardedValue(BO->getRHS());
6951 }
6952
Eli Friedmanc49c2262012-05-24 22:36:31 +00006953 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006954 // operands are one of the above, or
6955 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6956 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6957 IsSpecialDiscardedValue(CO->getFalseExpr());
6958 // The related edge case of "*x ?: *x".
6959 if (BinaryConditionalOperator *BCO =
6960 dyn_cast<BinaryConditionalOperator>(E)) {
6961 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6962 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6963 IsSpecialDiscardedValue(BCO->getFalseExpr());
6964 }
6965
6966 // Objective-C++ extensions to the rule.
6967 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6968 return true;
6969
6970 return false;
6971}
6972
John McCall34376a62010-12-04 03:47:34 +00006973/// Perform the conversions required for an expression used in a
6974/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006975ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006976 if (E->hasPlaceholderType()) {
6977 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006978 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006979 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006980 }
6981
John McCallfee942d2010-12-02 02:07:15 +00006982 // C99 6.3.2.1:
6983 // [Except in specific positions,] an lvalue that does not have
6984 // array type is converted to the value stored in the
6985 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006986 if (E->isRValue()) {
6987 // In C, function designators (i.e. expressions of function type)
6988 // are r-values, but we still want to do function-to-pointer decay
6989 // on them. This is both technically correct and convenient for
6990 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006991 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006992 return DefaultFunctionArrayConversion(E);
6993
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006994 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006995 }
John McCallfee942d2010-12-02 02:07:15 +00006996
Eli Friedmanf798f652012-05-24 22:04:19 +00006997 if (getLangOpts().CPlusPlus) {
6998 // The C++11 standard defines the notion of a discarded-value expression;
6999 // normally, we don't need to do anything to handle it, but if it is a
7000 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7001 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007002 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007003 E->getType().isVolatileQualified() &&
7004 IsSpecialDiscardedValue(E)) {
7005 ExprResult Res = DefaultLvalueConversion(E);
7006 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007007 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007008 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007009 }
Richard Smith122f88d2016-12-06 23:52:28 +00007010
7011 // C++1z:
7012 // If the expression is a prvalue after this optional conversion, the
7013 // temporary materialization conversion is applied.
7014 //
7015 // We skip this step: IR generation is able to synthesize the storage for
7016 // itself in the aggregate case, and adding the extra node to the AST is
7017 // just clutter.
7018 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7019 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007020 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007021 }
John McCall34376a62010-12-04 03:47:34 +00007022
7023 // GCC seems to also exclude expressions of incomplete enum type.
7024 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7025 if (!T->getDecl()->isComplete()) {
7026 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007027 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007028 return E;
John McCall34376a62010-12-04 03:47:34 +00007029 }
7030 }
7031
John Wiegley01296292011-04-08 18:41:53 +00007032 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7033 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007034 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007035 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007036
John McCallca61b652010-12-04 12:29:11 +00007037 if (!E->getType()->isVoidType())
7038 RequireCompleteType(E->getExprLoc(), E->getType(),
7039 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007040 return E;
John McCall34376a62010-12-04 03:47:34 +00007041}
7042
Faisal Valia17d19f2013-11-07 05:17:06 +00007043// If we can unambiguously determine whether Var can never be used
7044// in a constant expression, return true.
7045// - if the variable and its initializer are non-dependent, then
7046// we can unambiguously check if the variable is a constant expression.
7047// - if the initializer is not value dependent - we can determine whether
7048// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007049// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007050// never be a constant expression.
7051// - FXIME: if the initializer is dependent, we can still do some analysis and
7052// identify certain cases unambiguously as non-const by using a Visitor:
7053// - such as those that involve odr-use of a ParmVarDecl, involve a new
7054// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007055static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007056 ASTContext &Context) {
7057 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007058 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007059
7060 // If there is no initializer - this can not be a constant expression.
7061 if (!Var->getAnyInitializer(DefVD)) return true;
7062 assert(DefVD);
7063 if (DefVD->isWeak()) return false;
7064 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007065
Faisal Valia17d19f2013-11-07 05:17:06 +00007066 Expr *Init = cast<Expr>(Eval->Value);
7067
7068 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007069 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7070 // of value-dependent expressions, and use it here to determine whether the
7071 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007072 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007073 }
7074
Simon Pilgrim75c26882016-09-30 14:25:09 +00007075 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007076}
7077
Simon Pilgrim75c26882016-09-30 14:25:09 +00007078/// \brief Check if the current lambda has any potential captures
7079/// that must be captured by any of its enclosing lambdas that are ready to
7080/// capture. If there is a lambda that can capture a nested
7081/// potential-capture, go ahead and do so. Also, check to see if any
7082/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007083/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007084
Faisal Valiab3d6462013-12-07 20:22:44 +00007085static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7086 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7087
Simon Pilgrim75c26882016-09-30 14:25:09 +00007088 assert(!S.isUnevaluatedContext());
7089 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007090#ifndef NDEBUG
7091 DeclContext *DC = S.CurContext;
7092 while (DC && isa<CapturedDecl>(DC))
7093 DC = DC->getParent();
7094 assert(
7095 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007096 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007097#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007098
7099 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7100
7101 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7102 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007103
Faisal Valiab3d6462013-12-07 20:22:44 +00007104 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007105 // lambda (within a generic outer lambda), must be captured by an
7106 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007107 const unsigned NumPotentialCaptures =
7108 CurrentLSI->getNumPotentialVariableCaptures();
7109 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007110 Expr *VarExpr = nullptr;
7111 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007112 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007113 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007114 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007115 // need to check enclosing lambda's for speculative captures.
7116 // For e.g.:
7117 // Even though 'x' is not odr-used, it should be captured.
7118 // int test() {
7119 // const int x = 10;
7120 // auto L = [=](auto a) {
7121 // (void) +x + a;
7122 // };
7123 // }
7124 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007125 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007126 continue;
7127
7128 // If we have a capture-capable lambda for the variable, go ahead and
7129 // capture the variable in that lambda (and all its enclosing lambdas).
7130 if (const Optional<unsigned> Index =
7131 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7132 FunctionScopesArrayRef, Var, S)) {
7133 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7134 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7135 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007136 }
7137 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007138 VariableCanNeverBeAConstantExpression(Var, S.Context);
7139 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7140 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007141 // can not be used in a constant expression - which means
7142 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007143 // capture violation early, if the variable is un-captureable.
7144 // This is purely for diagnosing errors early. Otherwise, this
7145 // error would get diagnosed when the lambda becomes capture ready.
7146 QualType CaptureType, DeclRefType;
7147 SourceLocation ExprLoc = VarExpr->getExprLoc();
7148 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007149 /*EllipsisLoc*/ SourceLocation(),
7150 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007151 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007152 // We will never be able to capture this variable, and we need
7153 // to be able to in any and all instantiations, so diagnose it.
7154 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007155 /*EllipsisLoc*/ SourceLocation(),
7156 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007157 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007158 }
7159 }
7160 }
7161
Faisal Valiab3d6462013-12-07 20:22:44 +00007162 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007163 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007164 // If we have a capture-capable lambda for 'this', go ahead and capture
7165 // 'this' in that lambda (and all its enclosing lambdas).
7166 if (const Optional<unsigned> Index =
7167 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007168 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007169 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7170 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7171 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7172 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007173 }
7174 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007175
7176 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007177 CurrentLSI->clearPotentialCaptures();
7178}
7179
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007180static ExprResult attemptRecovery(Sema &SemaRef,
7181 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007182 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007183 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7184 Consumer.getLookupResult().getLookupKind());
7185 const CXXScopeSpec *SS = Consumer.getSS();
7186 CXXScopeSpec NewSS;
7187
7188 // Use an approprate CXXScopeSpec for building the expr.
7189 if (auto *NNS = TC.getCorrectionSpecifier())
7190 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7191 else if (SS && !TC.WillReplaceSpecifier())
7192 NewSS = *SS;
7193
Richard Smithde6d6c42015-12-29 19:43:10 +00007194 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007195 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007196 R.addDecl(ND);
7197 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007198 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007199 CXXRecordDecl *Record = nullptr;
7200 if (auto *NNS = TC.getCorrectionSpecifier())
7201 Record = NNS->getAsType()->getAsCXXRecordDecl();
7202 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007203 Record =
7204 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7205 if (Record)
7206 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007207
7208 // Detect and handle the case where the decl might be an implicit
7209 // member.
7210 bool MightBeImplicitMember;
7211 if (!Consumer.isAddressOfOperand())
7212 MightBeImplicitMember = true;
7213 else if (!NewSS.isEmpty())
7214 MightBeImplicitMember = false;
7215 else if (R.isOverloadedResult())
7216 MightBeImplicitMember = false;
7217 else if (R.isUnresolvableResult())
7218 MightBeImplicitMember = true;
7219 else
7220 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7221 isa<IndirectFieldDecl>(ND) ||
7222 isa<MSPropertyDecl>(ND);
7223
7224 if (MightBeImplicitMember)
7225 return SemaRef.BuildPossibleImplicitMemberExpr(
7226 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007227 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007228 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7229 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7230 Ivar->getIdentifier());
7231 }
7232 }
7233
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007234 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7235 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007236}
7237
Kaelyn Takata6c759512014-10-27 18:07:37 +00007238namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007239class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7240 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7241
7242public:
7243 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7244 : TypoExprs(TypoExprs) {}
7245 bool VisitTypoExpr(TypoExpr *TE) {
7246 TypoExprs.insert(TE);
7247 return true;
7248 }
7249};
7250
Kaelyn Takata6c759512014-10-27 18:07:37 +00007251class TransformTypos : public TreeTransform<TransformTypos> {
7252 typedef TreeTransform<TransformTypos> BaseTransform;
7253
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007254 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7255 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007256 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007257 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007258 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007259 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007260
7261 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7262 /// If the TypoExprs were successfully corrected, then the diagnostics should
7263 /// suggest the corrections. Otherwise the diagnostics will not suggest
7264 /// anything (having been passed an empty TypoCorrection).
7265 void EmitAllDiagnostics() {
7266 for (auto E : TypoExprs) {
7267 TypoExpr *TE = cast<TypoExpr>(E);
7268 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007269 if (State.DiagHandler) {
7270 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7271 ExprResult Replacement = TransformCache[TE];
7272
7273 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7274 // TypoCorrection, replacing the existing decls. This ensures the right
7275 // NamedDecl is used in diagnostics e.g. in the case where overload
7276 // resolution was used to select one from several possible decls that
7277 // had been stored in the TypoCorrection.
7278 if (auto *ND = getDeclFromExpr(
7279 Replacement.isInvalid() ? nullptr : Replacement.get()))
7280 TC.setCorrectionDecl(ND);
7281
7282 State.DiagHandler(TC);
7283 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007284 SemaRef.clearDelayedTypo(TE);
7285 }
7286 }
7287
7288 /// \brief If corrections for the first TypoExpr have been exhausted for a
7289 /// given combination of the other TypoExprs, retry those corrections against
7290 /// the next combination of substitutions for the other TypoExprs by advancing
7291 /// to the next potential correction of the second TypoExpr. For the second
7292 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7293 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7294 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7295 /// TransformCache). Returns true if there is still any untried combinations
7296 /// of corrections.
7297 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7298 for (auto TE : TypoExprs) {
7299 auto &State = SemaRef.getTypoExprState(TE);
7300 TransformCache.erase(TE);
7301 if (!State.Consumer->finished())
7302 return true;
7303 State.Consumer->resetCorrectionStream();
7304 }
7305 return false;
7306 }
7307
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007308 NamedDecl *getDeclFromExpr(Expr *E) {
7309 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7310 E = OverloadResolution[OE];
7311
7312 if (!E)
7313 return nullptr;
7314 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007315 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007316 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007317 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007318 // FIXME: Add any other expr types that could be be seen by the delayed typo
7319 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007320 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007321 return nullptr;
7322 }
7323
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007324 ExprResult TryTransform(Expr *E) {
7325 Sema::SFINAETrap Trap(SemaRef);
7326 ExprResult Res = TransformExpr(E);
7327 if (Trap.hasErrorOccurred() || Res.isInvalid())
7328 return ExprError();
7329
7330 return ExprFilter(Res.get());
7331 }
7332
Kaelyn Takata6c759512014-10-27 18:07:37 +00007333public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007334 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7335 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007336
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007337 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7338 MultiExprArg Args,
7339 SourceLocation RParenLoc,
7340 Expr *ExecConfig = nullptr) {
7341 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7342 RParenLoc, ExecConfig);
7343 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007344 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007345 Expr *ResultCall = Result.get();
7346 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7347 ResultCall = BE->getSubExpr();
7348 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7349 OverloadResolution[OE] = CE->getCallee();
7350 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007351 }
7352 return Result;
7353 }
7354
Kaelyn Takata6c759512014-10-27 18:07:37 +00007355 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7356
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007357 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7358
Kaelyn Takata6c759512014-10-27 18:07:37 +00007359 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007360 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007361 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007362 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007363
Kaelyn Takata6c759512014-10-27 18:07:37 +00007364 // Exit if either the transform was valid or if there were no TypoExprs
7365 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007366 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007367 !CheckAndAdvanceTypoExprCorrectionStreams())
7368 break;
7369 }
7370
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007371 // Ensure none of the TypoExprs have multiple typo correction candidates
7372 // with the same edit length that pass all the checks and filters.
7373 // TODO: Properly handle various permutations of possible corrections when
7374 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007375 // Also, disable typo correction while attempting the transform when
7376 // handling potentially ambiguous typo corrections as any new TypoExprs will
7377 // have been introduced by the application of one of the correction
7378 // candidates and add little to no value if corrected.
7379 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007380 while (!AmbiguousTypoExprs.empty()) {
7381 auto TE = AmbiguousTypoExprs.back();
7382 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007383 auto &State = SemaRef.getTypoExprState(TE);
7384 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007385 TransformCache.erase(TE);
7386 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007387 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007388 TransformCache.erase(TE);
7389 Res = ExprError();
7390 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007391 }
7392 AmbiguousTypoExprs.remove(TE);
7393 State.Consumer->restoreSavedPosition();
7394 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007395 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007396 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007397
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007398 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007399 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007400 FindTypoExprs(TypoExprs).TraverseStmt(E);
7401
Kaelyn Takata6c759512014-10-27 18:07:37 +00007402 EmitAllDiagnostics();
7403
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007404 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007405 }
7406
7407 ExprResult TransformTypoExpr(TypoExpr *E) {
7408 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7409 // cached transformation result if there is one and the TypoExpr isn't the
7410 // first one that was encountered.
7411 auto &CacheEntry = TransformCache[E];
7412 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7413 return CacheEntry;
7414 }
7415
7416 auto &State = SemaRef.getTypoExprState(E);
7417 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7418
7419 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7420 // typo correction and return it.
7421 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007422 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007423 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007424 // FIXME: If we would typo-correct to an invalid declaration, it's
7425 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007426 ExprResult NE = State.RecoveryHandler ?
7427 State.RecoveryHandler(SemaRef, E, TC) :
7428 attemptRecovery(SemaRef, *State.Consumer, TC);
7429 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007430 // Check whether there may be a second viable correction with the same
7431 // edit distance; if so, remember this TypoExpr may have an ambiguous
7432 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007433 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007434 if ((Next = State.Consumer->peekNextCorrection()) &&
7435 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7436 AmbiguousTypoExprs.insert(E);
7437 } else {
7438 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007439 }
7440 assert(!NE.isUnset() &&
7441 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007442 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007443 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007444 }
7445 return CacheEntry = ExprError();
7446 }
7447};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007448}
Faisal Valia17d19f2013-11-07 05:17:06 +00007449
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007450ExprResult
7451Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7452 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007453 // If the current evaluation context indicates there are uncorrected typos
7454 // and the current expression isn't guaranteed to not have typos, try to
7455 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007456 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007457 (E->isTypeDependent() || E->isValueDependent() ||
7458 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007459 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7460 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7461 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007462 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007463 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007464 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007465 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007466 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007467 ExprEvalContexts.back().NumTypos -= TyposResolved;
7468 return Result;
7469 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007470 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007471 }
7472 return E;
7473}
7474
Richard Smith945f8d32013-01-14 22:39:08 +00007475ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007476 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007477 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007478 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007479 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007480
7481 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007482 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007483
7484 // If we are an init-expression in a lambdas init-capture, we should not
7485 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007486 // containing full-expression is done).
7487 // template<class ... Ts> void test(Ts ... t) {
7488 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7489 // return a;
7490 // }() ...);
7491 // }
7492 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7493 // when we parse the lambda introducer, and teach capturing (but not
7494 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7495 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7496 // lambda where we've entered the introducer but not the body, or represent a
7497 // lambda where we've entered the body, depending on where the
7498 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007499 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007500 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007501 return ExprError();
7502
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007503 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007504 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007505 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007506 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007507 if (FullExpr.isInvalid())
7508 return ExprError();
7509 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007510
Richard Smith945f8d32013-01-14 22:39:08 +00007511 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007512 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007513 if (FullExpr.isInvalid())
7514 return ExprError();
7515
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007516 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007517 if (FullExpr.isInvalid())
7518 return ExprError();
7519 }
John Wiegley01296292011-04-08 18:41:53 +00007520
Kaelyn Takata49d84322014-11-11 23:26:56 +00007521 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7522 if (FullExpr.isInvalid())
7523 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007524
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007525 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007526
Simon Pilgrim75c26882016-09-30 14:25:09 +00007527 // At the end of this full expression (which could be a deeply nested
7528 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007529 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007530 // Consider the following code:
7531 // void f(int, int);
7532 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007533 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007534 // const int x = 10, y = 20;
7535 // auto L = [=](auto a) {
7536 // auto M = [=](auto b) {
7537 // f(x, b); <-- requires x to be captured by L and M
7538 // f(y, a); <-- requires y to be captured by L, but not all Ms
7539 // };
7540 // };
7541 // }
7542
Simon Pilgrim75c26882016-09-30 14:25:09 +00007543 // FIXME: Also consider what happens for something like this that involves
7544 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007545 // void f() {
7546 // const int n = 0;
7547 // auto L = [&](auto a) {
7548 // +n + ({ 0; a; });
7549 // };
7550 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007551 //
7552 // Here, we see +n, and then the full-expression 0; ends, so we don't
7553 // capture n (and instead remove it from our list of potential captures),
7554 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007555 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007556
Alexey Bataev31939e32016-11-11 12:36:20 +00007557 LambdaScopeInfo *const CurrentLSI =
7558 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007559 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007560 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007561 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007562 // By ensuring we are in the context of a lambda's call operator
7563 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007564 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007565 // PR, a proper fix would entail :
7566 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007567 // - Add to Sema an integer holding the smallest (outermost) scope
7568 // index that we are *lexically* within, and save/restore/set to
7569 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007570 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007571 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007572 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007573 DeclContext *DC = CurContext;
7574 while (DC && isa<CapturedDecl>(DC))
7575 DC = DC->getParent();
7576 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007577 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007578 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007579 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7580 *this);
John McCall5d413782010-12-06 08:20:24 +00007581 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007582}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007583
7584StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7585 if (!FullStmt) return StmtError();
7586
John McCall5d413782010-12-06 08:20:24 +00007587 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007588}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007589
Simon Pilgrim75c26882016-09-30 14:25:09 +00007590Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007591Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7592 CXXScopeSpec &SS,
7593 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007594 DeclarationName TargetName = TargetNameInfo.getName();
7595 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007596 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007597
Douglas Gregor43edb322011-10-24 22:31:10 +00007598 // If the name itself is dependent, then the result is dependent.
7599 if (TargetName.isDependentName())
7600 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007601
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007602 // Do the redeclaration lookup in the current scope.
7603 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7604 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007605 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007606 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007607
Douglas Gregor43edb322011-10-24 22:31:10 +00007608 switch (R.getResultKind()) {
7609 case LookupResult::Found:
7610 case LookupResult::FoundOverloaded:
7611 case LookupResult::FoundUnresolvedValue:
7612 case LookupResult::Ambiguous:
7613 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007614
Douglas Gregor43edb322011-10-24 22:31:10 +00007615 case LookupResult::NotFound:
7616 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007617
Douglas Gregor43edb322011-10-24 22:31:10 +00007618 case LookupResult::NotFoundInCurrentInstantiation:
7619 return IER_Dependent;
7620 }
David Blaikie8a40f702012-01-17 06:56:22 +00007621
7622 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007623}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007624
Simon Pilgrim75c26882016-09-30 14:25:09 +00007625Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007626Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7627 bool IsIfExists, CXXScopeSpec &SS,
7628 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007629 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007630
Richard Smith151c4562016-12-20 21:35:28 +00007631 // Check for an unexpanded parameter pack.
7632 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7633 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7634 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007635 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007636
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007637 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7638}