blob: 456aff2fe00ed827bd4e1116ee92c63afaa6133f [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) {
3287 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3288 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
3302 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3303 if (PointeeRD->isAbstract()) {
3304 // If the class is abstract, we warn by default, because we're
3305 // sure the code has undefined behavior.
3306 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3307 << ClassType;
3308 } else if (WarnOnNonAbstractTypes) {
3309 // Otherwise, if this is not an array delete, it's a bit suspect,
3310 // but not necessarily wrong.
3311 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3312 << ClassType;
3313 }
3314 if (!IsDelete) {
3315 std::string TypeStr;
3316 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3317 Diag(DtorLoc, diag::note_delete_non_virtual)
3318 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3319 }
3320}
3321
Richard Smith03a4aa32016-06-23 19:02:52 +00003322Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3323 SourceLocation StmtLoc,
3324 ConditionKind CK) {
3325 ExprResult E =
3326 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3327 if (E.isInvalid())
3328 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003329 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3330 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003331}
3332
Douglas Gregor633caca2009-11-23 23:44:04 +00003333/// \brief Check the use of the given variable as a C++ condition in an if,
3334/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003335ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003336 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003337 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003338 if (ConditionVar->isInvalidDecl())
3339 return ExprError();
3340
Douglas Gregor633caca2009-11-23 23:44:04 +00003341 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342
Douglas Gregor633caca2009-11-23 23:44:04 +00003343 // C++ [stmt.select]p2:
3344 // The declarator shall not specify a function or an array.
3345 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003347 diag::err_invalid_use_of_function_type)
3348 << ConditionVar->getSourceRange());
3349 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003351 diag::err_invalid_use_of_array_type)
3352 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003354 ExprResult Condition = DeclRefExpr::Create(
3355 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3356 /*enclosing*/ false, ConditionVar->getLocation(),
3357 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003358
Eli Friedmanfa0df832012-02-02 03:46:19 +00003359 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003360
Richard Smith03a4aa32016-06-23 19:02:52 +00003361 switch (CK) {
3362 case ConditionKind::Boolean:
3363 return CheckBooleanCondition(StmtLoc, Condition.get());
3364
Richard Smithb130fe72016-06-23 19:16:49 +00003365 case ConditionKind::ConstexprIf:
3366 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3367
Richard Smith03a4aa32016-06-23 19:02:52 +00003368 case ConditionKind::Switch:
3369 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371
Richard Smith03a4aa32016-06-23 19:02:52 +00003372 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003373}
3374
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003375/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003376ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003377 // C++ 6.4p4:
3378 // The value of a condition that is an initialized declaration in a statement
3379 // other than a switch statement is the value of the declared variable
3380 // implicitly converted to type bool. If that conversion is ill-formed, the
3381 // program is ill-formed.
3382 // The value of a condition that is an expression is the value of the
3383 // expression, implicitly converted to bool.
3384 //
Richard Smithb130fe72016-06-23 19:16:49 +00003385 // FIXME: Return this value to the caller so they don't need to recompute it.
3386 llvm::APSInt Value(/*BitWidth*/1);
3387 return (IsConstexpr && !CondExpr->isValueDependent())
3388 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3389 CCEK_ConstexprIf)
3390 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003391}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003392
3393/// Helper function to determine whether this is the (deprecated) C++
3394/// conversion from a string literal to a pointer to non-const char or
3395/// non-const wchar_t (for narrow and wide string literals,
3396/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003397bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003398Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3399 // Look inside the implicit cast, if it exists.
3400 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3401 From = Cast->getSubExpr();
3402
3403 // A string literal (2.13.4) that is not a wide string literal can
3404 // be converted to an rvalue of type "pointer to char"; a wide
3405 // string literal can be converted to an rvalue of type "pointer
3406 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003407 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003408 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003409 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003410 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003411 // This conversion is considered only when there is an
3412 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003413 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3414 switch (StrLit->getKind()) {
3415 case StringLiteral::UTF8:
3416 case StringLiteral::UTF16:
3417 case StringLiteral::UTF32:
3418 // We don't allow UTF literals to be implicitly converted
3419 break;
3420 case StringLiteral::Ascii:
3421 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3422 ToPointeeType->getKind() == BuiltinType::Char_S);
3423 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003424 return Context.typesAreCompatible(Context.getWideCharType(),
3425 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003426 }
3427 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003428 }
3429
3430 return false;
3431}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003432
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003434 SourceLocation CastLoc,
3435 QualType Ty,
3436 CastKind Kind,
3437 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003438 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003439 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003440 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003441 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003442 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003443 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003444 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003445 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Richard Smith72d74052013-07-20 19:41:36 +00003447 if (S.RequireNonAbstractType(CastLoc, Ty,
3448 diag::err_allocation_of_abstract_type))
3449 return ExprError();
3450
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003451 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003452 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453
Richard Smith5179eb72016-06-28 19:03:57 +00003454 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3455 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003456 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003457 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003458
Richard Smithf8adcdc2014-07-17 05:12:35 +00003459 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003460 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003461 ConstructorArgs, HadMultipleCandidates,
3462 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3463 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003464 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003465 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003467 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
John McCalle3027922010-08-25 11:45:40 +00003470 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003471 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Richard Smithd3f2d322015-02-24 21:16:19 +00003473 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003474 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003475 return ExprError();
3476
Douglas Gregora4253922010-04-16 22:17:36 +00003477 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003478 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3479 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003480 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003481 if (Result.isInvalid())
3482 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003483 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003484 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3485 CK_UserDefinedConversion, Result.get(),
3486 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487
Douglas Gregor668443e2011-01-20 00:18:04 +00003488 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003489 }
3490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491}
Douglas Gregora4253922010-04-16 22:17:36 +00003492
Douglas Gregor5fb53972009-01-14 15:45:31 +00003493/// PerformImplicitConversion - Perform an implicit conversion of the
3494/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003495/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003496/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003497/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003498ExprResult
3499Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003500 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003501 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003502 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003503 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003504 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003505 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3506 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003507 if (Res.isInvalid())
3508 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003509 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003510 break;
John Wiegley01296292011-04-08 18:41:53 +00003511 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003512
Anders Carlsson110b07b2009-09-15 06:28:28 +00003513 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003515 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003516 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003517 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003518 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003519 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003520 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Anders Carlsson110b07b2009-09-15 06:28:28 +00003522 // If the user-defined conversion is specified by a conversion function,
3523 // the initial standard conversion sequence converts the source type to
3524 // the implicit object parameter of the conversion function.
3525 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003526 } else {
3527 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003528 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003529 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003530 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003532 // initial standard conversion sequence converts the source type to
3533 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003534 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536 }
Richard Smith72d74052013-07-20 19:41:36 +00003537 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003538 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003539 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003540 PerformImplicitConversion(From, BeforeToType,
3541 ICS.UserDefined.Before, AA_Converting,
3542 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003543 if (Res.isInvalid())
3544 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003545 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547
3548 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003549 = BuildCXXCastArgument(*this,
3550 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003551 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003552 CastKind, cast<CXXMethodDecl>(FD),
3553 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003554 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003555 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003556
3557 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003558 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003559
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003560 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003561
Richard Smith507840d2011-11-29 22:48:16 +00003562 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3563 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003564 }
John McCall0d1da222010-01-12 00:44:57 +00003565
3566 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003567 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003568 PDiag(diag::err_typecheck_ambiguous_condition)
3569 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003570 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregor39c16d42008-10-24 04:54:22 +00003572 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003573 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003574
3575 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003576 bool Diagnosed =
3577 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3578 From->getType(), From, Action);
3579 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003580 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003581 }
3582
3583 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003584 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003585}
3586
Richard Smith507840d2011-11-29 22:48:16 +00003587/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003588/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003589/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003590/// expression. Flavor is the context in which we're performing this
3591/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003592ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003593Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003594 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003595 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003596 CheckedConversionKind CCK) {
3597 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003598
Mike Stump87c57ac2009-05-16 07:39:55 +00003599 // Overall FIXME: we are recomputing too many types here and doing far too
3600 // much extra work. What this means is that we need to keep track of more
3601 // information that is computed when we try the implicit conversion initially,
3602 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003603 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003604
Douglas Gregor2fe98832008-11-03 19:09:14 +00003605 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003606 // FIXME: When can ToType be a reference type?
3607 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003608 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003609 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003610 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003611 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003612 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003613 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003614 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003615 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3616 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003617 ConstructorArgs, /*HadMultipleCandidates*/ false,
3618 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3619 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003620 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003621 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003622 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3623 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003624 From, /*HadMultipleCandidates*/ false,
3625 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3626 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003627 }
3628
Douglas Gregor980fb162010-04-29 18:24:40 +00003629 // Resolve overloaded function references.
3630 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3631 DeclAccessPair Found;
3632 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3633 true, Found);
3634 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003635 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003636
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003637 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003638 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639
Douglas Gregor980fb162010-04-29 18:24:40 +00003640 From = FixOverloadedFunctionReference(From, Found, Fn);
3641 FromType = From->getType();
3642 }
3643
Richard Smitha23ab512013-05-23 00:30:41 +00003644 // If we're converting to an atomic type, first convert to the corresponding
3645 // non-atomic type.
3646 QualType ToAtomicType;
3647 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3648 ToAtomicType = ToType;
3649 ToType = ToAtomic->getValueType();
3650 }
3651
George Burgess IV8d141e02015-12-14 22:00:49 +00003652 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003653 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003654 switch (SCS.First) {
3655 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003656 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3657 FromType = FromAtomic->getValueType().getUnqualifiedType();
3658 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3659 From, /*BasePath=*/nullptr, VK_RValue);
3660 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003661 break;
3662
Eli Friedman946b7b52012-01-24 22:51:26 +00003663 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003664 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003665 ExprResult FromRes = DefaultLvalueConversion(From);
3666 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003667 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003668 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003669 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003670 }
John McCall34376a62010-12-04 03:47:34 +00003671
Douglas Gregor39c16d42008-10-24 04:54:22 +00003672 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003673 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003674 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003675 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003676 break;
3677
3678 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003679 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003680 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003681 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003682 break;
3683
3684 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003685 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003686 }
3687
Richard Smith507840d2011-11-29 22:48:16 +00003688 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003689 switch (SCS.Second) {
3690 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003691 // C++ [except.spec]p5:
3692 // [For] assignment to and initialization of pointers to functions,
3693 // pointers to member functions, and references to functions: the
3694 // target entity shall allow at least the exceptions allowed by the
3695 // source value in the assignment or initialization.
3696 switch (Action) {
3697 case AA_Assigning:
3698 case AA_Initializing:
3699 // Note, function argument passing and returning are initialization.
3700 case AA_Passing:
3701 case AA_Returning:
3702 case AA_Sending:
3703 case AA_Passing_CFAudited:
3704 if (CheckExceptionSpecCompatibility(From, ToType))
3705 return ExprError();
3706 break;
3707
3708 case AA_Casting:
3709 case AA_Converting:
3710 // Casts and implicit conversions are not initialization, so are not
3711 // checked for exception specification mismatches.
3712 break;
3713 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003714 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003715 break;
3716
3717 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003718 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003719 if (ToType->isBooleanType()) {
3720 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3721 SCS.Second == ICK_Integral_Promotion &&
3722 "only enums with fixed underlying type can promote to bool");
3723 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003724 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003725 } else {
3726 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003727 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003728 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003729 break;
3730
3731 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003732 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003733 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003734 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003735 break;
3736
3737 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003738 case ICK_Complex_Conversion: {
3739 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3740 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3741 CastKind CK;
3742 if (FromEl->isRealFloatingType()) {
3743 if (ToEl->isRealFloatingType())
3744 CK = CK_FloatingComplexCast;
3745 else
3746 CK = CK_FloatingComplexToIntegralComplex;
3747 } else if (ToEl->isRealFloatingType()) {
3748 CK = CK_IntegralComplexToFloatingComplex;
3749 } else {
3750 CK = CK_IntegralComplexCast;
3751 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003752 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003753 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003754 break;
John McCall8cb679e2010-11-15 09:13:47 +00003755 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003756
Douglas Gregor39c16d42008-10-24 04:54:22 +00003757 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003758 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003759 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003760 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003761 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003762 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003763 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003764 break;
3765
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003766 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003767 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003768 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003769 break;
3770
John McCall31168b02011-06-15 23:02:42 +00003771 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003772 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003773 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003774 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003775 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003776 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003777 diag::ext_typecheck_convert_incompatible_pointer)
3778 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003779 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003780 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003781 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003782 diag::ext_typecheck_convert_incompatible_pointer)
3783 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003784 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003785
Douglas Gregor33823722011-06-11 01:09:30 +00003786 if (From->getType()->isObjCObjectPointerType() &&
3787 ToType->isObjCObjectPointerType())
3788 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00003789 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3790 !CheckObjCARCUnavailableWeakConversion(ToType,
3791 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003792 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003793 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003794 diag::err_arc_weak_unavailable_assign);
3795 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003796 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003797 diag::err_arc_convesion_of_weak_unavailable)
3798 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003799 << From->getSourceRange();
3800 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003801
John McCall8cb679e2010-11-15 09:13:47 +00003802 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003803 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003804 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003805 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003806
3807 // Make sure we extend blocks if necessary.
3808 // FIXME: doing this here is really ugly.
3809 if (Kind == CK_BlockPointerToObjCPointerCast) {
3810 ExprResult E = From;
3811 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003812 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003813 }
Brian Kelley11352a82017-03-29 18:09:02 +00003814 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3815 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003816 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003817 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003818 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003821 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003822 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003823 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003824 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003825 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003826 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003827 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003828
3829 // We may not have been able to figure out what this member pointer resolved
3830 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003831 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003832 (void)isCompleteType(From->getExprLoc(), From->getType());
3833 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003834 }
David Majnemerd96b9972014-08-08 00:10:39 +00003835
Richard Smith507840d2011-11-29 22:48:16 +00003836 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003837 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003838 break;
3839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003841 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003842 // Perform half-to-boolean conversion via float.
3843 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003844 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003845 FromType = Context.FloatTy;
3846 }
3847
Richard Smith507840d2011-11-29 22:48:16 +00003848 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003849 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003850 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003851 break;
3852
Douglas Gregor88d292c2010-05-13 16:44:06 +00003853 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003854 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003856 ToType.getNonReferenceType(),
3857 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003859 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003860 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003861 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003862
Richard Smith507840d2011-11-29 22:48:16 +00003863 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3864 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003865 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003866 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003867 }
3868
Douglas Gregor46188682010-05-18 22:42:18 +00003869 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003870 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003871 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003872 break;
3873
George Burgess IVdf1ed002016-01-13 01:52:39 +00003874 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003875 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003876 Expr *Elem = prepareVectorSplat(ToType, From).get();
3877 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3878 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003879 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881
Douglas Gregor46188682010-05-18 22:42:18 +00003882 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003883 // Case 1. x -> _Complex y
3884 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3885 QualType ElType = ToComplex->getElementType();
3886 bool isFloatingComplex = ElType->isRealFloatingType();
3887
3888 // x -> y
3889 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3890 // do nothing
3891 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003892 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003893 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003894 } else {
3895 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003896 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003897 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003898 }
3899 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003900 From = ImpCastExprToType(From, ToType,
3901 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003902 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003903
3904 // Case 2. _Complex x -> y
3905 } else {
3906 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3907 assert(FromComplex);
3908
3909 QualType ElType = FromComplex->getElementType();
3910 bool isFloatingComplex = ElType->isRealFloatingType();
3911
3912 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003913 From = ImpCastExprToType(From, ElType,
3914 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003915 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003916 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003917
3918 // x -> y
3919 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3920 // do nothing
3921 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003922 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003923 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003924 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003925 } else {
3926 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003927 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003928 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003929 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003930 }
3931 }
Douglas Gregor46188682010-05-18 22:42:18 +00003932 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003933
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003934 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003935 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003936 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003937 break;
3938 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003939
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003940 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003941 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003942 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003943 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3944 if (FromRes.isInvalid())
3945 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003946 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003947 assert ((ConvTy == Sema::Compatible) &&
3948 "Improper transparent union conversion");
3949 (void)ConvTy;
3950 break;
3951 }
3952
Guy Benyei259f9f42013-02-07 16:05:33 +00003953 case ICK_Zero_Event_Conversion:
3954 From = ImpCastExprToType(From, ToType,
3955 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003956 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003957 break;
3958
Egor Churaev89831422016-12-23 14:55:49 +00003959 case ICK_Zero_Queue_Conversion:
3960 From = ImpCastExprToType(From, ToType,
3961 CK_ZeroToOCLQueue,
3962 From->getValueKind()).get();
3963 break;
3964
Douglas Gregor46188682010-05-18 22:42:18 +00003965 case ICK_Lvalue_To_Rvalue:
3966 case ICK_Array_To_Pointer:
3967 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003968 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003969 case ICK_Qualification:
3970 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003971 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003972 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003973 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003974 }
3975
3976 switch (SCS.Third) {
3977 case ICK_Identity:
3978 // Nothing to do.
3979 break;
3980
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003981 case ICK_Function_Conversion:
3982 // If both sides are functions (or pointers/references to them), there could
3983 // be incompatible exception declarations.
3984 if (CheckExceptionSpecCompatibility(From, ToType))
3985 return ExprError();
3986
3987 From = ImpCastExprToType(From, ToType, CK_NoOp,
3988 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3989 break;
3990
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003991 case ICK_Qualification: {
3992 // The qualification keeps the category of the inner expression, unless the
3993 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003994 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003995 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003996 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003997 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003998
Douglas Gregore981bb02011-03-14 16:13:32 +00003999 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004000 !getLangOpts().WritableStrings) {
4001 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4002 ? diag::ext_deprecated_string_literal_conversion
4003 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004004 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004005 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004006
Douglas Gregor39c16d42008-10-24 04:54:22 +00004007 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004008 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004009
Douglas Gregor39c16d42008-10-24 04:54:22 +00004010 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004011 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004012 }
4013
Douglas Gregor298f43d2012-04-12 20:42:30 +00004014 // If this conversion sequence involved a scalar -> atomic conversion, perform
4015 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004016 if (!ToAtomicType.isNull()) {
4017 assert(Context.hasSameType(
4018 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4019 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004020 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004021 }
4022
George Burgess IV8d141e02015-12-14 22:00:49 +00004023 // If this conversion sequence succeeded and involved implicitly converting a
4024 // _Nullable type to a _Nonnull one, complain.
4025 if (CCK == CCK_ImplicitConversion)
4026 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4027 From->getLocStart());
4028
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004029 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004030}
4031
Chandler Carruth8e172c62011-05-01 06:51:22 +00004032/// \brief Check the completeness of a type in a unary type trait.
4033///
4034/// If the particular type trait requires a complete type, tries to complete
4035/// it. If completing the type fails, a diagnostic is emitted and false
4036/// returned. If completing the type succeeds or no completion was required,
4037/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004038static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004039 SourceLocation Loc,
4040 QualType ArgTy) {
4041 // C++0x [meta.unary.prop]p3:
4042 // For all of the class templates X declared in this Clause, instantiating
4043 // that template with a template argument that is a class template
4044 // specialization may result in the implicit instantiation of the template
4045 // argument if and only if the semantics of X require that the argument
4046 // must be a complete type.
4047 // We apply this rule to all the type trait expressions used to implement
4048 // these class templates. We also try to follow any GCC documented behavior
4049 // in these expressions to ensure portability of standard libraries.
4050 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004051 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004052 // is_complete_type somewhat obviously cannot require a complete type.
4053 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004054 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004055
4056 // These traits are modeled on the type predicates in C++0x
4057 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4058 // requiring a complete type, as whether or not they return true cannot be
4059 // impacted by the completeness of the type.
4060 case UTT_IsVoid:
4061 case UTT_IsIntegral:
4062 case UTT_IsFloatingPoint:
4063 case UTT_IsArray:
4064 case UTT_IsPointer:
4065 case UTT_IsLvalueReference:
4066 case UTT_IsRvalueReference:
4067 case UTT_IsMemberFunctionPointer:
4068 case UTT_IsMemberObjectPointer:
4069 case UTT_IsEnum:
4070 case UTT_IsUnion:
4071 case UTT_IsClass:
4072 case UTT_IsFunction:
4073 case UTT_IsReference:
4074 case UTT_IsArithmetic:
4075 case UTT_IsFundamental:
4076 case UTT_IsObject:
4077 case UTT_IsScalar:
4078 case UTT_IsCompound:
4079 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004080 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004081
4082 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4083 // which requires some of its traits to have the complete type. However,
4084 // the completeness of the type cannot impact these traits' semantics, and
4085 // so they don't require it. This matches the comments on these traits in
4086 // Table 49.
4087 case UTT_IsConst:
4088 case UTT_IsVolatile:
4089 case UTT_IsSigned:
4090 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004091
4092 // This type trait always returns false, checking the type is moot.
4093 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004094 return true;
4095
David Majnemer213bea32015-11-16 06:58:51 +00004096 // C++14 [meta.unary.prop]:
4097 // If T is a non-union class type, T shall be a complete type.
4098 case UTT_IsEmpty:
4099 case UTT_IsPolymorphic:
4100 case UTT_IsAbstract:
4101 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4102 if (!RD->isUnion())
4103 return !S.RequireCompleteType(
4104 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4105 return true;
4106
4107 // C++14 [meta.unary.prop]:
4108 // If T is a class type, T shall be a complete type.
4109 case UTT_IsFinal:
4110 case UTT_IsSealed:
4111 if (ArgTy->getAsCXXRecordDecl())
4112 return !S.RequireCompleteType(
4113 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4114 return true;
4115
Richard Smithf03e9082017-06-01 00:28:16 +00004116 // C++1z [meta.unary.prop]:
4117 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004118 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004119 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004120 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004121 case UTT_IsStandardLayout:
4122 case UTT_IsPOD:
4123 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004124 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4125 // or an array of unknown bound. But GCC actually imposes the same constraints
4126 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004127 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004128 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004129 case UTT_HasNothrowConstructor:
4130 case UTT_HasNothrowCopy:
4131 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004132 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004133 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004134 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004135 case UTT_HasTrivialCopy:
4136 case UTT_HasTrivialDestructor:
4137 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004138 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4139 LLVM_FALLTHROUGH;
4140
4141 // C++1z [meta.unary.prop]:
4142 // T shall be a complete type, cv void, or an array of unknown bound.
4143 case UTT_IsDestructible:
4144 case UTT_IsNothrowDestructible:
4145 case UTT_IsTriviallyDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004146 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004147 return true;
4148
4149 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004150 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004151 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004152}
4153
Joao Matosc9523d42013-03-27 01:34:16 +00004154static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4155 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004156 bool (CXXRecordDecl::*HasTrivial)() const,
4157 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004158 bool (CXXMethodDecl::*IsDesiredOp)() const)
4159{
4160 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4161 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4162 return true;
4163
4164 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4165 DeclarationNameInfo NameInfo(Name, KeyLoc);
4166 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4167 if (Self.LookupQualifiedName(Res, RD)) {
4168 bool FoundOperator = false;
4169 Res.suppressDiagnostics();
4170 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4171 Op != OpEnd; ++Op) {
4172 if (isa<FunctionTemplateDecl>(*Op))
4173 continue;
4174
4175 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4176 if((Operator->*IsDesiredOp)()) {
4177 FoundOperator = true;
4178 const FunctionProtoType *CPT =
4179 Operator->getType()->getAs<FunctionProtoType>();
4180 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004181 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004182 return false;
4183 }
4184 }
4185 return FoundOperator;
4186 }
4187 return false;
4188}
4189
Alp Toker95e7ff22014-01-01 05:57:51 +00004190static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004191 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004192 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004193
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004194 ASTContext &C = Self.Context;
4195 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004196 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004197 // Type trait expressions corresponding to the primary type category
4198 // predicates in C++0x [meta.unary.cat].
4199 case UTT_IsVoid:
4200 return T->isVoidType();
4201 case UTT_IsIntegral:
4202 return T->isIntegralType(C);
4203 case UTT_IsFloatingPoint:
4204 return T->isFloatingType();
4205 case UTT_IsArray:
4206 return T->isArrayType();
4207 case UTT_IsPointer:
4208 return T->isPointerType();
4209 case UTT_IsLvalueReference:
4210 return T->isLValueReferenceType();
4211 case UTT_IsRvalueReference:
4212 return T->isRValueReferenceType();
4213 case UTT_IsMemberFunctionPointer:
4214 return T->isMemberFunctionPointerType();
4215 case UTT_IsMemberObjectPointer:
4216 return T->isMemberDataPointerType();
4217 case UTT_IsEnum:
4218 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004219 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004220 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004221 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004222 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004223 case UTT_IsFunction:
4224 return T->isFunctionType();
4225
4226 // Type trait expressions which correspond to the convenient composition
4227 // predicates in C++0x [meta.unary.comp].
4228 case UTT_IsReference:
4229 return T->isReferenceType();
4230 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004231 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004232 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004233 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004234 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004235 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004236 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004237 // Note: semantic analysis depends on Objective-C lifetime types to be
4238 // considered scalar types. However, such types do not actually behave
4239 // like scalar types at run time (since they may require retain/release
4240 // operations), so we report them as non-scalar.
4241 if (T->isObjCLifetimeType()) {
4242 switch (T.getObjCLifetime()) {
4243 case Qualifiers::OCL_None:
4244 case Qualifiers::OCL_ExplicitNone:
4245 return true;
4246
4247 case Qualifiers::OCL_Strong:
4248 case Qualifiers::OCL_Weak:
4249 case Qualifiers::OCL_Autoreleasing:
4250 return false;
4251 }
4252 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004253
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004254 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004255 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004256 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004257 case UTT_IsMemberPointer:
4258 return T->isMemberPointerType();
4259
4260 // Type trait expressions which correspond to the type property predicates
4261 // in C++0x [meta.unary.prop].
4262 case UTT_IsConst:
4263 return T.isConstQualified();
4264 case UTT_IsVolatile:
4265 return T.isVolatileQualified();
4266 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004267 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004268 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004269 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004270 case UTT_IsStandardLayout:
4271 return T->isStandardLayoutType();
4272 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004273 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004274 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004275 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004276 case UTT_IsEmpty:
4277 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4278 return !RD->isUnion() && RD->isEmpty();
4279 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004280 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004281 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004282 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004283 return false;
4284 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004285 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004286 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004287 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004288 case UTT_IsAggregate:
4289 // Report vector extensions and complex types as aggregates because they
4290 // support aggregate initialization. GCC mirrors this behavior for vectors
4291 // but not _Complex.
4292 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4293 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004294 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4295 // even then only when it is used with the 'interface struct ...' syntax
4296 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004297 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004298 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004299 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004300 case UTT_IsSealed:
4301 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004302 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004303 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004304 case UTT_IsSigned:
4305 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004306 case UTT_IsUnsigned:
4307 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004308
4309 // Type trait expressions which query classes regarding their construction,
4310 // destruction, and copying. Rather than being based directly on the
4311 // related type predicates in the standard, they are specified by both
4312 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4313 // specifications.
4314 //
4315 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4316 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004317 //
4318 // Note that these builtins do not behave as documented in g++: if a class
4319 // has both a trivial and a non-trivial special member of a particular kind,
4320 // they return false! For now, we emulate this behavior.
4321 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4322 // does not correctly compute triviality in the presence of multiple special
4323 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004324 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004325 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4326 // If __is_pod (type) is true then the trait is true, else if type is
4327 // a cv class or union type (or array thereof) with a trivial default
4328 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004329 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004330 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004331 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4332 return RD->hasTrivialDefaultConstructor() &&
4333 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004334 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004335 case UTT_HasTrivialMoveConstructor:
4336 // This trait is implemented by MSVC 2012 and needed to parse the
4337 // standard library headers. Specifically this is used as the logic
4338 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004339 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004340 return true;
4341 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4342 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4343 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004344 case UTT_HasTrivialCopy:
4345 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4346 // If __is_pod (type) is true or type is a reference type then
4347 // the trait is true, else if type is a cv class or union type
4348 // with a trivial copy constructor ([class.copy]) then the trait
4349 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004350 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004351 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004352 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4353 return RD->hasTrivialCopyConstructor() &&
4354 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004355 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004356 case UTT_HasTrivialMoveAssign:
4357 // This trait is implemented by MSVC 2012 and needed to parse the
4358 // standard library headers. Specifically it is used as the logic
4359 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004360 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004361 return true;
4362 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4363 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4364 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004365 case UTT_HasTrivialAssign:
4366 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4367 // If type is const qualified or is a reference type then the
4368 // trait is false. Otherwise if __is_pod (type) is true then the
4369 // trait is true, else if type is a cv class or union type with
4370 // a trivial copy assignment ([class.copy]) then the trait is
4371 // true, else it is false.
4372 // Note: the const and reference restrictions are interesting,
4373 // given that const and reference members don't prevent a class
4374 // from having a trivial copy assignment operator (but do cause
4375 // errors if the copy assignment operator is actually used, q.v.
4376 // [class.copy]p12).
4377
Richard Smith92f241f2012-12-08 02:53:02 +00004378 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004379 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004380 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004381 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004382 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4383 return RD->hasTrivialCopyAssignment() &&
4384 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004385 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004386 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004387 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004388 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004389 // C++14 [meta.unary.prop]:
4390 // For reference types, is_destructible<T>::value is true.
4391 if (T->isReferenceType())
4392 return true;
4393
4394 // Objective-C++ ARC: autorelease types don't require destruction.
4395 if (T->isObjCLifetimeType() &&
4396 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4397 return true;
4398
4399 // C++14 [meta.unary.prop]:
4400 // For incomplete types and function types, is_destructible<T>::value is
4401 // false.
4402 if (T->isIncompleteType() || T->isFunctionType())
4403 return false;
4404
Richard Smithf03e9082017-06-01 00:28:16 +00004405 // A type that requires destruction (via a non-trivial destructor or ARC
4406 // lifetime semantics) is not trivially-destructible.
4407 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4408 return false;
4409
David Majnemerac73de92015-08-11 03:03:28 +00004410 // C++14 [meta.unary.prop]:
4411 // For object types and given U equal to remove_all_extents_t<T>, if the
4412 // expression std::declval<U&>().~U() is well-formed when treated as an
4413 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4414 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4415 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4416 if (!Destructor)
4417 return false;
4418 // C++14 [dcl.fct.def.delete]p2:
4419 // A program that refers to a deleted function implicitly or
4420 // explicitly, other than to declare it, is ill-formed.
4421 if (Destructor->isDeleted())
4422 return false;
4423 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4424 return false;
4425 if (UTT == UTT_IsNothrowDestructible) {
4426 const FunctionProtoType *CPT =
4427 Destructor->getType()->getAs<FunctionProtoType>();
4428 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4429 if (!CPT || !CPT->isNothrow(C))
4430 return false;
4431 }
4432 }
4433 return true;
4434
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004435 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004436 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004437 // If __is_pod (type) is true or type is a reference type
4438 // then the trait is true, else if type is a cv class or union
4439 // type (or array thereof) with a trivial destructor
4440 // ([class.dtor]) then the trait is true, else it is
4441 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004442 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004443 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004444
John McCall31168b02011-06-15 23:02:42 +00004445 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004446 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004447 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4448 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004449
Richard Smith92f241f2012-12-08 02:53:02 +00004450 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4451 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004452 return false;
4453 // TODO: Propagate nothrowness for implicitly declared special members.
4454 case UTT_HasNothrowAssign:
4455 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4456 // If type is const qualified or is a reference type then the
4457 // trait is false. Otherwise if __has_trivial_assign (type)
4458 // is true then the trait is true, else if type is a cv class
4459 // or union type with copy assignment operators that are known
4460 // not to throw an exception then the trait is true, else it is
4461 // false.
4462 if (C.getBaseElementType(T).isConstQualified())
4463 return false;
4464 if (T->isReferenceType())
4465 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004466 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004467 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004468
Joao Matosc9523d42013-03-27 01:34:16 +00004469 if (const RecordType *RT = T->getAs<RecordType>())
4470 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4471 &CXXRecordDecl::hasTrivialCopyAssignment,
4472 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4473 &CXXMethodDecl::isCopyAssignmentOperator);
4474 return false;
4475 case UTT_HasNothrowMoveAssign:
4476 // This trait is implemented by MSVC 2012 and needed to parse the
4477 // standard library headers. Specifically this is used as the logic
4478 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004479 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004480 return true;
4481
4482 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4483 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4484 &CXXRecordDecl::hasTrivialMoveAssignment,
4485 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4486 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004487 return false;
4488 case UTT_HasNothrowCopy:
4489 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4490 // If __has_trivial_copy (type) is true then the trait is true, else
4491 // if type is a cv class or union type with copy constructors that are
4492 // known not to throw an exception then the trait is true, else it is
4493 // false.
John McCall31168b02011-06-15 23:02:42 +00004494 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004495 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004496 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4497 if (RD->hasTrivialCopyConstructor() &&
4498 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004499 return true;
4500
4501 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004502 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004503 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004504 // A template constructor is never a copy constructor.
4505 // FIXME: However, it may actually be selected at the actual overload
4506 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004507 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004508 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004509 // UsingDecl itself is not a constructor
4510 if (isa<UsingDecl>(ND))
4511 continue;
4512 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004513 if (Constructor->isCopyConstructor(FoundTQs)) {
4514 FoundConstructor = true;
4515 const FunctionProtoType *CPT
4516 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004517 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4518 if (!CPT)
4519 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004520 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004521 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004522 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004523 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004524 }
4525 }
4526
Richard Smith938f40b2011-06-11 17:19:42 +00004527 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004528 }
4529 return false;
4530 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004531 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004532 // If __has_trivial_constructor (type) is true then the trait is
4533 // true, else if type is a cv class or union type (or array
4534 // thereof) with a default constructor that is known not to
4535 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004536 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004537 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004538 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4539 if (RD->hasTrivialDefaultConstructor() &&
4540 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004541 return true;
4542
Alp Tokerb4bca412014-01-20 00:23:47 +00004543 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004544 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004545 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004546 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004547 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004548 // UsingDecl itself is not a constructor
4549 if (isa<UsingDecl>(ND))
4550 continue;
4551 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004552 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004553 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004554 const FunctionProtoType *CPT
4555 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004556 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4557 if (!CPT)
4558 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004559 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004560 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004561 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004562 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004563 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004564 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004565 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004566 }
4567 return false;
4568 case UTT_HasVirtualDestructor:
4569 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4570 // If type is a class type with a virtual destructor ([class.dtor])
4571 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004572 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004573 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004574 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004575 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004576
4577 // These type trait expressions are modeled on the specifications for the
4578 // Embarcadero C++0x type trait functions:
4579 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4580 case UTT_IsCompleteType:
4581 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4582 // Returns True if and only if T is a complete type at the point of the
4583 // function call.
4584 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004585 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004586}
Sebastian Redl5822f082009-02-07 20:10:22 +00004587
Alp Tokercbb90342013-12-13 20:49:58 +00004588static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4589 QualType RhsT, SourceLocation KeyLoc);
4590
Douglas Gregor29c42f22012-02-24 07:38:34 +00004591static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4592 ArrayRef<TypeSourceInfo *> Args,
4593 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004594 if (Kind <= UTT_Last)
4595 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4596
Alp Tokercbb90342013-12-13 20:49:58 +00004597 if (Kind <= BTT_Last)
4598 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4599 Args[1]->getType(), RParenLoc);
4600
Douglas Gregor29c42f22012-02-24 07:38:34 +00004601 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004602 case clang::TT_IsConstructible:
4603 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004604 case clang::TT_IsTriviallyConstructible: {
4605 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004606 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004607 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004608 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004609 // definition for is_constructible, as defined below, is known to call
4610 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004611 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004612 // The predicate condition for a template specialization
4613 // is_constructible<T, Args...> shall be satisfied if and only if the
4614 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004615 // variable t:
4616 //
4617 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004618 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004619
4620 // Precondition: T and all types in the parameter pack Args shall be
4621 // complete types, (possibly cv-qualified) void, or arrays of
4622 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004623 for (const auto *TSI : Args) {
4624 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004625 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004626 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004627
Simon Pilgrim75c26882016-09-30 14:25:09 +00004628 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004629 diag::err_incomplete_type_used_in_type_trait_expr))
4630 return false;
4631 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004632
David Majnemer9658ecc2015-11-13 05:32:43 +00004633 // Make sure the first argument is not incomplete nor a function type.
4634 QualType T = Args[0]->getType();
4635 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004636 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004637
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004638 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004639 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004640 if (RD && RD->isAbstract())
4641 return false;
4642
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004643 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4644 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004645 ArgExprs.reserve(Args.size() - 1);
4646 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004647 QualType ArgTy = Args[I]->getType();
4648 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4649 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004650 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004651 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4652 ArgTy.getNonLValueExprType(S.Context),
4653 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004654 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004655 for (Expr &E : OpaqueArgExprs)
4656 ArgExprs.push_back(&E);
4657
Simon Pilgrim75c26882016-09-30 14:25:09 +00004658 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004659 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004660 EnterExpressionEvaluationContext Unevaluated(
4661 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004662 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4663 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4664 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4665 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4666 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004667 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004668 if (Init.Failed())
4669 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004670
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004671 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004672 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4673 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004674
Alp Toker73287bf2014-01-20 00:24:09 +00004675 if (Kind == clang::TT_IsConstructible)
4676 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004677
Alp Toker73287bf2014-01-20 00:24:09 +00004678 if (Kind == clang::TT_IsNothrowConstructible)
4679 return S.canThrow(Result.get()) == CT_Cannot;
4680
4681 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004682 // Under Objective-C ARC and Weak, if the destination has non-trivial
4683 // Objective-C lifetime, this is a non-trivial construction.
4684 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004685 return false;
4686
4687 // The initialization succeeded; now make sure there are no non-trivial
4688 // calls.
4689 return !Result.get()->hasNonTrivialCall(S.Context);
4690 }
4691
4692 llvm_unreachable("unhandled type trait");
4693 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004694 }
Alp Tokercbb90342013-12-13 20:49:58 +00004695 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004696 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004697
Douglas Gregor29c42f22012-02-24 07:38:34 +00004698 return false;
4699}
4700
Simon Pilgrim75c26882016-09-30 14:25:09 +00004701ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4702 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004703 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004704 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004705
Alp Toker95e7ff22014-01-01 05:57:51 +00004706 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4707 *this, Kind, KWLoc, Args[0]->getType()))
4708 return ExprError();
4709
Douglas Gregor29c42f22012-02-24 07:38:34 +00004710 bool Dependent = false;
4711 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4712 if (Args[I]->getType()->isDependentType()) {
4713 Dependent = true;
4714 break;
4715 }
4716 }
Alp Tokercbb90342013-12-13 20:49:58 +00004717
4718 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004719 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004720 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4721
4722 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4723 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004724}
4725
Alp Toker88f64e62013-12-13 21:19:30 +00004726ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4727 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004728 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004729 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004730 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004731
Douglas Gregor29c42f22012-02-24 07:38:34 +00004732 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4733 TypeSourceInfo *TInfo;
4734 QualType T = GetTypeFromParser(Args[I], &TInfo);
4735 if (!TInfo)
4736 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004737
4738 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004739 }
Alp Tokercbb90342013-12-13 20:49:58 +00004740
Douglas Gregor29c42f22012-02-24 07:38:34 +00004741 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4742}
4743
Alp Tokercbb90342013-12-13 20:49:58 +00004744static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4745 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004746 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4747 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004748
4749 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004750 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004751 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004752 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004753 // Base and Derived are not unions and name the same class type without
4754 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004755
John McCall388ef532011-01-28 22:02:36 +00004756 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004757 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004758 if (!rhsRecord || !lhsRecord) {
4759 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4760 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4761 if (!LHSObjTy || !RHSObjTy)
4762 return false;
4763
4764 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4765 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4766 if (!BaseInterface || !DerivedInterface)
4767 return false;
4768
4769 if (Self.RequireCompleteType(
4770 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4771 return false;
4772
4773 return BaseInterface->isSuperClassOf(DerivedInterface);
4774 }
John McCall388ef532011-01-28 22:02:36 +00004775
4776 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4777 == (lhsRecord == rhsRecord));
4778
4779 if (lhsRecord == rhsRecord)
4780 return !lhsRecord->getDecl()->isUnion();
4781
4782 // C++0x [meta.rel]p2:
4783 // If Base and Derived are class types and are different types
4784 // (ignoring possible cv-qualifiers) then Derived shall be a
4785 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004786 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004787 diag::err_incomplete_type_used_in_type_trait_expr))
4788 return false;
4789
4790 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4791 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4792 }
John Wiegley65497cc2011-04-27 23:09:49 +00004793 case BTT_IsSame:
4794 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004795 case BTT_TypeCompatible:
4796 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4797 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004798 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004799 case BTT_IsConvertibleTo: {
4800 // C++0x [meta.rel]p4:
4801 // Given the following function prototype:
4802 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004803 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004804 // typename add_rvalue_reference<T>::type create();
4805 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004806 // the predicate condition for a template specialization
4807 // is_convertible<From, To> shall be satisfied if and only if
4808 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004809 // well-formed, including any implicit conversions to the return
4810 // type of the function:
4811 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004812 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004813 // return create<From>();
4814 // }
4815 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004816 // Access checking is performed as if in a context unrelated to To and
4817 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004818 // of the return-statement (including conversions to the return type)
4819 // is considered.
4820 //
4821 // We model the initialization as a copy-initialization of a temporary
4822 // of the appropriate type, which for this expression is identical to the
4823 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004824
4825 // Functions aren't allowed to return function or array types.
4826 if (RhsT->isFunctionType() || RhsT->isArrayType())
4827 return false;
4828
4829 // A return statement in a void function must have void type.
4830 if (RhsT->isVoidType())
4831 return LhsT->isVoidType();
4832
4833 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004834 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004835 return false;
4836
4837 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004838 if (LhsT->isObjectType() || LhsT->isFunctionType())
4839 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004840
4841 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004842 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004843 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004844 Expr::getValueKindForType(LhsT));
4845 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004846 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004847 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004848
4849 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004850 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004851 EnterExpressionEvaluationContext Unevaluated(
4852 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004853 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4854 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004855 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004856 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004857 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004858
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004859 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004860 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4861 }
Alp Toker73287bf2014-01-20 00:24:09 +00004862
David Majnemerb3d96882016-05-23 17:21:55 +00004863 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004864 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004865 case BTT_IsTriviallyAssignable: {
4866 // C++11 [meta.unary.prop]p3:
4867 // is_trivially_assignable is defined as:
4868 // is_assignable<T, U>::value is true and the assignment, as defined by
4869 // is_assignable, is known to call no operation that is not trivial
4870 //
4871 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004872 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004873 // treated as an unevaluated operand (Clause 5).
4874 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004875 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004876 // void, or arrays of unknown bound.
4877 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004878 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004879 diag::err_incomplete_type_used_in_type_trait_expr))
4880 return false;
4881 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004882 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004883 diag::err_incomplete_type_used_in_type_trait_expr))
4884 return false;
4885
4886 // cv void is never assignable.
4887 if (LhsT->isVoidType() || RhsT->isVoidType())
4888 return false;
4889
Simon Pilgrim75c26882016-09-30 14:25:09 +00004890 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004891 // declval<U>().
4892 if (LhsT->isObjectType() || LhsT->isFunctionType())
4893 LhsT = Self.Context.getRValueReferenceType(LhsT);
4894 if (RhsT->isObjectType() || RhsT->isFunctionType())
4895 RhsT = Self.Context.getRValueReferenceType(RhsT);
4896 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4897 Expr::getValueKindForType(LhsT));
4898 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4899 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004900
4901 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004902 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004903 EnterExpressionEvaluationContext Unevaluated(
4904 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004905 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4906 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004907 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4908 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004909 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4910 return false;
4911
David Majnemerb3d96882016-05-23 17:21:55 +00004912 if (BTT == BTT_IsAssignable)
4913 return true;
4914
Alp Toker73287bf2014-01-20 00:24:09 +00004915 if (BTT == BTT_IsNothrowAssignable)
4916 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004917
Alp Toker73287bf2014-01-20 00:24:09 +00004918 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004919 // Under Objective-C ARC and Weak, if the destination has non-trivial
4920 // Objective-C lifetime, this is a non-trivial assignment.
4921 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004922 return false;
4923
4924 return !Result.get()->hasNonTrivialCall(Self.Context);
4925 }
4926
4927 llvm_unreachable("unhandled type trait");
4928 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004929 }
Alp Tokercbb90342013-12-13 20:49:58 +00004930 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004931 }
4932 llvm_unreachable("Unknown type trait or not implemented");
4933}
4934
John Wiegley6242b6a2011-04-28 00:16:57 +00004935ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4936 SourceLocation KWLoc,
4937 ParsedType Ty,
4938 Expr* DimExpr,
4939 SourceLocation RParen) {
4940 TypeSourceInfo *TSInfo;
4941 QualType T = GetTypeFromParser(Ty, &TSInfo);
4942 if (!TSInfo)
4943 TSInfo = Context.getTrivialTypeSourceInfo(T);
4944
4945 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4946}
4947
4948static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4949 QualType T, Expr *DimExpr,
4950 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004951 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004952
4953 switch(ATT) {
4954 case ATT_ArrayRank:
4955 if (T->isArrayType()) {
4956 unsigned Dim = 0;
4957 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4958 ++Dim;
4959 T = AT->getElementType();
4960 }
4961 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004962 }
John Wiegleyd3522222011-04-28 02:06:46 +00004963 return 0;
4964
John Wiegley6242b6a2011-04-28 00:16:57 +00004965 case ATT_ArrayExtent: {
4966 llvm::APSInt Value;
4967 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004968 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004969 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004970 false).isInvalid())
4971 return 0;
4972 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004973 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4974 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004975 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004976 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004977 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004978
4979 if (T->isArrayType()) {
4980 unsigned D = 0;
4981 bool Matched = false;
4982 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4983 if (Dim == D) {
4984 Matched = true;
4985 break;
4986 }
4987 ++D;
4988 T = AT->getElementType();
4989 }
4990
John Wiegleyd3522222011-04-28 02:06:46 +00004991 if (Matched && T->isArrayType()) {
4992 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4993 return CAT->getSize().getLimitedValue();
4994 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004995 }
John Wiegleyd3522222011-04-28 02:06:46 +00004996 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004997 }
4998 }
4999 llvm_unreachable("Unknown type trait or not implemented");
5000}
5001
5002ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5003 SourceLocation KWLoc,
5004 TypeSourceInfo *TSInfo,
5005 Expr* DimExpr,
5006 SourceLocation RParen) {
5007 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005008
Chandler Carruthc5276e52011-05-01 08:48:21 +00005009 // FIXME: This should likely be tracked as an APInt to remove any host
5010 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005011 uint64_t Value = 0;
5012 if (!T->isDependentType())
5013 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5014
Chandler Carruthc5276e52011-05-01 08:48:21 +00005015 // While the specification for these traits from the Embarcadero C++
5016 // compiler's documentation says the return type is 'unsigned int', Clang
5017 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5018 // compiler, there is no difference. On several other platforms this is an
5019 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005020 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5021 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005022}
5023
John Wiegleyf9f65842011-04-25 06:54:41 +00005024ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005025 SourceLocation KWLoc,
5026 Expr *Queried,
5027 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005028 // If error parsing the expression, ignore.
5029 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005030 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005031
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005032 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005033
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005034 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005035}
5036
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005037static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5038 switch (ET) {
5039 case ET_IsLValueExpr: return E->isLValue();
5040 case ET_IsRValueExpr: return E->isRValue();
5041 }
5042 llvm_unreachable("Expression trait not covered by switch");
5043}
5044
John Wiegleyf9f65842011-04-25 06:54:41 +00005045ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005046 SourceLocation KWLoc,
5047 Expr *Queried,
5048 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005049 if (Queried->isTypeDependent()) {
5050 // Delay type-checking for type-dependent expressions.
5051 } else if (Queried->getType()->isPlaceholderType()) {
5052 ExprResult PE = CheckPlaceholderExpr(Queried);
5053 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005054 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005055 }
5056
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005057 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005058
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005059 return new (Context)
5060 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005061}
5062
Richard Trieu82402a02011-09-15 21:56:47 +00005063QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005064 ExprValueKind &VK,
5065 SourceLocation Loc,
5066 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005067 assert(!LHS.get()->getType()->isPlaceholderType() &&
5068 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005069 "placeholders should have been weeded out by now");
5070
Richard Smith4baaa5a2016-12-03 01:14:32 +00005071 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5072 // temporary materialization conversion otherwise.
5073 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005074 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005075 else if (LHS.get()->isRValue())
5076 LHS = TemporaryMaterializationConversion(LHS.get());
5077 if (LHS.isInvalid())
5078 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005079
5080 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005081 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005082 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005083
Sebastian Redl5822f082009-02-07 20:10:22 +00005084 const char *OpSpelling = isIndirect ? "->*" : ".*";
5085 // C++ 5.5p2
5086 // The binary operator .* [p3: ->*] binds its second operand, which shall
5087 // be of type "pointer to member of T" (where T is a completely-defined
5088 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005089 QualType RHSType = RHS.get()->getType();
5090 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005091 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005092 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005093 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005094 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005095 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005096
Sebastian Redl5822f082009-02-07 20:10:22 +00005097 QualType Class(MemPtr->getClass(), 0);
5098
Douglas Gregord07ba342010-10-13 20:41:14 +00005099 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5100 // member pointer points must be completely-defined. However, there is no
5101 // reason for this semantic distinction, and the rule is not enforced by
5102 // other compilers. Therefore, we do not check this property, as it is
5103 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005104
Sebastian Redl5822f082009-02-07 20:10:22 +00005105 // C++ 5.5p2
5106 // [...] to its first operand, which shall be of class T or of a class of
5107 // which T is an unambiguous and accessible base class. [p3: a pointer to
5108 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005109 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005110 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005111 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5112 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005113 else {
5114 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005115 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005116 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005117 return QualType();
5118 }
5119 }
5120
Richard Trieu82402a02011-09-15 21:56:47 +00005121 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005122 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005123 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5124 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005125 return QualType();
5126 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005127
Richard Smith0f59cb32015-12-18 21:45:41 +00005128 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005129 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005130 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005131 return QualType();
5132 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005133
5134 CXXCastPath BasePath;
5135 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5136 SourceRange(LHS.get()->getLocStart(),
5137 RHS.get()->getLocEnd()),
5138 &BasePath))
5139 return QualType();
5140
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005141 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005142 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5143 if (isIndirect)
5144 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005145 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005146 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005147 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005148 }
5149
Richard Trieu82402a02011-09-15 21:56:47 +00005150 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005151 // Diagnose use of pointer-to-member type which when used as
5152 // the functional cast in a pointer-to-member expression.
5153 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5154 return QualType();
5155 }
John McCall7decc9e2010-11-18 06:31:45 +00005156
Sebastian Redl5822f082009-02-07 20:10:22 +00005157 // C++ 5.5p2
5158 // The result is an object or a function of the type specified by the
5159 // second operand.
5160 // The cv qualifiers are the union of those in the pointer and the left side,
5161 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005162 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005163 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005164
Douglas Gregor1d042092011-01-26 16:40:18 +00005165 // C++0x [expr.mptr.oper]p6:
5166 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167 // ill-formed if the second operand is a pointer to member function with
5168 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5169 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005170 // is a pointer to member function with ref-qualifier &&.
5171 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5172 switch (Proto->getRefQualifier()) {
5173 case RQ_None:
5174 // Do nothing
5175 break;
5176
5177 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005178 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5179 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5180 if (Proto->isConst())
5181 Diag(Loc, getLangOpts().CPlusPlus2a
5182 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5183 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5184 else
5185 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5186 << RHSType << 1 << LHS.get()->getSourceRange();
5187 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005188 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Douglas Gregor1d042092011-01-26 16:40:18 +00005190 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005191 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005192 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005193 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005194 break;
5195 }
5196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
John McCall7decc9e2010-11-18 06:31:45 +00005198 // C++ [expr.mptr.oper]p6:
5199 // The result of a .* expression whose second operand is a pointer
5200 // to a data member is of the same value category as its
5201 // first operand. The result of a .* expression whose second
5202 // operand is a pointer to a member function is a prvalue. The
5203 // result of an ->* expression is an lvalue if its second operand
5204 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005205 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005206 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005207 return Context.BoundMemberTy;
5208 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005209 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005210 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005211 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005212 }
John McCall7decc9e2010-11-18 06:31:45 +00005213
Sebastian Redl5822f082009-02-07 20:10:22 +00005214 return Result;
5215}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005216
Richard Smith2414bca2016-04-25 19:30:37 +00005217/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005218///
5219/// This is part of the parameter validation for the ? operator. If either
5220/// value operand is a class type, the two operands are attempted to be
5221/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005222/// It returns true if the program is ill-formed and has already been diagnosed
5223/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005224static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5225 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005226 bool &HaveConversion,
5227 QualType &ToType) {
5228 HaveConversion = false;
5229 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
5231 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005232 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005233 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005234 // The process for determining whether an operand expression E1 of type T1
5235 // can be converted to match an operand expression E2 of type T2 is defined
5236 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005237 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5238 // implicitly converted to type "lvalue reference to T2", subject to the
5239 // constraint that in the conversion the reference must bind directly to
5240 // an lvalue.
5241 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5242 // implicitly conveted to the type "rvalue reference to R2", subject to
5243 // the constraint that the reference must bind directly.
5244 if (To->isLValue() || To->isXValue()) {
5245 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5246 : Self.Context.getRValueReferenceType(ToType);
5247
Douglas Gregor838fcc32010-03-26 20:14:36 +00005248 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005250 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005251 if (InitSeq.isDirectReferenceBinding()) {
5252 ToType = T;
5253 HaveConversion = true;
5254 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005256
Douglas Gregor838fcc32010-03-26 20:14:36 +00005257 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005258 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005259 }
John McCall65eb8792010-02-25 01:37:24 +00005260
Sebastian Redl1a99f442009-04-16 17:51:27 +00005261 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5262 // -- if E1 and E2 have class type, and the underlying class types are
5263 // the same or one is a base class of the other:
5264 QualType FTy = From->getType();
5265 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005266 const RecordType *FRec = FTy->getAs<RecordType>();
5267 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005268 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005269 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5270 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5271 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005272 // E1 can be converted to match E2 if the class of T2 is the
5273 // same type as, or a base class of, the class of T1, and
5274 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005275 if (FRec == TRec || FDerivedFromT) {
5276 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005277 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005278 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005279 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005280 HaveConversion = true;
5281 return false;
5282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283
Douglas Gregor838fcc32010-03-26 20:14:36 +00005284 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005285 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005286 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005288
Douglas Gregor838fcc32010-03-26 20:14:36 +00005289 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291
Douglas Gregor838fcc32010-03-26 20:14:36 +00005292 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5293 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005294 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005295 // an rvalue).
5296 //
5297 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5298 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005299 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005300
Douglas Gregor838fcc32010-03-26 20:14:36 +00005301 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005302 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005303 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005304 ToType = TTy;
5305 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005306 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005307
Sebastian Redl1a99f442009-04-16 17:51:27 +00005308 return false;
5309}
5310
5311/// \brief Try to find a common type for two according to C++0x 5.16p5.
5312///
5313/// This is part of the parameter validation for the ? operator. If either
5314/// value operand is a class type, overload resolution is used to find a
5315/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005316static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005317 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005318 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005319 OverloadCandidateSet CandidateSet(QuestionLoc,
5320 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005321 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005322 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005323
5324 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005325 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005326 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005328 ExprResult LHSRes = Self.PerformImplicitConversion(
5329 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5330 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005331 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005332 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005333 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005334
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005335 ExprResult RHSRes = Self.PerformImplicitConversion(
5336 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5337 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005338 if (RHSRes.isInvalid())
5339 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005340 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005341 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005342 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005343 return false;
John Wiegley01296292011-04-08 18:41:53 +00005344 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005345
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005346 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005347
5348 // Emit a better diagnostic if one of the expressions is a null pointer
5349 // constant and the other is a pointer type. In this case, the user most
5350 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005351 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005352 return true;
5353
5354 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005355 << LHS.get()->getType() << RHS.get()->getType()
5356 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005357 return true;
5358
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005359 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005360 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005361 << LHS.get()->getType() << RHS.get()->getType()
5362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005363 // FIXME: Print the possible common types by printing the return types of
5364 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005365 break;
5366
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005367 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005368 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005369 }
5370 return true;
5371}
5372
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005373/// \brief Perform an "extended" implicit conversion as returned by
5374/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005375static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005376 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005377 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005378 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005379 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005380 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005381 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005382 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005383 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
John Wiegley01296292011-04-08 18:41:53 +00005385 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005386 return false;
5387}
5388
Sebastian Redl1a99f442009-04-16 17:51:27 +00005389/// \brief Check the operands of ?: under C++ semantics.
5390///
5391/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5392/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005393QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5394 ExprResult &RHS, ExprValueKind &VK,
5395 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005396 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005397 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5398 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005399
Richard Smith45edb702012-08-07 22:06:48 +00005400 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005401 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005402 //
5403 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5404 // a is that of a integer vector with the same number of elements and
5405 // size as the vectors of b and c. If one of either b or c is a scalar
5406 // it is implicitly converted to match the type of the vector.
5407 // Otherwise the expression is ill-formed. If both b and c are scalars,
5408 // then b and c are checked and converted to the type of a if possible.
5409 // Unlike the OpenCL ?: operator, the expression is evaluated as
5410 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005411 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005412 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005413 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005414 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005415 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005416 }
5417
John McCall7decc9e2010-11-18 06:31:45 +00005418 // Assume r-value.
5419 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005420 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005421
Sebastian Redl1a99f442009-04-16 17:51:27 +00005422 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005423 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005424 return Context.DependentTy;
5425
Richard Smith45edb702012-08-07 22:06:48 +00005426 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005427 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005428 QualType LTy = LHS.get()->getType();
5429 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005430 bool LVoid = LTy->isVoidType();
5431 bool RVoid = RTy->isVoidType();
5432 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005433 // ... one of the following shall hold:
5434 // -- The second or the third operand (but not both) is a (possibly
5435 // parenthesized) throw-expression; the result is of the type
5436 // and value category of the other.
5437 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5438 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5439 if (LThrow != RThrow) {
5440 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5441 VK = NonThrow->getValueKind();
5442 // DR (no number yet): the result is a bit-field if the
5443 // non-throw-expression operand is a bit-field.
5444 OK = NonThrow->getObjectKind();
5445 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005446 }
5447
Sebastian Redl1a99f442009-04-16 17:51:27 +00005448 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005449 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005450 if (LVoid && RVoid)
5451 return Context.VoidTy;
5452
5453 // Neither holds, error.
5454 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5455 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005456 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005457 return QualType();
5458 }
5459
5460 // Neither is void.
5461
Richard Smithf2b084f2012-08-08 06:13:49 +00005462 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005463 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005464 // either has (cv) class type [...] an attempt is made to convert each of
5465 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005466 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005467 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005468 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005469 QualType L2RType, R2LType;
5470 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005471 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005472 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005473 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005474 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Sebastian Redl1a99f442009-04-16 17:51:27 +00005476 // If both can be converted, [...] the program is ill-formed.
5477 if (HaveL2R && HaveR2L) {
5478 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005479 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005480 return QualType();
5481 }
5482
5483 // If exactly one conversion is possible, that conversion is applied to
5484 // the chosen operand and the converted operands are used in place of the
5485 // original operands for the remainder of this section.
5486 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005487 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005488 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005489 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005490 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005491 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005492 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005493 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005494 }
5495 }
5496
Richard Smithf2b084f2012-08-08 06:13:49 +00005497 // C++11 [expr.cond]p3
5498 // if both are glvalues of the same value category and the same type except
5499 // for cv-qualification, an attempt is made to convert each of those
5500 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005501 // FIXME:
5502 // Resolving a defect in P0012R1: we extend this to cover all cases where
5503 // one of the operands is reference-compatible with the other, in order
5504 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005505 ExprValueKind LVK = LHS.get()->getValueKind();
5506 ExprValueKind RVK = RHS.get()->getValueKind();
5507 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005508 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005509 // DerivedToBase was already handled by the class-specific case above.
5510 // FIXME: Should we allow ObjC conversions here?
5511 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5512 if (CompareReferenceRelationship(
5513 QuestionLoc, LTy, RTy, DerivedToBase,
5514 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005515 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5516 // [...] subject to the constraint that the reference must bind
5517 // directly [...]
5518 !RHS.get()->refersToBitField() &&
5519 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005520 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005521 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005522 } else if (CompareReferenceRelationship(
5523 QuestionLoc, RTy, LTy, DerivedToBase,
5524 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005525 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5526 !LHS.get()->refersToBitField() &&
5527 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005528 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5529 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005530 }
5531 }
5532
5533 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005534 // If the second and third operands are glvalues of the same value
5535 // category and have the same type, the result is of that type and
5536 // value category and it is a bit-field if the second or the third
5537 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005538 // We only extend this to bitfields, not to the crazy other kinds of
5539 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005540 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005541 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005542 LHS.get()->isOrdinaryOrBitFieldObject() &&
5543 RHS.get()->isOrdinaryOrBitFieldObject()) {
5544 VK = LHS.get()->getValueKind();
5545 if (LHS.get()->getObjectKind() == OK_BitField ||
5546 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005547 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005548
5549 // If we have function pointer types, unify them anyway to unify their
5550 // exception specifications, if any.
5551 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5552 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005553 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005554 /*ConvertArgs*/false);
5555 LTy = Context.getQualifiedType(LTy, Qs);
5556
5557 assert(!LTy.isNull() && "failed to find composite pointer type for "
5558 "canonically equivalent function ptr types");
5559 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5560 }
5561
John McCall7decc9e2010-11-18 06:31:45 +00005562 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005563 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005564
Richard Smithf2b084f2012-08-08 06:13:49 +00005565 // C++11 [expr.cond]p5
5566 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005567 // do not have the same type, and either has (cv) class type, ...
5568 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5569 // ... overload resolution is used to determine the conversions (if any)
5570 // to be applied to the operands. If the overload resolution fails, the
5571 // program is ill-formed.
5572 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5573 return QualType();
5574 }
5575
Richard Smithf2b084f2012-08-08 06:13:49 +00005576 // C++11 [expr.cond]p6
5577 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005578 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005579 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5580 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005581 if (LHS.isInvalid() || RHS.isInvalid())
5582 return QualType();
5583 LTy = LHS.get()->getType();
5584 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005585
5586 // After those conversions, one of the following shall hold:
5587 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005588 // is of that type. If the operands have class type, the result
5589 // is a prvalue temporary of the result type, which is
5590 // copy-initialized from either the second operand or the third
5591 // operand depending on the value of the first operand.
5592 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5593 if (LTy->isRecordType()) {
5594 // The operands have class type. Make a temporary copy.
5595 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005596
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005597 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5598 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005599 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005600 if (LHSCopy.isInvalid())
5601 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005602
5603 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5604 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005605 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005606 if (RHSCopy.isInvalid())
5607 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
John Wiegley01296292011-04-08 18:41:53 +00005609 LHS = LHSCopy;
5610 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005611 }
5612
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005613 // If we have function pointer types, unify them anyway to unify their
5614 // exception specifications, if any.
5615 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5616 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5617 assert(!LTy.isNull() && "failed to find composite pointer type for "
5618 "canonically equivalent function ptr types");
5619 }
5620
Sebastian Redl1a99f442009-04-16 17:51:27 +00005621 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005622 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005623
Douglas Gregor46188682010-05-18 22:42:18 +00005624 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005626 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5627 /*AllowBothBool*/true,
5628 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005629
Sebastian Redl1a99f442009-04-16 17:51:27 +00005630 // -- The second and third operands have arithmetic or enumeration type;
5631 // the usual arithmetic conversions are performed to bring them to a
5632 // common type, and the result is of that type.
5633 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005634 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005635 if (LHS.isInvalid() || RHS.isInvalid())
5636 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005637 if (ResTy.isNull()) {
5638 Diag(QuestionLoc,
5639 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5640 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5641 return QualType();
5642 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005643
5644 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5645 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5646
5647 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005648 }
5649
5650 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005651 // type and the other is a null pointer constant, or both are null
5652 // pointer constants, at least one of which is non-integral; pointer
5653 // conversions and qualification conversions are performed to bring them
5654 // to their composite pointer type. The result is of the composite
5655 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005656 // -- The second and third operands have pointer to member type, or one has
5657 // pointer to member type and the other is a null pointer constant;
5658 // pointer to member conversions and qualification conversions are
5659 // performed to bring them to a common type, whose cv-qualification
5660 // shall match the cv-qualification of either the second or the third
5661 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005662 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5663 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005664 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665
Douglas Gregor697a3912010-04-01 22:47:07 +00005666 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005667 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5668 if (!Composite.isNull())
5669 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005670
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005671 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005672 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005673 return QualType();
5674
Sebastian Redl1a99f442009-04-16 17:51:27 +00005675 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005676 << LHS.get()->getType() << RHS.get()->getType()
5677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005678 return QualType();
5679}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005680
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005681static FunctionProtoType::ExceptionSpecInfo
5682mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5683 FunctionProtoType::ExceptionSpecInfo ESI2,
5684 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5685 ExceptionSpecificationType EST1 = ESI1.Type;
5686 ExceptionSpecificationType EST2 = ESI2.Type;
5687
5688 // If either of them can throw anything, that is the result.
5689 if (EST1 == EST_None) return ESI1;
5690 if (EST2 == EST_None) return ESI2;
5691 if (EST1 == EST_MSAny) return ESI1;
5692 if (EST2 == EST_MSAny) return ESI2;
5693
5694 // If either of them is non-throwing, the result is the other.
5695 if (EST1 == EST_DynamicNone) return ESI2;
5696 if (EST2 == EST_DynamicNone) return ESI1;
5697 if (EST1 == EST_BasicNoexcept) return ESI2;
5698 if (EST2 == EST_BasicNoexcept) return ESI1;
5699
5700 // If either of them is a non-value-dependent computed noexcept, that
5701 // determines the result.
5702 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5703 !ESI2.NoexceptExpr->isValueDependent())
5704 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5705 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5706 !ESI1.NoexceptExpr->isValueDependent())
5707 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5708 // If we're left with value-dependent computed noexcept expressions, we're
5709 // stuck. Before C++17, we can just drop the exception specification entirely,
5710 // since it's not actually part of the canonical type. And this should never
5711 // happen in C++17, because it would mean we were computing the composite
5712 // pointer type of dependent types, which should never happen.
5713 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5714 assert(!S.getLangOpts().CPlusPlus1z &&
5715 "computing composite pointer type of dependent types");
5716 return FunctionProtoType::ExceptionSpecInfo();
5717 }
5718
5719 // Switch over the possibilities so that people adding new values know to
5720 // update this function.
5721 switch (EST1) {
5722 case EST_None:
5723 case EST_DynamicNone:
5724 case EST_MSAny:
5725 case EST_BasicNoexcept:
5726 case EST_ComputedNoexcept:
5727 llvm_unreachable("handled above");
5728
5729 case EST_Dynamic: {
5730 // This is the fun case: both exception specifications are dynamic. Form
5731 // the union of the two lists.
5732 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5733 llvm::SmallPtrSet<QualType, 8> Found;
5734 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5735 for (QualType E : Exceptions)
5736 if (Found.insert(S.Context.getCanonicalType(E)).second)
5737 ExceptionTypeStorage.push_back(E);
5738
5739 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5740 Result.Exceptions = ExceptionTypeStorage;
5741 return Result;
5742 }
5743
5744 case EST_Unevaluated:
5745 case EST_Uninstantiated:
5746 case EST_Unparsed:
5747 llvm_unreachable("shouldn't see unresolved exception specifications here");
5748 }
5749
5750 llvm_unreachable("invalid ExceptionSpecificationType");
5751}
5752
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005753/// \brief Find a merged pointer type and convert the two expressions to it.
5754///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005755/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005756/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005757/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005758/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005759///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005760/// \param Loc The location of the operator requiring these two expressions to
5761/// be converted to the composite pointer type.
5762///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005763/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005765 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005766 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005767 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005768
5769 // C++1z [expr]p14:
5770 // The composite pointer type of two operands p1 and p2 having types T1
5771 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005772 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005773
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005774 // where at least one is a pointer or pointer to member type or
5775 // std::nullptr_t is:
5776 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5777 T1->isNullPtrType();
5778 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5779 T2->isNullPtrType();
5780 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005781 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005782
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005783 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5784 // This can't actually happen, following the standard, but we also use this
5785 // to implement the end of [expr.conv], which hits this case.
5786 //
5787 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5788 if (T1IsPointerLike &&
5789 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005790 if (ConvertArgs)
5791 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5792 ? CK_NullToMemberPointer
5793 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005794 return T1;
5795 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005796 if (T2IsPointerLike &&
5797 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005798 if (ConvertArgs)
5799 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5800 ? CK_NullToMemberPointer
5801 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005802 return T2;
5803 }
Mike Stump11289f42009-09-09 15:08:12 +00005804
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005805 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005806 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005807 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005808 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5809 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005810
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005811 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5812 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5813 // the union of cv1 and cv2;
5814 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5815 // "pointer to function", where the function types are otherwise the same,
5816 // "pointer to function";
5817 // FIXME: This rule is defective: it should also permit removing noexcept
5818 // from a pointer to member function. As a Clang extension, we also
5819 // permit removing 'noreturn', so we generalize this rule to;
5820 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5821 // "pointer to member function" and the pointee types can be unified
5822 // by a function pointer conversion, that conversion is applied
5823 // before checking the following rules.
5824 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5825 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5826 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5827 // respectively;
5828 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5829 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5830 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5831 // T1 or the cv-combined type of T1 and T2, respectively;
5832 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5833 // T2;
5834 //
5835 // If looked at in the right way, these bullets all do the same thing.
5836 // What we do here is, we build the two possible cv-combined types, and try
5837 // the conversions in both directions. If only one works, or if the two
5838 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005839 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005840 //
5841 // Note that this will fail to find a composite pointer type for "pointer
5842 // to void" and "pointer to function". We can't actually perform the final
5843 // conversion in this case, even though a composite pointer type formally
5844 // exists.
5845 SmallVector<unsigned, 4> QualifierUnion;
5846 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005847 QualType Composite1 = T1;
5848 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005849 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005850 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005851 const PointerType *Ptr1, *Ptr2;
5852 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5853 (Ptr2 = Composite2->getAs<PointerType>())) {
5854 Composite1 = Ptr1->getPointeeType();
5855 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005856
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005857 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005858 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005859 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005860 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005861
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005862 QualifierUnion.push_back(
5863 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005864 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005865 continue;
5866 }
Mike Stump11289f42009-09-09 15:08:12 +00005867
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005868 const MemberPointerType *MemPtr1, *MemPtr2;
5869 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5870 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5871 Composite1 = MemPtr1->getPointeeType();
5872 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005874 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005875 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005876 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005877 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005879 QualifierUnion.push_back(
5880 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5881 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5882 MemPtr2->getClass()));
5883 continue;
5884 }
Mike Stump11289f42009-09-09 15:08:12 +00005885
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005886 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005887
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005888 // Cannot unwrap any more types.
5889 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005890 }
Mike Stump11289f42009-09-09 15:08:12 +00005891
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005892 // Apply the function pointer conversion to unify the types. We've already
5893 // unwrapped down to the function types, and we want to merge rather than
5894 // just convert, so do this ourselves rather than calling
5895 // IsFunctionConversion.
5896 //
5897 // FIXME: In order to match the standard wording as closely as possible, we
5898 // currently only do this under a single level of pointers. Ideally, we would
5899 // allow this in general, and set NeedConstBefore to the relevant depth on
5900 // the side(s) where we changed anything.
5901 if (QualifierUnion.size() == 1) {
5902 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5903 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5904 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5905 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5906
5907 // The result is noreturn if both operands are.
5908 bool Noreturn =
5909 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5910 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5911 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5912
5913 // The result is nothrow if both operands are.
5914 SmallVector<QualType, 8> ExceptionTypeStorage;
5915 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5916 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5917 ExceptionTypeStorage);
5918
5919 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5920 FPT1->getParamTypes(), EPI1);
5921 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5922 FPT2->getParamTypes(), EPI2);
5923 }
5924 }
5925 }
5926
Richard Smith5e9746f2016-10-21 22:00:42 +00005927 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005928 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005930 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005931 for (unsigned I = 0; I != NeedConstBefore; ++I)
5932 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005933 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005936 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005937 auto MOC = MemberOfClass.rbegin();
5938 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5939 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5940 auto Classes = *MOC++;
5941 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005942 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005943 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005944 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005945 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005946 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005947 } else {
5948 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005949 Composite1 =
5950 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5951 Composite2 =
5952 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005953 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005954 }
5955
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005956 struct Conversion {
5957 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005958 Expr *&E1, *&E2;
5959 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005960 InitializedEntity Entity;
5961 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005962 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005963 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005964
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005965 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5966 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005967 : S(S), E1(E1), E2(E2), Composite(Composite),
5968 Entity(InitializedEntity::InitializeTemporary(Composite)),
5969 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5970 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5971 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005972
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005973 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005974 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5975 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005976 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005977 E1 = E1Result.getAs<Expr>();
5978
5979 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5980 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005981 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005982 E2 = E2Result.getAs<Expr>();
5983
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005984 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005985 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005986 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005987
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005988 // Try to convert to each composite pointer type.
5989 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005990 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5991 if (ConvertArgs && C1.perform())
5992 return QualType();
5993 return C1.Composite;
5994 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005995 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005996
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005997 if (C1.Viable == C2.Viable) {
5998 // Either Composite1 and Composite2 are viable and are different, or
5999 // neither is viable.
6000 // FIXME: How both be viable and different?
6001 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006002 }
6003
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006004 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006005 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6006 return QualType();
6007
6008 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006009}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006010
John McCalldadc5752010-08-24 06:29:42 +00006011ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006012 if (!E)
6013 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006014
John McCall31168b02011-06-15 23:02:42 +00006015 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6016
6017 // If the result is a glvalue, we shouldn't bind it.
6018 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006019 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006020
John McCall31168b02011-06-15 23:02:42 +00006021 // In ARC, calls that return a retainable type can return retained,
6022 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006023 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006024 E->getType()->isObjCRetainableType()) {
6025
6026 bool ReturnsRetained;
6027
6028 // For actual calls, we compute this by examining the type of the
6029 // called value.
6030 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6031 Expr *Callee = Call->getCallee()->IgnoreParens();
6032 QualType T = Callee->getType();
6033
6034 if (T == Context.BoundMemberTy) {
6035 // Handle pointer-to-members.
6036 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6037 T = BinOp->getRHS()->getType();
6038 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6039 T = Mem->getMemberDecl()->getType();
6040 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006041
John McCall31168b02011-06-15 23:02:42 +00006042 if (const PointerType *Ptr = T->getAs<PointerType>())
6043 T = Ptr->getPointeeType();
6044 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6045 T = Ptr->getPointeeType();
6046 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6047 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006048
John McCall31168b02011-06-15 23:02:42 +00006049 const FunctionType *FTy = T->getAs<FunctionType>();
6050 assert(FTy && "call to value not of function type?");
6051 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6052
6053 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6054 // type always produce a +1 object.
6055 } else if (isa<StmtExpr>(E)) {
6056 ReturnsRetained = true;
6057
Ted Kremeneke65b0862012-03-06 20:05:56 +00006058 // We hit this case with the lambda conversion-to-block optimization;
6059 // we don't want any extra casts here.
6060 } else if (isa<CastExpr>(E) &&
6061 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006062 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006063
John McCall31168b02011-06-15 23:02:42 +00006064 // For message sends and property references, we try to find an
6065 // actual method. FIXME: we should infer retention by selector in
6066 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006067 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006068 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006069 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6070 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006071 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6072 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006073 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006074 // Don't do reclaims if we're using the zero-element array
6075 // constant.
6076 if (ArrayLit->getNumElements() == 0 &&
6077 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6078 return E;
6079
Ted Kremeneke65b0862012-03-06 20:05:56 +00006080 D = ArrayLit->getArrayWithObjectsMethod();
6081 } else if (ObjCDictionaryLiteral *DictLit
6082 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006083 // Don't do reclaims if we're using the zero-element dictionary
6084 // constant.
6085 if (DictLit->getNumElements() == 0 &&
6086 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6087 return E;
6088
Ted Kremeneke65b0862012-03-06 20:05:56 +00006089 D = DictLit->getDictWithObjectsMethod();
6090 }
John McCall31168b02011-06-15 23:02:42 +00006091
6092 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006093
6094 // Don't do reclaims on performSelector calls; despite their
6095 // return type, the invoked method doesn't necessarily actually
6096 // return an object.
6097 if (!ReturnsRetained &&
6098 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006099 return E;
John McCall31168b02011-06-15 23:02:42 +00006100 }
6101
John McCall16de4d22011-11-14 19:53:16 +00006102 // Don't reclaim an object of Class type.
6103 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006104 return E;
John McCall16de4d22011-11-14 19:53:16 +00006105
Tim Shen4a05bb82016-06-21 20:29:17 +00006106 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006107
John McCall2d637d22011-09-10 06:18:15 +00006108 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6109 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006110 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6111 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006112 }
6113
David Blaikiebbafb8a2012-03-11 07:00:24 +00006114 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006115 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006116
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006117 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6118 // a fast path for the common case that the type is directly a RecordType.
6119 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006120 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006121 while (!RT) {
6122 switch (T->getTypeClass()) {
6123 case Type::Record:
6124 RT = cast<RecordType>(T);
6125 break;
6126 case Type::ConstantArray:
6127 case Type::IncompleteArray:
6128 case Type::VariableArray:
6129 case Type::DependentSizedArray:
6130 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6131 break;
6132 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006133 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006134 }
6135 }
Mike Stump11289f42009-09-09 15:08:12 +00006136
Richard Smithfd555f62012-02-22 02:04:18 +00006137 // That should be enough to guarantee that this type is complete, if we're
6138 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006139 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006140 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006141 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006142
6143 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006144 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006145
John McCall31168b02011-06-15 23:02:42 +00006146 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006147 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006148 CheckDestructorAccess(E->getExprLoc(), Destructor,
6149 PDiag(diag::err_access_dtor_temp)
6150 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006151 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6152 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006153
Richard Smithfd555f62012-02-22 02:04:18 +00006154 // If destructor is trivial, we can avoid the extra copy.
6155 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006156 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006157
John McCall28fc7092011-11-10 05:35:25 +00006158 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006159 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006160 }
Richard Smitheec915d62012-02-18 04:13:32 +00006161
6162 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006163 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6164
6165 if (IsDecltype)
6166 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6167
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006168 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006169}
6170
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006171ExprResult
John McCall5d413782010-12-06 08:20:24 +00006172Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006173 if (SubExpr.isInvalid())
6174 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006175
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006176 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006177}
6178
John McCall28fc7092011-11-10 05:35:25 +00006179Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006180 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006181
Eli Friedman3bda6b12012-02-02 23:15:15 +00006182 CleanupVarDeclMarking();
6183
John McCall28fc7092011-11-10 05:35:25 +00006184 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6185 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006186 assert(Cleanup.exprNeedsCleanups() ||
6187 ExprCleanupObjects.size() == FirstCleanup);
6188 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006189 return SubExpr;
6190
Craig Topper5fc8fc22014-08-27 06:28:36 +00006191 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6192 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006193
Tim Shen4a05bb82016-06-21 20:29:17 +00006194 auto *E = ExprWithCleanups::Create(
6195 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006196 DiscardCleanupsInEvaluationContext();
6197
6198 return E;
6199}
6200
John McCall5d413782010-12-06 08:20:24 +00006201Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006202 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006203
Eli Friedman3bda6b12012-02-02 23:15:15 +00006204 CleanupVarDeclMarking();
6205
Tim Shen4a05bb82016-06-21 20:29:17 +00006206 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006207 return SubStmt;
6208
6209 // FIXME: In order to attach the temporaries, wrap the statement into
6210 // a StmtExpr; currently this is only used for asm statements.
6211 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6212 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006213 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006214 SourceLocation(),
6215 SourceLocation());
6216 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6217 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006218 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006219}
6220
Richard Smithfd555f62012-02-22 02:04:18 +00006221/// Process the expression contained within a decltype. For such expressions,
6222/// certain semantic checks on temporaries are delayed until this point, and
6223/// are omitted for the 'topmost' call in the decltype expression. If the
6224/// topmost call bound a temporary, strip that temporary off the expression.
6225ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006226 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006227
6228 // C++11 [expr.call]p11:
6229 // If a function call is a prvalue of object type,
6230 // -- if the function call is either
6231 // -- the operand of a decltype-specifier, or
6232 // -- the right operand of a comma operator that is the operand of a
6233 // decltype-specifier,
6234 // a temporary object is not introduced for the prvalue.
6235
6236 // Recursively rebuild ParenExprs and comma expressions to strip out the
6237 // outermost CXXBindTemporaryExpr, if any.
6238 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6239 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6240 if (SubExpr.isInvalid())
6241 return ExprError();
6242 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006243 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006244 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006245 }
6246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6247 if (BO->getOpcode() == BO_Comma) {
6248 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6249 if (RHS.isInvalid())
6250 return ExprError();
6251 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006252 return E;
6253 return new (Context) BinaryOperator(
6254 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006255 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006256 }
6257 }
6258
6259 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006260 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6261 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006262 if (TopCall)
6263 E = TopCall;
6264 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006265 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006266
6267 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006268 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006269
Richard Smithf86b0ae2012-07-28 19:54:11 +00006270 // In MS mode, don't perform any extra checking of call return types within a
6271 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006272 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006273 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006274
Richard Smithfd555f62012-02-22 02:04:18 +00006275 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006276 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6277 I != N; ++I) {
6278 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006279 if (Call == TopCall)
6280 continue;
6281
David Majnemerced8bdf2015-02-25 17:36:15 +00006282 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006283 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006284 Call, Call->getDirectCallee()))
6285 return ExprError();
6286 }
6287
6288 // Now all relevant types are complete, check the destructors are accessible
6289 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006290 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6291 I != N; ++I) {
6292 CXXBindTemporaryExpr *Bind =
6293 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006294 if (Bind == TopBind)
6295 continue;
6296
6297 CXXTemporary *Temp = Bind->getTemporary();
6298
6299 CXXRecordDecl *RD =
6300 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6301 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6302 Temp->setDestructor(Destructor);
6303
Richard Smith7d847b12012-05-11 22:20:10 +00006304 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6305 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006306 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006307 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006308 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6309 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006310
6311 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006312 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006313 }
6314
6315 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006316 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006317}
6318
Richard Smith79c927b2013-11-06 19:31:51 +00006319/// Note a set of 'operator->' functions that were used for a member access.
6320static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006321 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006322 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6323 // FIXME: Make this configurable?
6324 unsigned Limit = 9;
6325 if (OperatorArrows.size() > Limit) {
6326 // Produce Limit-1 normal notes and one 'skipping' note.
6327 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6328 SkipCount = OperatorArrows.size() - (Limit - 1);
6329 }
6330
6331 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6332 if (I == SkipStart) {
6333 S.Diag(OperatorArrows[I]->getLocation(),
6334 diag::note_operator_arrows_suppressed)
6335 << SkipCount;
6336 I += SkipCount;
6337 } else {
6338 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6339 << OperatorArrows[I]->getCallResultType();
6340 ++I;
6341 }
6342 }
6343}
6344
Nico Weber964d3322015-02-16 22:35:45 +00006345ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6346 SourceLocation OpLoc,
6347 tok::TokenKind OpKind,
6348 ParsedType &ObjectType,
6349 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006350 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006351 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006352 if (Result.isInvalid()) return ExprError();
6353 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006354
John McCall526ab472011-10-25 17:37:35 +00006355 Result = CheckPlaceholderExpr(Base);
6356 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006357 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006358
John McCallb268a282010-08-23 23:25:46 +00006359 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006360 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006361 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006362 // If we have a pointer to a dependent type and are using the -> operator,
6363 // the object type is the type that the pointer points to. We might still
6364 // have enough information about that type to do something useful.
6365 if (OpKind == tok::arrow)
6366 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6367 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006368
John McCallba7bf592010-08-24 05:47:05 +00006369 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006370 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006371 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006372 }
Mike Stump11289f42009-09-09 15:08:12 +00006373
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006374 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006375 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006376 // returned, with the original second operand.
6377 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006378 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006379 bool NoArrowOperatorFound = false;
6380 bool FirstIteration = true;
6381 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006382 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006383 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006384 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006385 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006387 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006388 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6389 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006390 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006391 noteOperatorArrows(*this, OperatorArrows);
6392 Diag(OpLoc, diag::note_operator_arrow_depth)
6393 << getLangOpts().ArrowDepth;
6394 return ExprError();
6395 }
6396
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006397 Result = BuildOverloadedArrowExpr(
6398 S, Base, OpLoc,
6399 // When in a template specialization and on the first loop iteration,
6400 // potentially give the default diagnostic (with the fixit in a
6401 // separate note) instead of having the error reported back to here
6402 // and giving a diagnostic with a fixit attached to the error itself.
6403 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006404 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006405 : &NoArrowOperatorFound);
6406 if (Result.isInvalid()) {
6407 if (NoArrowOperatorFound) {
6408 if (FirstIteration) {
6409 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006410 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006411 << FixItHint::CreateReplacement(OpLoc, ".");
6412 OpKind = tok::period;
6413 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006414 }
6415 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6416 << BaseType << Base->getSourceRange();
6417 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006418 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006419 Diag(CD->getLocStart(),
6420 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006421 }
6422 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006423 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006424 }
John McCallb268a282010-08-23 23:25:46 +00006425 Base = Result.get();
6426 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006427 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006428 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006429 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006430 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006431 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6432 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006433 return ExprError();
6434 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006435 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006436 }
Mike Stump11289f42009-09-09 15:08:12 +00006437
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006438 if (OpKind == tok::arrow &&
6439 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006440 BaseType = BaseType->getPointeeType();
6441 }
Mike Stump11289f42009-09-09 15:08:12 +00006442
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006443 // Objective-C properties allow "." access on Objective-C pointer types,
6444 // so adjust the base type to the object type itself.
6445 if (BaseType->isObjCObjectPointerType())
6446 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006447
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006448 // C++ [basic.lookup.classref]p2:
6449 // [...] If the type of the object expression is of pointer to scalar
6450 // type, the unqualified-id is looked up in the context of the complete
6451 // postfix-expression.
6452 //
6453 // This also indicates that we could be parsing a pseudo-destructor-name.
6454 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006455 // expressions or normal member (ivar or property) access expressions, and
6456 // it's legal for the type to be incomplete if this is a pseudo-destructor
6457 // call. We'll do more incomplete-type checks later in the lookup process,
6458 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006459 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006460 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006461 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006462 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006463 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006464 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006465 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006466 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006467 }
Mike Stump11289f42009-09-09 15:08:12 +00006468
Douglas Gregor3024f072012-04-16 07:05:22 +00006469 // The object type must be complete (or dependent), or
6470 // C++11 [expr.prim.general]p3:
6471 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006472 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006473 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006474 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006475 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006476 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006477 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006478
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006479 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006480 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006481 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006482 // type C (or of pointer to a class type C), the unqualified-id is looked
6483 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006484 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006485 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006486}
6487
Simon Pilgrim75c26882016-09-30 14:25:09 +00006488static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006489 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006490 if (Base->hasPlaceholderType()) {
6491 ExprResult result = S.CheckPlaceholderExpr(Base);
6492 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006493 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006494 }
6495 ObjectType = Base->getType();
6496
David Blaikie1d578782011-12-16 16:03:09 +00006497 // C++ [expr.pseudo]p2:
6498 // The left-hand side of the dot operator shall be of scalar type. The
6499 // left-hand side of the arrow operator shall be of pointer to scalar type.
6500 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006501 // Note that this is rather different from the normal handling for the
6502 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006503 if (OpKind == tok::arrow) {
6504 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6505 ObjectType = Ptr->getPointeeType();
6506 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006507 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006508 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6509 << ObjectType << true
6510 << FixItHint::CreateReplacement(OpLoc, ".");
6511 if (S.isSFINAEContext())
6512 return true;
6513
6514 OpKind = tok::period;
6515 }
6516 }
6517
6518 return false;
6519}
6520
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006521/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6522/// pointer objects.
6523static bool
6524canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6525 QualType DestructedType) {
6526 // If this is a record type, check if its destructor is callable.
6527 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6528 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6529 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6530 return false;
6531 }
6532
6533 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6534 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6535 DestructedType->isVectorType();
6536}
6537
John McCalldadc5752010-08-24 06:29:42 +00006538ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006539 SourceLocation OpLoc,
6540 tok::TokenKind OpKind,
6541 const CXXScopeSpec &SS,
6542 TypeSourceInfo *ScopeTypeInfo,
6543 SourceLocation CCLoc,
6544 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006545 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006546 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006547
Eli Friedman0ce4de42012-01-25 04:35:06 +00006548 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006549 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6550 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006551
Douglas Gregorc5c57342012-09-10 14:57:06 +00006552 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6553 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006554 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006555 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006556 else {
Nico Weber58829272012-01-23 05:50:57 +00006557 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6558 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006559 return ExprError();
6560 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006561 }
6562
6563 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006565 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006566 if (DestructedTypeInfo) {
6567 QualType DestructedType = DestructedTypeInfo->getType();
6568 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006569 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006570 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6571 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006572 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6573 // Foo *foo;
6574 // foo.~Foo();
6575 if (OpKind == tok::period && ObjectType->isPointerType() &&
6576 Context.hasSameUnqualifiedType(DestructedType,
6577 ObjectType->getPointeeType())) {
6578 auto Diagnostic =
6579 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6580 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006581
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006582 // Issue a fixit only when the destructor is valid.
6583 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6584 *this, DestructedType))
6585 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6586
6587 // Recover by setting the object type to the destructed type and the
6588 // operator to '->'.
6589 ObjectType = DestructedType;
6590 OpKind = tok::arrow;
6591 } else {
6592 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6593 << ObjectType << DestructedType << Base->getSourceRange()
6594 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6595
6596 // Recover by setting the destructed type to the object type.
6597 DestructedType = ObjectType;
6598 DestructedTypeInfo =
6599 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6600 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6601 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006602 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006603 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006604
John McCall31168b02011-06-15 23:02:42 +00006605 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6606 // Okay: just pretend that the user provided the correctly-qualified
6607 // type.
6608 } else {
6609 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6610 << ObjectType << DestructedType << Base->getSourceRange()
6611 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6612 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006613
John McCall31168b02011-06-15 23:02:42 +00006614 // Recover by setting the destructed type to the object type.
6615 DestructedType = ObjectType;
6616 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6617 DestructedTypeStart);
6618 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6619 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006620 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006623 // C++ [expr.pseudo]p2:
6624 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6625 // form
6626 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006627 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006628 //
6629 // shall designate the same scalar type.
6630 if (ScopeTypeInfo) {
6631 QualType ScopeType = ScopeTypeInfo->getType();
6632 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006633 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006635 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006636 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006637 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006638 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006640 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006641 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006642 }
6643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006644
John McCallb268a282010-08-23 23:25:46 +00006645 Expr *Result
6646 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6647 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006648 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006649 ScopeTypeInfo,
6650 CCLoc,
6651 TildeLoc,
6652 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006653
David Majnemerced8bdf2015-02-25 17:36:15 +00006654 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006655}
6656
John McCalldadc5752010-08-24 06:29:42 +00006657ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006658 SourceLocation OpLoc,
6659 tok::TokenKind OpKind,
6660 CXXScopeSpec &SS,
6661 UnqualifiedId &FirstTypeName,
6662 SourceLocation CCLoc,
6663 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006664 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006665 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6666 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6667 "Invalid first type name in pseudo-destructor");
6668 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6669 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6670 "Invalid second type name in pseudo-destructor");
6671
Eli Friedman0ce4de42012-01-25 04:35:06 +00006672 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006673 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6674 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006675
6676 // Compute the object type that we should use for name lookup purposes. Only
6677 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006678 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006679 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006680 if (ObjectType->isRecordType())
6681 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006682 else if (ObjectType->isDependentType())
6683 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685
6686 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006687 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006688 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006689 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006690 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006691 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006693 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006694 S, &SS, true, false, ObjectTypePtrForLookup,
6695 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006697 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6698 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006699 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006700 // couldn't find anything useful in scope. Just store the identifier and
6701 // it's location, and we'll perform (qualified) name lookup again at
6702 // template instantiation time.
6703 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6704 SecondTypeName.StartLocation);
6705 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006707 diag::err_pseudo_dtor_destructor_non_type)
6708 << SecondTypeName.Identifier << ObjectType;
6709 if (isSFINAEContext())
6710 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006711
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006712 // Recover by assuming we had the right type all along.
6713 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006714 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006715 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006716 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006717 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006718 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006719 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006720 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006721 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006722 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006723 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006724 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006725 TemplateId->TemplateNameLoc,
6726 TemplateId->LAngleLoc,
6727 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006728 TemplateId->RAngleLoc,
6729 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006730 if (T.isInvalid() || !T.get()) {
6731 // Recover by assuming we had the right type all along.
6732 DestructedType = ObjectType;
6733 } else
6734 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736
6737 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006738 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006739 if (!DestructedType.isNull()) {
6740 if (!DestructedTypeInfo)
6741 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006742 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006743 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006746 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006747 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006748 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006749 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006750 FirstTypeName.Identifier) {
6751 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006753 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006754 S, &SS, true, false, ObjectTypePtrForLookup,
6755 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006756 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006757 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006758 diag::err_pseudo_dtor_destructor_non_type)
6759 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006760
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006761 if (isSFINAEContext())
6762 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006764 // Just drop this type. It's unnecessary anyway.
6765 ScopeType = QualType();
6766 } else
6767 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006768 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006769 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006770 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006771 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006772 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006773 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006774 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006775 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006776 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006777 TemplateId->TemplateNameLoc,
6778 TemplateId->LAngleLoc,
6779 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006780 TemplateId->RAngleLoc,
6781 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006782 if (T.isInvalid() || !T.get()) {
6783 // Recover by dropping this type.
6784 ScopeType = QualType();
6785 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006786 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006787 }
6788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006789
Douglas Gregor90ad9222010-02-24 23:02:30 +00006790 if (!ScopeType.isNull() && !ScopeTypeInfo)
6791 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6792 FirstTypeName.StartLocation);
6793
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794
John McCallb268a282010-08-23 23:25:46 +00006795 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006796 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006797 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006798}
6799
David Blaikie1d578782011-12-16 16:03:09 +00006800ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6801 SourceLocation OpLoc,
6802 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006803 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006804 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006805 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006806 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6807 return ExprError();
6808
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006809 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6810 false);
David Blaikie1d578782011-12-16 16:03:09 +00006811
6812 TypeLocBuilder TLB;
6813 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6814 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6815 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6816 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6817
6818 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006819 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006820 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006821}
6822
John Wiegley01296292011-04-08 18:41:53 +00006823ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006824 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006825 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006826 if (Method->getParent()->isLambda() &&
6827 Method->getConversionType()->isBlockPointerType()) {
6828 // This is a lambda coversion to block pointer; check if the argument
6829 // is a LambdaExpr.
6830 Expr *SubE = E;
6831 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6832 if (CE && CE->getCastKind() == CK_NoOp)
6833 SubE = CE->getSubExpr();
6834 SubE = SubE->IgnoreParens();
6835 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6836 SubE = BE->getSubExpr();
6837 if (isa<LambdaExpr>(SubE)) {
6838 // For the conversion to block pointer on a lambda expression, we
6839 // construct a special BlockLiteral instead; this doesn't really make
6840 // a difference in ARC, but outside of ARC the resulting block literal
6841 // follows the normal lifetime rules for block literals instead of being
6842 // autoreleased.
6843 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00006844 PushExpressionEvaluationContext(
6845 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006846 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6847 E->getExprLoc(),
6848 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006849 PopExpressionEvaluationContext();
6850
Eli Friedman98b01ed2012-03-01 04:01:32 +00006851 if (Exp.isInvalid())
6852 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6853 return Exp;
6854 }
6855 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006856
Craig Topperc3ec1492014-05-26 06:22:03 +00006857 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006858 FoundDecl, Method);
6859 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006860 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006861
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006862 MemberExpr *ME = new (Context) MemberExpr(
6863 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6864 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006865 if (HadMultipleCandidates)
6866 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006867 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006868
Alp Toker314cc812014-01-25 16:55:45 +00006869 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006870 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6871 ResultType = ResultType.getNonLValueExprType(Context);
6872
Douglas Gregor27381f32009-11-23 12:27:39 +00006873 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006874 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006875 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006876
6877 if (CheckFunctionCall(Method, CE,
6878 Method->getType()->castAs<FunctionProtoType>()))
6879 return ExprError();
6880
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006881 return CE;
6882}
6883
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006884ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6885 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006886 // If the operand is an unresolved lookup expression, the expression is ill-
6887 // formed per [over.over]p1, because overloaded function names cannot be used
6888 // without arguments except in explicit contexts.
6889 ExprResult R = CheckPlaceholderExpr(Operand);
6890 if (R.isInvalid())
6891 return R;
6892
6893 // The operand may have been modified when checking the placeholder type.
6894 Operand = R.get();
6895
Richard Smith51ec0cf2017-02-21 01:17:38 +00006896 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006897 // The expression operand for noexcept is in an unevaluated expression
6898 // context, so side effects could result in unintended consequences.
6899 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6900 }
6901
Richard Smithf623c962012-04-17 00:58:00 +00006902 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006903 return new (Context)
6904 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006905}
6906
6907ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6908 Expr *Operand, SourceLocation RParen) {
6909 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006910}
6911
Eli Friedmanf798f652012-05-24 22:04:19 +00006912static bool IsSpecialDiscardedValue(Expr *E) {
6913 // In C++11, discarded-value expressions of a certain form are special,
6914 // according to [expr]p10:
6915 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6916 // expression is an lvalue of volatile-qualified type and it has
6917 // one of the following forms:
6918 E = E->IgnoreParens();
6919
Eli Friedmanc49c2262012-05-24 22:36:31 +00006920 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006921 if (isa<DeclRefExpr>(E))
6922 return true;
6923
Eli Friedmanc49c2262012-05-24 22:36:31 +00006924 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006925 if (isa<ArraySubscriptExpr>(E))
6926 return true;
6927
Eli Friedmanc49c2262012-05-24 22:36:31 +00006928 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006929 if (isa<MemberExpr>(E))
6930 return true;
6931
Eli Friedmanc49c2262012-05-24 22:36:31 +00006932 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006933 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6934 if (UO->getOpcode() == UO_Deref)
6935 return true;
6936
6937 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006938 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006939 if (BO->isPtrMemOp())
6940 return true;
6941
Eli Friedmanc49c2262012-05-24 22:36:31 +00006942 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006943 if (BO->getOpcode() == BO_Comma)
6944 return IsSpecialDiscardedValue(BO->getRHS());
6945 }
6946
Eli Friedmanc49c2262012-05-24 22:36:31 +00006947 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006948 // operands are one of the above, or
6949 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6950 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6951 IsSpecialDiscardedValue(CO->getFalseExpr());
6952 // The related edge case of "*x ?: *x".
6953 if (BinaryConditionalOperator *BCO =
6954 dyn_cast<BinaryConditionalOperator>(E)) {
6955 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6956 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6957 IsSpecialDiscardedValue(BCO->getFalseExpr());
6958 }
6959
6960 // Objective-C++ extensions to the rule.
6961 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6962 return true;
6963
6964 return false;
6965}
6966
John McCall34376a62010-12-04 03:47:34 +00006967/// Perform the conversions required for an expression used in a
6968/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006969ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006970 if (E->hasPlaceholderType()) {
6971 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006972 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006973 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006974 }
6975
John McCallfee942d2010-12-02 02:07:15 +00006976 // C99 6.3.2.1:
6977 // [Except in specific positions,] an lvalue that does not have
6978 // array type is converted to the value stored in the
6979 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006980 if (E->isRValue()) {
6981 // In C, function designators (i.e. expressions of function type)
6982 // are r-values, but we still want to do function-to-pointer decay
6983 // on them. This is both technically correct and convenient for
6984 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006985 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006986 return DefaultFunctionArrayConversion(E);
6987
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006988 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006989 }
John McCallfee942d2010-12-02 02:07:15 +00006990
Eli Friedmanf798f652012-05-24 22:04:19 +00006991 if (getLangOpts().CPlusPlus) {
6992 // The C++11 standard defines the notion of a discarded-value expression;
6993 // normally, we don't need to do anything to handle it, but if it is a
6994 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6995 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006996 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006997 E->getType().isVolatileQualified() &&
6998 IsSpecialDiscardedValue(E)) {
6999 ExprResult Res = DefaultLvalueConversion(E);
7000 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007001 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007002 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007003 }
Richard Smith122f88d2016-12-06 23:52:28 +00007004
7005 // C++1z:
7006 // If the expression is a prvalue after this optional conversion, the
7007 // temporary materialization conversion is applied.
7008 //
7009 // We skip this step: IR generation is able to synthesize the storage for
7010 // itself in the aggregate case, and adding the extra node to the AST is
7011 // just clutter.
7012 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7013 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007014 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007015 }
John McCall34376a62010-12-04 03:47:34 +00007016
7017 // GCC seems to also exclude expressions of incomplete enum type.
7018 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7019 if (!T->getDecl()->isComplete()) {
7020 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007021 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007022 return E;
John McCall34376a62010-12-04 03:47:34 +00007023 }
7024 }
7025
John Wiegley01296292011-04-08 18:41:53 +00007026 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7027 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007028 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007029 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007030
John McCallca61b652010-12-04 12:29:11 +00007031 if (!E->getType()->isVoidType())
7032 RequireCompleteType(E->getExprLoc(), E->getType(),
7033 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007034 return E;
John McCall34376a62010-12-04 03:47:34 +00007035}
7036
Faisal Valia17d19f2013-11-07 05:17:06 +00007037// If we can unambiguously determine whether Var can never be used
7038// in a constant expression, return true.
7039// - if the variable and its initializer are non-dependent, then
7040// we can unambiguously check if the variable is a constant expression.
7041// - if the initializer is not value dependent - we can determine whether
7042// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007043// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007044// never be a constant expression.
7045// - FXIME: if the initializer is dependent, we can still do some analysis and
7046// identify certain cases unambiguously as non-const by using a Visitor:
7047// - such as those that involve odr-use of a ParmVarDecl, involve a new
7048// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007049static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007050 ASTContext &Context) {
7051 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007052 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007053
7054 // If there is no initializer - this can not be a constant expression.
7055 if (!Var->getAnyInitializer(DefVD)) return true;
7056 assert(DefVD);
7057 if (DefVD->isWeak()) return false;
7058 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007059
Faisal Valia17d19f2013-11-07 05:17:06 +00007060 Expr *Init = cast<Expr>(Eval->Value);
7061
7062 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007063 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7064 // of value-dependent expressions, and use it here to determine whether the
7065 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007066 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007067 }
7068
Simon Pilgrim75c26882016-09-30 14:25:09 +00007069 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007070}
7071
Simon Pilgrim75c26882016-09-30 14:25:09 +00007072/// \brief Check if the current lambda has any potential captures
7073/// that must be captured by any of its enclosing lambdas that are ready to
7074/// capture. If there is a lambda that can capture a nested
7075/// potential-capture, go ahead and do so. Also, check to see if any
7076/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007077/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007078
Faisal Valiab3d6462013-12-07 20:22:44 +00007079static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7080 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7081
Simon Pilgrim75c26882016-09-30 14:25:09 +00007082 assert(!S.isUnevaluatedContext());
7083 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007084#ifndef NDEBUG
7085 DeclContext *DC = S.CurContext;
7086 while (DC && isa<CapturedDecl>(DC))
7087 DC = DC->getParent();
7088 assert(
7089 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007090 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007091#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007092
7093 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7094
7095 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7096 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007097
Faisal Valiab3d6462013-12-07 20:22:44 +00007098 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007099 // lambda (within a generic outer lambda), must be captured by an
7100 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007101 const unsigned NumPotentialCaptures =
7102 CurrentLSI->getNumPotentialVariableCaptures();
7103 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007104 Expr *VarExpr = nullptr;
7105 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007106 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007107 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007108 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007109 // need to check enclosing lambda's for speculative captures.
7110 // For e.g.:
7111 // Even though 'x' is not odr-used, it should be captured.
7112 // int test() {
7113 // const int x = 10;
7114 // auto L = [=](auto a) {
7115 // (void) +x + a;
7116 // };
7117 // }
7118 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007119 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007120 continue;
7121
7122 // If we have a capture-capable lambda for the variable, go ahead and
7123 // capture the variable in that lambda (and all its enclosing lambdas).
7124 if (const Optional<unsigned> Index =
7125 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7126 FunctionScopesArrayRef, Var, S)) {
7127 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7128 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7129 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007130 }
7131 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007132 VariableCanNeverBeAConstantExpression(Var, S.Context);
7133 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7134 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007135 // can not be used in a constant expression - which means
7136 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007137 // capture violation early, if the variable is un-captureable.
7138 // This is purely for diagnosing errors early. Otherwise, this
7139 // error would get diagnosed when the lambda becomes capture ready.
7140 QualType CaptureType, DeclRefType;
7141 SourceLocation ExprLoc = VarExpr->getExprLoc();
7142 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007143 /*EllipsisLoc*/ SourceLocation(),
7144 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007145 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007146 // We will never be able to capture this variable, and we need
7147 // to be able to in any and all instantiations, so diagnose it.
7148 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007149 /*EllipsisLoc*/ SourceLocation(),
7150 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007151 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007152 }
7153 }
7154 }
7155
Faisal Valiab3d6462013-12-07 20:22:44 +00007156 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007157 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007158 // If we have a capture-capable lambda for 'this', go ahead and capture
7159 // 'this' in that lambda (and all its enclosing lambdas).
7160 if (const Optional<unsigned> Index =
7161 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007162 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007163 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7164 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7165 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7166 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007167 }
7168 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007169
7170 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007171 CurrentLSI->clearPotentialCaptures();
7172}
7173
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007174static ExprResult attemptRecovery(Sema &SemaRef,
7175 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007176 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007177 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7178 Consumer.getLookupResult().getLookupKind());
7179 const CXXScopeSpec *SS = Consumer.getSS();
7180 CXXScopeSpec NewSS;
7181
7182 // Use an approprate CXXScopeSpec for building the expr.
7183 if (auto *NNS = TC.getCorrectionSpecifier())
7184 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7185 else if (SS && !TC.WillReplaceSpecifier())
7186 NewSS = *SS;
7187
Richard Smithde6d6c42015-12-29 19:43:10 +00007188 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007189 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007190 R.addDecl(ND);
7191 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007192 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007193 CXXRecordDecl *Record = nullptr;
7194 if (auto *NNS = TC.getCorrectionSpecifier())
7195 Record = NNS->getAsType()->getAsCXXRecordDecl();
7196 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007197 Record =
7198 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7199 if (Record)
7200 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007201
7202 // Detect and handle the case where the decl might be an implicit
7203 // member.
7204 bool MightBeImplicitMember;
7205 if (!Consumer.isAddressOfOperand())
7206 MightBeImplicitMember = true;
7207 else if (!NewSS.isEmpty())
7208 MightBeImplicitMember = false;
7209 else if (R.isOverloadedResult())
7210 MightBeImplicitMember = false;
7211 else if (R.isUnresolvableResult())
7212 MightBeImplicitMember = true;
7213 else
7214 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7215 isa<IndirectFieldDecl>(ND) ||
7216 isa<MSPropertyDecl>(ND);
7217
7218 if (MightBeImplicitMember)
7219 return SemaRef.BuildPossibleImplicitMemberExpr(
7220 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007221 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007222 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7223 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7224 Ivar->getIdentifier());
7225 }
7226 }
7227
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007228 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7229 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007230}
7231
Kaelyn Takata6c759512014-10-27 18:07:37 +00007232namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007233class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7234 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7235
7236public:
7237 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7238 : TypoExprs(TypoExprs) {}
7239 bool VisitTypoExpr(TypoExpr *TE) {
7240 TypoExprs.insert(TE);
7241 return true;
7242 }
7243};
7244
Kaelyn Takata6c759512014-10-27 18:07:37 +00007245class TransformTypos : public TreeTransform<TransformTypos> {
7246 typedef TreeTransform<TransformTypos> BaseTransform;
7247
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007248 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7249 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007250 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007251 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007252 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007253 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007254
7255 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7256 /// If the TypoExprs were successfully corrected, then the diagnostics should
7257 /// suggest the corrections. Otherwise the diagnostics will not suggest
7258 /// anything (having been passed an empty TypoCorrection).
7259 void EmitAllDiagnostics() {
7260 for (auto E : TypoExprs) {
7261 TypoExpr *TE = cast<TypoExpr>(E);
7262 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007263 if (State.DiagHandler) {
7264 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7265 ExprResult Replacement = TransformCache[TE];
7266
7267 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7268 // TypoCorrection, replacing the existing decls. This ensures the right
7269 // NamedDecl is used in diagnostics e.g. in the case where overload
7270 // resolution was used to select one from several possible decls that
7271 // had been stored in the TypoCorrection.
7272 if (auto *ND = getDeclFromExpr(
7273 Replacement.isInvalid() ? nullptr : Replacement.get()))
7274 TC.setCorrectionDecl(ND);
7275
7276 State.DiagHandler(TC);
7277 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007278 SemaRef.clearDelayedTypo(TE);
7279 }
7280 }
7281
7282 /// \brief If corrections for the first TypoExpr have been exhausted for a
7283 /// given combination of the other TypoExprs, retry those corrections against
7284 /// the next combination of substitutions for the other TypoExprs by advancing
7285 /// to the next potential correction of the second TypoExpr. For the second
7286 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7287 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7288 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7289 /// TransformCache). Returns true if there is still any untried combinations
7290 /// of corrections.
7291 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7292 for (auto TE : TypoExprs) {
7293 auto &State = SemaRef.getTypoExprState(TE);
7294 TransformCache.erase(TE);
7295 if (!State.Consumer->finished())
7296 return true;
7297 State.Consumer->resetCorrectionStream();
7298 }
7299 return false;
7300 }
7301
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007302 NamedDecl *getDeclFromExpr(Expr *E) {
7303 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7304 E = OverloadResolution[OE];
7305
7306 if (!E)
7307 return nullptr;
7308 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007309 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007310 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007311 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007312 // FIXME: Add any other expr types that could be be seen by the delayed typo
7313 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007314 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007315 return nullptr;
7316 }
7317
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007318 ExprResult TryTransform(Expr *E) {
7319 Sema::SFINAETrap Trap(SemaRef);
7320 ExprResult Res = TransformExpr(E);
7321 if (Trap.hasErrorOccurred() || Res.isInvalid())
7322 return ExprError();
7323
7324 return ExprFilter(Res.get());
7325 }
7326
Kaelyn Takata6c759512014-10-27 18:07:37 +00007327public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007328 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7329 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007330
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007331 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7332 MultiExprArg Args,
7333 SourceLocation RParenLoc,
7334 Expr *ExecConfig = nullptr) {
7335 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7336 RParenLoc, ExecConfig);
7337 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007338 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007339 Expr *ResultCall = Result.get();
7340 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7341 ResultCall = BE->getSubExpr();
7342 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7343 OverloadResolution[OE] = CE->getCallee();
7344 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007345 }
7346 return Result;
7347 }
7348
Kaelyn Takata6c759512014-10-27 18:07:37 +00007349 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7350
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007351 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7352
Kaelyn Takata6c759512014-10-27 18:07:37 +00007353 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007354 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007355 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007356 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007357
Kaelyn Takata6c759512014-10-27 18:07:37 +00007358 // Exit if either the transform was valid or if there were no TypoExprs
7359 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007360 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007361 !CheckAndAdvanceTypoExprCorrectionStreams())
7362 break;
7363 }
7364
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007365 // Ensure none of the TypoExprs have multiple typo correction candidates
7366 // with the same edit length that pass all the checks and filters.
7367 // TODO: Properly handle various permutations of possible corrections when
7368 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007369 // Also, disable typo correction while attempting the transform when
7370 // handling potentially ambiguous typo corrections as any new TypoExprs will
7371 // have been introduced by the application of one of the correction
7372 // candidates and add little to no value if corrected.
7373 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007374 while (!AmbiguousTypoExprs.empty()) {
7375 auto TE = AmbiguousTypoExprs.back();
7376 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007377 auto &State = SemaRef.getTypoExprState(TE);
7378 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007379 TransformCache.erase(TE);
7380 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007381 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007382 TransformCache.erase(TE);
7383 Res = ExprError();
7384 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007385 }
7386 AmbiguousTypoExprs.remove(TE);
7387 State.Consumer->restoreSavedPosition();
7388 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007389 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007390 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007391
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007392 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007393 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007394 FindTypoExprs(TypoExprs).TraverseStmt(E);
7395
Kaelyn Takata6c759512014-10-27 18:07:37 +00007396 EmitAllDiagnostics();
7397
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007398 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007399 }
7400
7401 ExprResult TransformTypoExpr(TypoExpr *E) {
7402 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7403 // cached transformation result if there is one and the TypoExpr isn't the
7404 // first one that was encountered.
7405 auto &CacheEntry = TransformCache[E];
7406 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7407 return CacheEntry;
7408 }
7409
7410 auto &State = SemaRef.getTypoExprState(E);
7411 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7412
7413 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7414 // typo correction and return it.
7415 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007416 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007417 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007418 // FIXME: If we would typo-correct to an invalid declaration, it's
7419 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007420 ExprResult NE = State.RecoveryHandler ?
7421 State.RecoveryHandler(SemaRef, E, TC) :
7422 attemptRecovery(SemaRef, *State.Consumer, TC);
7423 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007424 // Check whether there may be a second viable correction with the same
7425 // edit distance; if so, remember this TypoExpr may have an ambiguous
7426 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007427 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007428 if ((Next = State.Consumer->peekNextCorrection()) &&
7429 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7430 AmbiguousTypoExprs.insert(E);
7431 } else {
7432 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007433 }
7434 assert(!NE.isUnset() &&
7435 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007436 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007437 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007438 }
7439 return CacheEntry = ExprError();
7440 }
7441};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007442}
Faisal Valia17d19f2013-11-07 05:17:06 +00007443
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007444ExprResult
7445Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7446 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007447 // If the current evaluation context indicates there are uncorrected typos
7448 // and the current expression isn't guaranteed to not have typos, try to
7449 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007450 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007451 (E->isTypeDependent() || E->isValueDependent() ||
7452 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007453 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7454 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7455 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007456 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007457 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007458 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007459 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007460 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007461 ExprEvalContexts.back().NumTypos -= TyposResolved;
7462 return Result;
7463 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007464 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007465 }
7466 return E;
7467}
7468
Richard Smith945f8d32013-01-14 22:39:08 +00007469ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007470 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007471 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007472 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007473 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007474
7475 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007476 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007477
7478 // If we are an init-expression in a lambdas init-capture, we should not
7479 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007480 // containing full-expression is done).
7481 // template<class ... Ts> void test(Ts ... t) {
7482 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7483 // return a;
7484 // }() ...);
7485 // }
7486 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7487 // when we parse the lambda introducer, and teach capturing (but not
7488 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7489 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7490 // lambda where we've entered the introducer but not the body, or represent a
7491 // lambda where we've entered the body, depending on where the
7492 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007493 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007494 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007495 return ExprError();
7496
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007497 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007498 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007499 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007500 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007501 if (FullExpr.isInvalid())
7502 return ExprError();
7503 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007504
Richard Smith945f8d32013-01-14 22:39:08 +00007505 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007506 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007507 if (FullExpr.isInvalid())
7508 return ExprError();
7509
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007510 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007511 if (FullExpr.isInvalid())
7512 return ExprError();
7513 }
John Wiegley01296292011-04-08 18:41:53 +00007514
Kaelyn Takata49d84322014-11-11 23:26:56 +00007515 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7516 if (FullExpr.isInvalid())
7517 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007518
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007519 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007520
Simon Pilgrim75c26882016-09-30 14:25:09 +00007521 // At the end of this full expression (which could be a deeply nested
7522 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007523 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007524 // Consider the following code:
7525 // void f(int, int);
7526 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007527 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007528 // const int x = 10, y = 20;
7529 // auto L = [=](auto a) {
7530 // auto M = [=](auto b) {
7531 // f(x, b); <-- requires x to be captured by L and M
7532 // f(y, a); <-- requires y to be captured by L, but not all Ms
7533 // };
7534 // };
7535 // }
7536
Simon Pilgrim75c26882016-09-30 14:25:09 +00007537 // FIXME: Also consider what happens for something like this that involves
7538 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007539 // void f() {
7540 // const int n = 0;
7541 // auto L = [&](auto a) {
7542 // +n + ({ 0; a; });
7543 // };
7544 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007545 //
7546 // Here, we see +n, and then the full-expression 0; ends, so we don't
7547 // capture n (and instead remove it from our list of potential captures),
7548 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007549 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007550
Alexey Bataev31939e32016-11-11 12:36:20 +00007551 LambdaScopeInfo *const CurrentLSI =
7552 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007553 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007554 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007555 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007556 // By ensuring we are in the context of a lambda's call operator
7557 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007558 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007559 // PR, a proper fix would entail :
7560 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007561 // - Add to Sema an integer holding the smallest (outermost) scope
7562 // index that we are *lexically* within, and save/restore/set to
7563 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007564 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007565 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007566 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007567 DeclContext *DC = CurContext;
7568 while (DC && isa<CapturedDecl>(DC))
7569 DC = DC->getParent();
7570 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007571 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007572 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007573 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7574 *this);
John McCall5d413782010-12-06 08:20:24 +00007575 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007576}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007577
7578StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7579 if (!FullStmt) return StmtError();
7580
John McCall5d413782010-12-06 08:20:24 +00007581 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007582}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007583
Simon Pilgrim75c26882016-09-30 14:25:09 +00007584Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007585Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7586 CXXScopeSpec &SS,
7587 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007588 DeclarationName TargetName = TargetNameInfo.getName();
7589 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007590 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007591
Douglas Gregor43edb322011-10-24 22:31:10 +00007592 // If the name itself is dependent, then the result is dependent.
7593 if (TargetName.isDependentName())
7594 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007595
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007596 // Do the redeclaration lookup in the current scope.
7597 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7598 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007599 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007600 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007601
Douglas Gregor43edb322011-10-24 22:31:10 +00007602 switch (R.getResultKind()) {
7603 case LookupResult::Found:
7604 case LookupResult::FoundOverloaded:
7605 case LookupResult::FoundUnresolvedValue:
7606 case LookupResult::Ambiguous:
7607 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007608
Douglas Gregor43edb322011-10-24 22:31:10 +00007609 case LookupResult::NotFound:
7610 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007611
Douglas Gregor43edb322011-10-24 22:31:10 +00007612 case LookupResult::NotFoundInCurrentInstantiation:
7613 return IER_Dependent;
7614 }
David Blaikie8a40f702012-01-17 06:56:22 +00007615
7616 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007617}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007618
Simon Pilgrim75c26882016-09-30 14:25:09 +00007619Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007620Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7621 bool IsIfExists, CXXScopeSpec &SS,
7622 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007623 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007624
Richard Smith151c4562016-12-20 21:35:28 +00007625 // Check for an unexpanded parameter pack.
7626 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7627 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7628 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007629 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007630
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007631 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7632}