blob: 1d56fc856e8dabf60d48203321dd50c303b5f7c5 [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) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000359 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000360
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 &&
Alexey Bataev1ab34572018-05-02 16:52:07 +0000698 !getSourceManager().isInSystemHeader(OpLoc) &&
699 (!getLangOpts().OpenMPIsDevice ||
700 !getLangOpts().OpenMPHostCXXExceptions ||
701 isInOpenMPTargetExecutionDirective() ||
702 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000703 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000704
Justin Lebar2a8db342016-09-28 22:45:54 +0000705 // Exceptions aren't allowed in CUDA device code.
706 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000707 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
708 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000709
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000710 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
711 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
712
John Wiegley01296292011-04-08 18:41:53 +0000713 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000714 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
715 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000716 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000717
718 // Initialize the exception result. This implicitly weeds out
719 // abstract types or types with inaccessible copy constructors.
720
721 // C++0x [class.copymove]p31:
722 // When certain criteria are met, an implementation is allowed to omit the
723 // copy/move construction of a class object [...]
724 //
725 // - in a throw-expression, when the operand is the name of a
726 // non-volatile automatic object (other than a function or
727 // catch-clause
728 // parameter) whose scope does not extend beyond the end of the
729 // innermost enclosing try-block (if there is one), the copy/move
730 // operation from the operand to the exception object (15.1) can be
731 // omitted by constructing the automatic object directly into the
732 // exception object
733 const VarDecl *NRVOVariable = nullptr;
734 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000735 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000736
737 InitializedEntity Entity = InitializedEntity::InitializeException(
738 OpLoc, ExceptionObjectTy,
739 /*NRVO=*/NRVOVariable != nullptr);
740 ExprResult Res = PerformMoveOrCopyInitialization(
741 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
742 if (Res.isInvalid())
743 return ExprError();
744 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000745 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000746
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000747 return new (Context)
748 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000749}
750
David Majnemere7a818f2015-03-06 18:53:55 +0000751static void
752collectPublicBases(CXXRecordDecl *RD,
753 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
754 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
755 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
756 bool ParentIsPublic) {
757 for (const CXXBaseSpecifier &BS : RD->bases()) {
758 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
759 bool NewSubobject;
760 // Virtual bases constitute the same subobject. Non-virtual bases are
761 // always distinct subobjects.
762 if (BS.isVirtual())
763 NewSubobject = VBases.insert(BaseDecl).second;
764 else
765 NewSubobject = true;
766
767 if (NewSubobject)
768 ++SubobjectsSeen[BaseDecl];
769
770 // Only add subobjects which have public access throughout the entire chain.
771 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
772 if (PublicPath)
773 PublicSubobjectsSeen.insert(BaseDecl);
774
775 // Recurse on to each base subobject.
776 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
777 PublicPath);
778 }
779}
780
781static void getUnambiguousPublicSubobjects(
782 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
783 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
784 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
785 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
786 SubobjectsSeen[RD] = 1;
787 PublicSubobjectsSeen.insert(RD);
788 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
789 /*ParentIsPublic=*/true);
790
791 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
792 // Skip ambiguous objects.
793 if (SubobjectsSeen[PublicSubobject] > 1)
794 continue;
795
796 Objects.push_back(PublicSubobject);
797 }
798}
799
Sebastian Redl4de47b42009-04-27 20:27:31 +0000800/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000801bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
802 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000803 // If the type of the exception would be an incomplete type or a pointer
804 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000805 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000806 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000807 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000808 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000809 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000810 }
811 if (!isPointer || !Ty->isVoidType()) {
812 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000813 isPointer ? diag::err_throw_incomplete_ptr
814 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000815 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000816 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000817
David Majnemerd09a51c2015-03-03 01:50:05 +0000818 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000819 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000820 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000821 }
822
Eli Friedman91a3d272010-06-03 20:39:03 +0000823 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000824 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
825 if (!RD)
826 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000827
Douglas Gregor88d292c2010-05-13 16:44:06 +0000828 // If we are throwing a polymorphic class type or pointer thereof,
829 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000830 MarkVTableUsed(ThrowLoc, RD);
831
Eli Friedman36ebbec2010-10-12 20:32:36 +0000832 // If a pointer is thrown, the referenced object will not be destroyed.
833 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000834 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000835
Richard Smitheec915d62012-02-18 04:13:32 +0000836 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000837 if (!RD->hasIrrelevantDestructor()) {
838 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
839 MarkFunctionReferenced(E->getExprLoc(), Destructor);
840 CheckDestructorAccess(E->getExprLoc(), Destructor,
841 PDiag(diag::err_access_dtor_exception) << Ty);
842 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000843 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000844 }
845 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000846
David Majnemerdfa6d202015-03-11 18:36:39 +0000847 // The MSVC ABI creates a list of all types which can catch the exception
848 // object. This list also references the appropriate copy constructor to call
849 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000850 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000851 // We are only interested in the public, unambiguous bases contained within
852 // the exception object. Bases which are ambiguous or otherwise
853 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000854 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
855 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000856
David Majnemere7a818f2015-03-06 18:53:55 +0000857 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000858 // Attempt to lookup the copy constructor. Various pieces of machinery
859 // will spring into action, like template instantiation, which means this
860 // cannot be a simple walk of the class's decls. Instead, we must perform
861 // lookup and overload resolution.
862 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
863 if (!CD)
864 continue;
865
866 // Mark the constructor referenced as it is used by this throw expression.
867 MarkFunctionReferenced(E->getExprLoc(), CD);
868
869 // Skip this copy constructor if it is trivial, we don't need to record it
870 // in the catchable type data.
871 if (CD->isTrivial())
872 continue;
873
874 // The copy constructor is non-trivial, create a mapping from this class
875 // type to this constructor.
876 // N.B. The selection of copy constructor is not sensitive to this
877 // particular throw-site. Lookup will be performed at the catch-site to
878 // ensure that the copy constructor is, in fact, accessible (via
879 // friendship or any other means).
880 Context.addCopyConstructorForExceptionObject(Subobject, CD);
881
882 // We don't keep the instantiated default argument expressions around so
883 // we must rebuild them here.
884 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000885 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
886 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000887 }
888 }
889 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000890
David Majnemerba3e5ec2015-03-13 18:26:17 +0000891 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000892}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893
Faisal Vali67b04462016-06-11 16:41:54 +0000894static QualType adjustCVQualifiersForCXXThisWithinLambda(
895 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
896 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
897
898 QualType ClassType = ThisTy->getPointeeType();
899 LambdaScopeInfo *CurLSI = nullptr;
900 DeclContext *CurDC = CurSemaContext;
901
902 // Iterate through the stack of lambdas starting from the innermost lambda to
903 // the outermost lambda, checking if '*this' is ever captured by copy - since
904 // that could change the cv-qualifiers of the '*this' object.
905 // The object referred to by '*this' starts out with the cv-qualifiers of its
906 // member function. We then start with the innermost lambda and iterate
907 // outward checking to see if any lambda performs a by-copy capture of '*this'
908 // - and if so, any nested lambda must respect the 'constness' of that
909 // capturing lamdbda's call operator.
910 //
911
Faisal Vali999f27e2017-05-02 20:56:34 +0000912 // Since the FunctionScopeInfo stack is representative of the lexical
913 // nesting of the lambda expressions during initial parsing (and is the best
914 // place for querying information about captures about lambdas that are
915 // partially processed) and perhaps during instantiation of function templates
916 // that contain lambda expressions that need to be transformed BUT not
917 // necessarily during instantiation of a nested generic lambda's function call
918 // operator (which might even be instantiated at the end of the TU) - at which
919 // time the DeclContext tree is mature enough to query capture information
920 // reliably - we use a two pronged approach to walk through all the lexically
921 // enclosing lambda expressions:
922 //
923 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
924 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
925 // enclosed by the call-operator of the LSI below it on the stack (while
926 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
927 // the stack represents the innermost lambda.
928 //
929 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
930 // represents a lambda's call operator. If it does, we must be instantiating
931 // a generic lambda's call operator (represented by the Current LSI, and
932 // should be the only scenario where an inconsistency between the LSI and the
933 // DeclContext should occur), so climb out the DeclContexts if they
934 // represent lambdas, while querying the corresponding closure types
935 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000936
Faisal Vali999f27e2017-05-02 20:56:34 +0000937 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000938 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000939 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
940 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
941 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000942 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
943 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000944
945 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000946 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000947
Faisal Vali67b04462016-06-11 16:41:54 +0000948 auto C = CurLSI->getCXXThisCapture();
949
950 if (C.isCopyCapture()) {
951 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
952 if (CurLSI->CallOperator->isConst())
953 ClassType.addConst();
954 return ASTCtx.getPointerType(ClassType);
955 }
956 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000957
958 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
959 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000960 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +0000961 assert(CurLSI && "While computing 'this' capture-type for a generic "
962 "lambda, we must have a corresponding LambdaScopeInfo");
963 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
964 "While computing 'this' capture-type for a generic lambda, when we "
965 "run out of enclosing LSI's, yet the enclosing DC is a "
966 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
967 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +0000968 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000969
Faisal Vali67b04462016-06-11 16:41:54 +0000970 auto IsThisCaptured =
971 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
972 IsConst = false;
973 IsByCopy = false;
974 for (auto &&C : Closure->captures()) {
975 if (C.capturesThis()) {
976 if (C.getCaptureKind() == LCK_StarThis)
977 IsByCopy = true;
978 if (Closure->getLambdaCallOperator()->isConst())
979 IsConst = true;
980 return true;
981 }
982 }
983 return false;
984 };
985
986 bool IsByCopyCapture = false;
987 bool IsConstCapture = false;
988 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
989 while (Closure &&
990 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
991 if (IsByCopyCapture) {
992 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
993 if (IsConstCapture)
994 ClassType.addConst();
995 return ASTCtx.getPointerType(ClassType);
996 }
997 Closure = isLambdaCallOperator(Closure->getParent())
998 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
999 : nullptr;
1000 }
1001 }
1002 return ASTCtx.getPointerType(ClassType);
1003}
1004
Eli Friedman73a04092012-01-07 04:59:52 +00001005QualType Sema::getCurrentThisType() {
1006 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001007 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001008
Richard Smith938f40b2011-06-11 17:19:42 +00001009 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1010 if (method && method->isInstance())
1011 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001012 }
Faisal Validc6b5962016-03-21 09:25:37 +00001013
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001014 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001015 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001016
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001017 assert(isa<CXXRecordDecl>(DC) &&
1018 "Trying to get 'this' type from static method?");
1019
1020 // This is a lambda call operator that is being instantiated as a default
1021 // initializer. DC must point to the enclosing class type, so we can recover
1022 // the 'this' type from it.
1023
1024 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1025 // There are no cv-qualifiers for 'this' within default initializers,
1026 // per [expr.prim.general]p4.
1027 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001028 }
Faisal Vali67b04462016-06-11 16:41:54 +00001029
1030 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1031 // might need to be adjusted if the lambda or any of its enclosing lambda's
1032 // captures '*this' by copy.
1033 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1034 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1035 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001036 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001037}
1038
Simon Pilgrim75c26882016-09-30 14:25:09 +00001039Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001040 Decl *ContextDecl,
1041 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001042 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001043 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1044{
1045 if (!Enabled || !ContextDecl)
1046 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001047
1048 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001049 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1050 Record = Template->getTemplatedDecl();
1051 else
1052 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001053
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001054 // We care only for CVR qualifiers here, so cut everything else.
1055 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001056 S.CXXThisTypeOverride
1057 = S.Context.getPointerType(
1058 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001059
Douglas Gregor3024f072012-04-16 07:05:22 +00001060 this->Enabled = true;
1061}
1062
1063
1064Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1065 if (Enabled) {
1066 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1067 }
1068}
1069
Faisal Validc6b5962016-03-21 09:25:37 +00001070static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1071 QualType ThisTy, SourceLocation Loc,
1072 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001073
Faisal Vali67b04462016-06-11 16:41:54 +00001074 QualType AdjustedThisTy = ThisTy;
1075 // The type of the corresponding data member (not a 'this' pointer if 'by
1076 // copy').
1077 QualType CaptureThisFieldTy = ThisTy;
1078 if (ByCopy) {
1079 // If we are capturing the object referred to by '*this' by copy, ignore any
1080 // cv qualifiers inherited from the type of the member function for the type
1081 // of the closure-type's corresponding data member and any use of 'this'.
1082 CaptureThisFieldTy = ThisTy->getPointeeType();
1083 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1084 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1085 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001086
Faisal Vali67b04462016-06-11 16:41:54 +00001087 FieldDecl *Field = FieldDecl::Create(
1088 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1089 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1090 ICIS_NoInit);
1091
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001092 Field->setImplicit(true);
1093 Field->setAccess(AS_private);
1094 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001095 Expr *This =
1096 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001097 if (ByCopy) {
1098 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1099 UO_Deref,
1100 This).get();
1101 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001102 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001103 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1104 InitializationSequence Init(S, Entity, InitKind, StarThis);
1105 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1106 if (ER.isInvalid()) return nullptr;
1107 return ER.get();
1108 }
1109 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001110}
1111
Simon Pilgrim75c26882016-09-30 14:25:09 +00001112bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001113 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1114 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001115 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001116 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001117 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001118
Faisal Validc6b5962016-03-21 09:25:37 +00001119 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001120
Reid Kleckner87a31802018-03-12 21:43:02 +00001121 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1122 ? *FunctionScopeIndexToStopAt
1123 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001124
Simon Pilgrim75c26882016-09-30 14:25:09 +00001125 // Check that we can capture the *enclosing object* (referred to by '*this')
1126 // by the capturing-entity/closure (lambda/block/etc) at
1127 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1128
1129 // Note: The *enclosing object* can only be captured by-value by a
1130 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001131 // [*this] { ... }.
1132 // Every other capture of the *enclosing object* results in its by-reference
1133 // capture.
1134
1135 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1136 // stack), we can capture the *enclosing object* only if:
1137 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1138 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001139 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001140 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001141 // -- or, there is some enclosing closure 'E' that has already captured the
1142 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001143 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001144 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001145 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001146
1147
Faisal Validc6b5962016-03-21 09:25:37 +00001148 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001149 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001150 if (CapturingScopeInfo *CSI =
1151 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1152 if (CSI->CXXThisCaptureIndex != 0) {
1153 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001154 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001155 break;
1156 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001157 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1158 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1159 // This context can't implicitly capture 'this'; fail out.
1160 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001161 Diag(Loc, diag::err_this_capture)
1162 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001163 return true;
1164 }
Eli Friedman20139d32012-01-11 02:36:31 +00001165 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001166 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001167 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001168 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001169 (Explicit && idx == MaxFunctionScopesIndex)) {
1170 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1171 // iteration through can be an explicit capture, all enclosing closures,
1172 // if any, must perform implicit captures.
1173
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001174 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001175 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001176 continue;
1177 }
Eli Friedman20139d32012-01-11 02:36:31 +00001178 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001179 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001180 Diag(Loc, diag::err_this_capture)
1181 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001182 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001183 }
Eli Friedman73a04092012-01-07 04:59:52 +00001184 break;
1185 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001186 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001187
1188 // If we got here, then the closure at MaxFunctionScopesIndex on the
1189 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1190 // (including implicit by-reference captures in any enclosing closures).
1191
1192 // In the loop below, respect the ByCopy flag only for the closure requesting
1193 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001194 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001195 // implicitly capturing the *enclosing object* by reference (see loop
1196 // above)).
1197 assert((!ByCopy ||
1198 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1199 "Only a lambda can capture the enclosing object (referred to by "
1200 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001201 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1202 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001203 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001204 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1205 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001206 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001207 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001208
Faisal Validc6b5962016-03-21 09:25:37 +00001209 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1210 // For lambda expressions, build a field and an initializing expression,
1211 // and capture the *enclosing object* by copy only if this is the first
1212 // iteration.
1213 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1214 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001215
Faisal Validc6b5962016-03-21 09:25:37 +00001216 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001217 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001218 ThisExpr =
1219 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1220 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001221
Faisal Validc6b5962016-03-21 09:25:37 +00001222 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001223 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001224 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001225 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001226}
1227
Richard Smith938f40b2011-06-11 17:19:42 +00001228ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001229 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1230 /// is a non-lvalue expression whose value is the address of the object for
1231 /// which the function is called.
1232
Douglas Gregor09deffa2011-10-18 16:47:30 +00001233 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001234 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001235
Eli Friedman73a04092012-01-07 04:59:52 +00001236 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001237 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001238}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001239
Douglas Gregor3024f072012-04-16 07:05:22 +00001240bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1241 // If we're outside the body of a member function, then we'll have a specified
1242 // type for 'this'.
1243 if (CXXThisTypeOverride.isNull())
1244 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001245
Douglas Gregor3024f072012-04-16 07:05:22 +00001246 // Determine whether we're looking into a class that's currently being
1247 // defined.
1248 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1249 return Class && Class->isBeingDefined();
1250}
1251
Vedant Kumara14a1f92018-01-17 18:53:51 +00001252/// Parse construction of a specified type.
1253/// Can be interpreted either as function-style casting ("int(x)")
1254/// or class type construction ("ClassType(x,y,z)")
1255/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001256ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001257Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001258 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001259 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001260 SourceLocation RParenOrBraceLoc,
1261 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001262 if (!TypeRep)
1263 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
John McCall97513962010-01-15 18:39:57 +00001265 TypeSourceInfo *TInfo;
1266 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1267 if (!TInfo)
1268 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001269
Vedant Kumara14a1f92018-01-17 18:53:51 +00001270 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1271 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001272 // Avoid creating a non-type-dependent expression that contains typos.
1273 // Non-type-dependent expressions are liable to be discarded without
1274 // checking for embedded typos.
1275 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1276 !Result.get()->isTypeDependent())
1277 Result = CorrectDelayedTyposInExpr(Result.get());
1278 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001279}
1280
Douglas Gregor2b88c112010-09-08 00:15:04 +00001281ExprResult
1282Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001283 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001284 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001285 SourceLocation RParenOrBraceLoc,
1286 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001287 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001288 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001289
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001290 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001291 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1292 // directly. We work around this by dropping the locations of the braces.
1293 SourceRange Locs = ListInitialization
1294 ? SourceRange()
1295 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1296 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1297 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001298 }
1299
Richard Smith600b5262017-01-26 20:40:47 +00001300 assert((!ListInitialization ||
1301 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1302 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001303 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001304
Richard Smith60437622017-02-09 19:17:44 +00001305 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1306 InitializationKind Kind =
1307 Exprs.size()
1308 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001309 ? InitializationKind::CreateDirectList(
1310 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1311 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1312 RParenOrBraceLoc)
1313 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1314 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001315
1316 // C++1z [expr.type.conv]p1:
1317 // If the type is a placeholder for a deduced class type, [...perform class
1318 // template argument deduction...]
1319 DeducedType *Deduced = Ty->getContainedDeducedType();
1320 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1321 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1322 Kind, Exprs);
1323 if (Ty.isNull())
1324 return ExprError();
1325 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1326 }
1327
Douglas Gregordd04d332009-01-16 18:33:17 +00001328 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001329 // If the expression list is a parenthesized single expression, the type
1330 // conversion expression is equivalent (in definedness, and if defined in
1331 // meaning) to the corresponding cast expression.
1332 if (Exprs.size() == 1 && !ListInitialization &&
1333 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001334 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001335 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1336 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001337 }
1338
Richard Smith49a6b6e2017-03-24 01:14:25 +00001339 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001340 QualType ElemTy = Ty;
1341 if (Ty->isArrayType()) {
1342 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001343 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1344 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001345 ElemTy = Context.getBaseElementType(Ty);
1346 }
1347
Richard Smith49a6b6e2017-03-24 01:14:25 +00001348 // There doesn't seem to be an explicit rule against this but sanity demands
1349 // we only construct objects with object types.
1350 if (Ty->isFunctionType())
1351 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1352 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001353
Richard Smith49a6b6e2017-03-24 01:14:25 +00001354 // C++17 [expr.type.conv]p2:
1355 // If the type is cv void and the initializer is (), the expression is a
1356 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001357 if (!Ty->isVoidType() &&
1358 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001359 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001360 return ExprError();
1361
Richard Smith49a6b6e2017-03-24 01:14:25 +00001362 // Otherwise, the expression is a prvalue of the specified type whose
1363 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001364 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1365 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001366
Richard Smith49a6b6e2017-03-24 01:14:25 +00001367 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001368 return Result;
1369
1370 Expr *Inner = Result.get();
1371 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1372 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001373 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1374 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001375 // If we created a CXXTemporaryObjectExpr, that node also represents the
1376 // functional cast. Otherwise, create an explicit cast to represent
1377 // the syntactic form of a functional-style cast that was used here.
1378 //
1379 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1380 // would give a more consistent AST representation than using a
1381 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1382 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001383 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001384 SourceRange Locs = ListInitialization
1385 ? SourceRange()
1386 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001387 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001388 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1389 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001390 }
1391
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001392 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001393}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001394
Richard Smithb2f0f052016-10-10 18:54:32 +00001395/// \brief Determine whether the given function is a non-placement
1396/// deallocation function.
1397static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1399 return Method->isUsualDeallocationFunction();
1400
1401 if (FD->getOverloadedOperator() != OO_Delete &&
1402 FD->getOverloadedOperator() != OO_Array_Delete)
1403 return false;
1404
1405 unsigned UsualParams = 1;
1406
1407 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1408 S.Context.hasSameUnqualifiedType(
1409 FD->getParamDecl(UsualParams)->getType(),
1410 S.Context.getSizeType()))
1411 ++UsualParams;
1412
1413 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1414 S.Context.hasSameUnqualifiedType(
1415 FD->getParamDecl(UsualParams)->getType(),
1416 S.Context.getTypeDeclType(S.getStdAlignValT())))
1417 ++UsualParams;
1418
1419 return UsualParams == FD->getNumParams();
1420}
1421
1422namespace {
1423 struct UsualDeallocFnInfo {
1424 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001425 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001426 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001427 Destroying(false), HasSizeT(false), HasAlignValT(false),
1428 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001429 // A function template declaration is never a usual deallocation function.
1430 if (!FD)
1431 return;
Richard Smith5b349582017-10-13 01:55:36 +00001432 unsigned NumBaseParams = 1;
1433 if (FD->isDestroyingOperatorDelete()) {
1434 Destroying = true;
1435 ++NumBaseParams;
1436 }
1437 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001438 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001439 else if (FD->getNumParams() == NumBaseParams + 1) {
1440 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001441 HasAlignValT = !HasSizeT;
1442 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001443
1444 // In CUDA, determine how much we'd like / dislike to call this.
1445 if (S.getLangOpts().CUDA)
1446 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1447 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001448 }
1449
Eric Fiselierfa752f22018-03-21 19:19:48 +00001450 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001451
Richard Smithf75dcbe2016-10-11 00:21:10 +00001452 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1453 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001454 // C++ P0722:
1455 // A destroying operator delete is preferred over a non-destroying
1456 // operator delete.
1457 if (Destroying != Other.Destroying)
1458 return Destroying;
1459
Richard Smithf75dcbe2016-10-11 00:21:10 +00001460 // C++17 [expr.delete]p10:
1461 // If the type has new-extended alignment, a function with a parameter
1462 // of type std::align_val_t is preferred; otherwise a function without
1463 // such a parameter is preferred
1464 if (HasAlignValT != Other.HasAlignValT)
1465 return HasAlignValT == WantAlign;
1466
1467 if (HasSizeT != Other.HasSizeT)
1468 return HasSizeT == WantSize;
1469
1470 // Use CUDA call preference as a tiebreaker.
1471 return CUDAPref > Other.CUDAPref;
1472 }
1473
Richard Smithb2f0f052016-10-10 18:54:32 +00001474 DeclAccessPair Found;
1475 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001476 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001477 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001478 };
1479}
1480
1481/// Determine whether a type has new-extended alignment. This may be called when
1482/// the type is incomplete (for a delete-expression with an incomplete pointee
1483/// type), in which case it will conservatively return false if the alignment is
1484/// not known.
1485static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1486 return S.getLangOpts().AlignedAllocation &&
1487 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1488 S.getASTContext().getTargetInfo().getNewAlign();
1489}
1490
1491/// Select the correct "usual" deallocation function to use from a selection of
1492/// deallocation functions (either global or class-scope).
1493static UsualDeallocFnInfo resolveDeallocationOverload(
1494 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1495 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1496 UsualDeallocFnInfo Best;
1497
Richard Smithb2f0f052016-10-10 18:54:32 +00001498 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001499 UsualDeallocFnInfo Info(S, I.getPair());
1500 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1501 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001502 continue;
1503
1504 if (!Best) {
1505 Best = Info;
1506 if (BestFns)
1507 BestFns->push_back(Info);
1508 continue;
1509 }
1510
Richard Smithf75dcbe2016-10-11 00:21:10 +00001511 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001512 continue;
1513
1514 // If more than one preferred function is found, all non-preferred
1515 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001516 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001517 BestFns->clear();
1518
1519 Best = Info;
1520 if (BestFns)
1521 BestFns->push_back(Info);
1522 }
1523
1524 return Best;
1525}
1526
1527/// Determine whether a given type is a class for which 'delete[]' would call
1528/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1529/// we need to store the array size (even if the type is
1530/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001531static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1532 QualType allocType) {
1533 const RecordType *record =
1534 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1535 if (!record) return false;
1536
1537 // Try to find an operator delete[] in class scope.
1538
1539 DeclarationName deleteName =
1540 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1541 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1542 S.LookupQualifiedName(ops, record->getDecl());
1543
1544 // We're just doing this for information.
1545 ops.suppressDiagnostics();
1546
1547 // Very likely: there's no operator delete[].
1548 if (ops.empty()) return false;
1549
1550 // If it's ambiguous, it should be illegal to call operator delete[]
1551 // on this thing, so it doesn't matter if we allocate extra space or not.
1552 if (ops.isAmbiguous()) return false;
1553
Richard Smithb2f0f052016-10-10 18:54:32 +00001554 // C++17 [expr.delete]p10:
1555 // If the deallocation functions have class scope, the one without a
1556 // parameter of type std::size_t is selected.
1557 auto Best = resolveDeallocationOverload(
1558 S, ops, /*WantSize*/false,
1559 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1560 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001561}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001562
Sebastian Redld74dd492012-02-12 18:41:05 +00001563/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001564///
Sebastian Redld74dd492012-02-12 18:41:05 +00001565/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001566/// @code new (memory) int[size][4] @endcode
1567/// or
1568/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001569///
1570/// \param StartLoc The first location of the expression.
1571/// \param UseGlobal True if 'new' was prefixed with '::'.
1572/// \param PlacementLParen Opening paren of the placement arguments.
1573/// \param PlacementArgs Placement new arguments.
1574/// \param PlacementRParen Closing paren of the placement arguments.
1575/// \param TypeIdParens If the type is in parens, the source range.
1576/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001577/// \param Initializer The initializing expression or initializer-list, or null
1578/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001579ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001580Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001581 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001582 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001583 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001584 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001585 // If the specified type is an array, unwrap it and save the expression.
1586 if (D.getNumTypeObjects() > 0 &&
1587 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001588 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001589 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001590 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1591 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001592 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001593 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1594 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001595 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001596 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1597 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001598
Sebastian Redl351bb782008-12-02 14:43:59 +00001599 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001600 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001601 }
1602
Douglas Gregor73341c42009-09-11 00:18:58 +00001603 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001604 if (ArraySize) {
1605 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001606 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1607 break;
1608
1609 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1610 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001611 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001612 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001613 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1614 // shall be a converted constant expression (5.19) of type std::size_t
1615 // and shall evaluate to a strictly positive value.
1616 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1617 assert(IntWidth && "Builtin type of size 0?");
1618 llvm::APSInt Value(IntWidth);
1619 Array.NumElts
1620 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1621 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001622 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001623 } else {
1624 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001625 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001626 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001627 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001628 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001629 if (!Array.NumElts)
1630 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001631 }
1632 }
1633 }
1634 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001635
Craig Topperc3ec1492014-05-26 06:22:03 +00001636 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001637 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001638 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001639 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640
Sebastian Redl6047f072012-02-16 12:22:20 +00001641 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001642 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001643 DirectInitRange = List->getSourceRange();
1644
David Blaikie7b97aef2012-11-07 00:12:38 +00001645 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001646 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001647 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001648 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001649 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001650 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001651 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001652 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001653 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001654 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001655}
1656
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001657static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1658 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001659 if (!Init)
1660 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001661 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1662 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001663 if (isa<ImplicitValueInitExpr>(Init))
1664 return true;
1665 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1666 return !CCE->isListInitialization() &&
1667 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001668 else if (Style == CXXNewExpr::ListInit) {
1669 assert(isa<InitListExpr>(Init) &&
1670 "Shouldn't create list CXXConstructExprs for arrays.");
1671 return true;
1672 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001673 return false;
1674}
1675
Akira Hatanakacae83f72017-06-29 18:48:40 +00001676// Emit a diagnostic if an aligned allocation/deallocation function that is not
1677// implemented in the standard library is selected.
1678static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1679 SourceLocation Loc, bool IsDelete,
1680 Sema &S) {
1681 if (!S.getLangOpts().AlignedAllocationUnavailable)
1682 return;
1683
1684 // Return if there is a definition.
1685 if (FD.isDefined())
1686 return;
1687
1688 bool IsAligned = false;
1689 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001690 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1691 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1692 S.getASTContext().getTargetInfo().getPlatformName());
1693
Akira Hatanakacae83f72017-06-29 18:48:40 +00001694 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001695 << IsDelete << FD.getType().getAsString() << OSName
1696 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001697 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1698 }
1699}
1700
John McCalldadc5752010-08-24 06:29:42 +00001701ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001702Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001703 SourceLocation PlacementLParen,
1704 MultiExprArg PlacementArgs,
1705 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001706 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001707 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001708 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001709 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001710 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001711 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001712 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001713 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001714
Sebastian Redl6047f072012-02-16 12:22:20 +00001715 CXXNewExpr::InitializationStyle initStyle;
1716 if (DirectInitRange.isValid()) {
1717 assert(Initializer && "Have parens but no initializer.");
1718 initStyle = CXXNewExpr::CallInit;
1719 } else if (Initializer && isa<InitListExpr>(Initializer))
1720 initStyle = CXXNewExpr::ListInit;
1721 else {
1722 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1723 isa<CXXConstructExpr>(Initializer)) &&
1724 "Initializer expression that cannot have been implicitly created.");
1725 initStyle = CXXNewExpr::NoInit;
1726 }
1727
1728 Expr **Inits = &Initializer;
1729 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001730 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1731 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1732 Inits = List->getExprs();
1733 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001734 }
1735
Richard Smith60437622017-02-09 19:17:44 +00001736 // C++11 [expr.new]p15:
1737 // A new-expression that creates an object of type T initializes that
1738 // object as follows:
1739 InitializationKind Kind
1740 // - If the new-initializer is omitted, the object is default-
1741 // initialized (8.5); if no initialization is performed,
1742 // the object has indeterminate value
1743 = initStyle == CXXNewExpr::NoInit
1744 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1745 // - Otherwise, the new-initializer is interpreted according to the
1746 // initialization rules of 8.5 for direct-initialization.
1747 : initStyle == CXXNewExpr::ListInit
Vedant Kumara14a1f92018-01-17 18:53:51 +00001748 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1749 Initializer->getLocStart(),
1750 Initializer->getLocEnd())
Richard Smith60437622017-02-09 19:17:44 +00001751 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1752 DirectInitRange.getBegin(),
1753 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001754
Richard Smith60437622017-02-09 19:17:44 +00001755 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1756 auto *Deduced = AllocType->getContainedDeducedType();
1757 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1758 if (ArraySize)
1759 return ExprError(Diag(ArraySize->getExprLoc(),
1760 diag::err_deduced_class_template_compound_type)
1761 << /*array*/ 2 << ArraySize->getSourceRange());
1762
1763 InitializedEntity Entity
1764 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1765 AllocType = DeduceTemplateSpecializationFromInitializer(
1766 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1767 if (AllocType.isNull())
1768 return ExprError();
1769 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001770 bool Braced = (initStyle == CXXNewExpr::ListInit);
1771 if (NumInits == 1) {
1772 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1773 Inits = p->getInits();
1774 NumInits = p->getNumInits();
1775 Braced = true;
1776 }
1777 }
1778
Sebastian Redl6047f072012-02-16 12:22:20 +00001779 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001780 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1781 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001782 if (NumInits > 1) {
1783 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001784 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001785 diag::err_auto_new_ctor_multiple_expressions)
1786 << AllocType << TypeRange);
1787 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001788 if (Braced && !getLangOpts().CPlusPlus17)
1789 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1790 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001791 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001792 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001793 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001794 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001795 << AllocType << Deduce->getType()
1796 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001797 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001798 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001799 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001800 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001801
Douglas Gregorcda95f42010-05-16 16:01:03 +00001802 // Per C++0x [expr.new]p5, the type being constructed may be a
1803 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001804 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001805 if (const ConstantArrayType *Array
1806 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001807 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1808 Context.getSizeType(),
1809 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001810 AllocType = Array->getElementType();
1811 }
1812 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001813
Douglas Gregor3999e152010-10-06 16:00:31 +00001814 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1815 return ExprError();
1816
Craig Topperc3ec1492014-05-26 06:22:03 +00001817 if (initStyle == CXXNewExpr::ListInit &&
1818 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001819 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1820 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001821 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001822 }
1823
Simon Pilgrim75c26882016-09-30 14:25:09 +00001824 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001825 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001826 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1827 AllocType->isObjCLifetimeType()) {
1828 AllocType = Context.getLifetimeQualifiedType(AllocType,
1829 AllocType->getObjCARCImplicitLifetime());
1830 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001831
John McCall31168b02011-06-15 23:02:42 +00001832 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001833
John McCall5e77d762013-04-16 07:28:30 +00001834 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1835 ExprResult result = CheckPlaceholderExpr(ArraySize);
1836 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001837 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001838 }
Richard Smith8dd34252012-02-04 07:07:42 +00001839 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1840 // integral or enumeration type with a non-negative value."
1841 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1842 // enumeration type, or a class type for which a single non-explicit
1843 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001844 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001845 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001846 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001847 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001848 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001849 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001850 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1851
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001852 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1853 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001854
Simon Pilgrim75c26882016-09-30 14:25:09 +00001855 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001856 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001857 // Diagnose the compatibility of this conversion.
1858 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1859 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001860 } else {
1861 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1862 protected:
1863 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001864
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001865 public:
1866 SizeConvertDiagnoser(Expr *ArraySize)
1867 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1868 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001869
1870 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1871 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001872 return S.Diag(Loc, diag::err_array_size_not_integral)
1873 << S.getLangOpts().CPlusPlus11 << T;
1874 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001875
1876 SemaDiagnosticBuilder diagnoseIncomplete(
1877 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001878 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1879 << T << ArraySize->getSourceRange();
1880 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001881
1882 SemaDiagnosticBuilder diagnoseExplicitConv(
1883 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001884 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1885 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001886
1887 SemaDiagnosticBuilder noteExplicitConv(
1888 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001889 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1890 << ConvTy->isEnumeralType() << ConvTy;
1891 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001892
1893 SemaDiagnosticBuilder diagnoseAmbiguous(
1894 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001895 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1896 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001897
1898 SemaDiagnosticBuilder noteAmbiguous(
1899 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001900 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1901 << ConvTy->isEnumeralType() << ConvTy;
1902 }
Richard Smithccc11812013-05-21 19:05:48 +00001903
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001904 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1905 QualType T,
1906 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001907 return S.Diag(Loc,
1908 S.getLangOpts().CPlusPlus11
1909 ? diag::warn_cxx98_compat_array_size_conversion
1910 : diag::ext_array_size_conversion)
1911 << T << ConvTy->isEnumeralType() << ConvTy;
1912 }
1913 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001914
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001915 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1916 SizeDiagnoser);
1917 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001918 if (ConvertedSize.isInvalid())
1919 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001921 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001922 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001923
Douglas Gregor0bf31402010-10-08 23:50:27 +00001924 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001925 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001927 // C++98 [expr.new]p7:
1928 // The expression in a direct-new-declarator shall have integral type
1929 // with a non-negative value.
1930 //
Richard Smith0511d232016-10-05 22:41:02 +00001931 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1932 // per CWG1464. Otherwise, if it's not a constant, we must have an
1933 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001934 if (!ArraySize->isValueDependent()) {
1935 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001936 // We've already performed any required implicit conversion to integer or
1937 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001938 // FIXME: Per CWG1464, we are required to check the value prior to
1939 // converting to size_t. This will never find a negative array size in
1940 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001941 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001942 if (Value.isSigned() && Value.isNegative()) {
1943 return ExprError(Diag(ArraySize->getLocStart(),
1944 diag::err_typecheck_negative_array_size)
1945 << ArraySize->getSourceRange());
1946 }
1947
1948 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001949 unsigned ActiveSizeBits =
1950 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001951 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1952 return ExprError(Diag(ArraySize->getLocStart(),
1953 diag::err_array_too_large)
1954 << Value.toString(10)
1955 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001956 }
Richard Smith0511d232016-10-05 22:41:02 +00001957
1958 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001959 } else if (TypeIdParens.isValid()) {
1960 // Can't have dynamic array size when the type-id is in parentheses.
1961 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1962 << ArraySize->getSourceRange()
1963 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1964 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
Douglas Gregorf2753b32010-07-13 15:54:32 +00001966 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001967 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969
John McCall036f2f62011-05-15 07:14:44 +00001970 // Note that we do *not* convert the argument in any way. It can
1971 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001972 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001973
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 FunctionDecl *OperatorNew = nullptr;
1975 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001976 unsigned Alignment =
1977 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1978 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1979 bool PassAlignment = getLangOpts().AlignedAllocation &&
1980 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981
Brian Gesiakcb024022018-04-01 22:59:22 +00001982 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001983 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001984 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001985 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001986 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00001987 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00001988 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001989 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001990
1991 // If this is an array allocation, compute whether the usual array
1992 // deallocation function for the type has a size_t parameter.
1993 bool UsualArrayDeleteWantsSize = false;
1994 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001995 UsualArrayDeleteWantsSize =
1996 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001997
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001998 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001999 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002001 OperatorNew->getType()->getAs<FunctionProtoType>();
2002 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2003 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
Richard Smithd6f9e732014-05-13 19:56:21 +00002005 // We've already converted the placement args, just fill in any default
2006 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002007 // argument. Skip the second parameter too if we're passing in the
2008 // alignment; we've already filled it in.
2009 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2010 PassAlignment ? 2 : 1, PlacementArgs,
2011 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002012 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002013
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002014 if (!AllPlaceArgs.empty())
2015 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002016
Richard Smithd6f9e732014-05-13 19:56:21 +00002017 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002018 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002019
2020 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
Richard Smithb2f0f052016-10-10 18:54:32 +00002022 // Warn if the type is over-aligned and is being allocated by (unaligned)
2023 // global operator new.
2024 if (PlacementArgs.empty() && !PassAlignment &&
2025 (OperatorNew->isImplicit() ||
2026 (OperatorNew->getLocStart().isValid() &&
2027 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2028 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002029 Diag(StartLoc, diag::warn_overaligned_type)
2030 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002031 << unsigned(Alignment / Context.getCharWidth())
2032 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002033 }
2034 }
2035
Sebastian Redl6047f072012-02-16 12:22:20 +00002036 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002037 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2038 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002039 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2040 SourceRange InitRange(Inits[0]->getLocStart(),
2041 Inits[NumInits - 1]->getLocEnd());
2042 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2043 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002044 }
2045
Richard Smithdd2ca572012-11-26 08:32:48 +00002046 // If we can perform the initialization, and we've not already done so,
2047 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002048 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002049 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002050 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002051 // The type we initialize is the complete type, including the array bound.
2052 QualType InitType;
2053 if (KnownArraySize)
2054 InitType = Context.getConstantArrayType(
2055 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2056 *KnownArraySize),
2057 ArrayType::Normal, 0);
2058 else if (ArraySize)
2059 InitType =
2060 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2061 else
2062 InitType = AllocType;
2063
Douglas Gregor85dabae2009-12-16 01:38:02 +00002064 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002065 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002066 InitializationSequence InitSeq(*this, Entity, Kind,
2067 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002069 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002070 if (FullInit.isInvalid())
2071 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
Sebastian Redl6047f072012-02-16 12:22:20 +00002073 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2074 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002075 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002076 if (CXXBindTemporaryExpr *Binder =
2077 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002078 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002080 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Douglas Gregor6642ca22010-02-26 05:06:18 +00002083 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002084 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002085 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2086 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002087 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002088 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002089 }
2090 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002091 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2092 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002093 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002094 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002095 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002096
John McCall928a2572011-07-13 20:12:57 +00002097 // C++0x [expr.new]p17:
2098 // If the new expression creates an array of objects of class type,
2099 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002100 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2101 if (ArraySize && !BaseAllocType->isDependentType()) {
2102 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2103 if (CXXDestructorDecl *dtor = LookupDestructor(
2104 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2105 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002106 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002107 PDiag(diag::err_access_dtor)
2108 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002109 if (DiagnoseUseOfDecl(dtor, StartLoc))
2110 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002111 }
John McCall928a2572011-07-13 20:12:57 +00002112 }
2113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002115 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002116 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002117 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2118 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2119 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002120}
2121
Sebastian Redl6047f072012-02-16 12:22:20 +00002122/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002123/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002124bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002125 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002126 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2127 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002128 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002129 return Diag(Loc, diag::err_bad_new_type)
2130 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002131 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002132 return Diag(Loc, diag::err_bad_new_type)
2133 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002134 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002135 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002136 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002137 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002138 diag::err_allocation_of_abstract_type))
2139 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002140 else if (AllocType->isVariablyModifiedType())
2141 return Diag(Loc, diag::err_variably_modified_new_type)
2142 << AllocType;
Alexander Richardson6d989432017-10-15 18:48:14 +00002143 else if (AllocType.getAddressSpace() != LangAS::Default)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002144 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002145 << AllocType.getUnqualifiedType()
2146 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002147 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002148 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2149 QualType BaseAllocType = Context.getBaseElementType(AT);
2150 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2151 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002152 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002153 << BaseAllocType;
2154 }
2155 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002156
Sebastian Redlbd150f42008-11-21 19:14:01 +00002157 return false;
2158}
2159
Brian Gesiak87412d92018-02-15 20:09:25 +00002160static bool resolveAllocationOverload(
2161 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2162 bool &PassAlignment, FunctionDecl *&Operator,
2163 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002164 OverloadCandidateSet Candidates(R.getNameLoc(),
2165 OverloadCandidateSet::CSK_Normal);
2166 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2167 Alloc != AllocEnd; ++Alloc) {
2168 // Even member operator new/delete are implicitly treated as
2169 // static, so don't use AddMemberCandidate.
2170 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2171
2172 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2173 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2174 /*ExplicitTemplateArgs=*/nullptr, Args,
2175 Candidates,
2176 /*SuppressUserConversions=*/false);
2177 continue;
2178 }
2179
2180 FunctionDecl *Fn = cast<FunctionDecl>(D);
2181 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2182 /*SuppressUserConversions=*/false);
2183 }
2184
2185 // Do the resolution.
2186 OverloadCandidateSet::iterator Best;
2187 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2188 case OR_Success: {
2189 // Got one!
2190 FunctionDecl *FnDecl = Best->Function;
2191 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2192 Best->FoundDecl) == Sema::AR_inaccessible)
2193 return true;
2194
2195 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002196 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002197 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002198
Richard Smithb2f0f052016-10-10 18:54:32 +00002199 case OR_No_Viable_Function:
2200 // C++17 [expr.new]p13:
2201 // If no matching function is found and the allocated object type has
2202 // new-extended alignment, the alignment argument is removed from the
2203 // argument list, and overload resolution is performed again.
2204 if (PassAlignment) {
2205 PassAlignment = false;
2206 AlignArg = Args[1];
2207 Args.erase(Args.begin() + 1);
2208 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002209 Operator, &Candidates, AlignArg,
2210 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002211 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002212
Richard Smithb2f0f052016-10-10 18:54:32 +00002213 // MSVC will fall back on trying to find a matching global operator new
2214 // if operator new[] cannot be found. Also, MSVC will leak by not
2215 // generating a call to operator delete or operator delete[], but we
2216 // will not replicate that bug.
2217 // FIXME: Find out how this interacts with the std::align_val_t fallback
2218 // once MSVC implements it.
2219 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2220 S.Context.getLangOpts().MSVCCompat) {
2221 R.clear();
2222 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2223 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2224 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2225 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002226 Operator, /*Candidates=*/nullptr,
2227 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002228 }
Richard Smith1cdec012013-09-29 04:40:38 +00002229
Brian Gesiak87412d92018-02-15 20:09:25 +00002230 if (Diagnose) {
2231 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2232 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002233
Brian Gesiak87412d92018-02-15 20:09:25 +00002234 // If we have aligned candidates, only note the align_val_t candidates
2235 // from AlignedCandidates and the non-align_val_t candidates from
2236 // Candidates.
2237 if (AlignedCandidates) {
2238 auto IsAligned = [](OverloadCandidate &C) {
2239 return C.Function->getNumParams() > 1 &&
2240 C.Function->getParamDecl(1)->getType()->isAlignValT();
2241 };
2242 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002243
Brian Gesiak87412d92018-02-15 20:09:25 +00002244 // This was an overaligned allocation, so list the aligned candidates
2245 // first.
2246 Args.insert(Args.begin() + 1, AlignArg);
2247 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2248 R.getNameLoc(), IsAligned);
2249 Args.erase(Args.begin() + 1);
2250 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2251 IsUnaligned);
2252 } else {
2253 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2254 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002255 }
Richard Smith1cdec012013-09-29 04:40:38 +00002256 return true;
2257
Richard Smithb2f0f052016-10-10 18:54:32 +00002258 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002259 if (Diagnose) {
2260 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2261 << R.getLookupName() << Range;
2262 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2263 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002264 return true;
2265
2266 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002267 if (Diagnose) {
2268 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2269 << Best->Function->isDeleted() << R.getLookupName()
2270 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2271 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2272 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002273 return true;
2274 }
2275 }
2276 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002277}
2278
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002279bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002280 AllocationFunctionScope NewScope,
2281 AllocationFunctionScope DeleteScope,
2282 QualType AllocType, bool IsArray,
2283 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002284 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002285 FunctionDecl *&OperatorDelete,
2286 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002287 // --- Choosing an allocation function ---
2288 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002289 // 1) If looking in AFS_Global scope for allocation functions, only look in
2290 // the global scope. Else, if AFS_Class, only look in the scope of the
2291 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002292 // 2) If an array size is given, look for operator new[], else look for
2293 // operator new.
2294 // 3) The first argument is always size_t. Append the arguments from the
2295 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002296
Richard Smithb2f0f052016-10-10 18:54:32 +00002297 SmallVector<Expr*, 8> AllocArgs;
2298 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2299
2300 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002301 // FIXME: Should the Sema create the expression and embed it in the syntax
2302 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002303 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002304 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002305 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002306 Context.getSizeType(),
2307 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002308 AllocArgs.push_back(&Size);
2309
2310 QualType AlignValT = Context.VoidTy;
2311 if (PassAlignment) {
2312 DeclareGlobalNewDelete();
2313 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2314 }
2315 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2316 if (PassAlignment)
2317 AllocArgs.push_back(&Align);
2318
2319 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002320
Douglas Gregor6642ca22010-02-26 05:06:18 +00002321 // C++ [expr.new]p8:
2322 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002323 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002324 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002325 // type, the allocation function's name is operator new[] and the
2326 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002327 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002328 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002329
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002330 QualType AllocElemType = Context.getBaseElementType(AllocType);
2331
Richard Smithb2f0f052016-10-10 18:54:32 +00002332 // Find the allocation function.
2333 {
2334 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2335
2336 // C++1z [expr.new]p9:
2337 // If the new-expression begins with a unary :: operator, the allocation
2338 // function's name is looked up in the global scope. Otherwise, if the
2339 // allocated type is a class type T or array thereof, the allocation
2340 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002341 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002342 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2343
2344 // We can see ambiguity here if the allocation function is found in
2345 // multiple base classes.
2346 if (R.isAmbiguous())
2347 return true;
2348
2349 // If this lookup fails to find the name, or if the allocated type is not
2350 // a class type, the allocation function's name is looked up in the
2351 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002352 if (R.empty()) {
2353 if (NewScope == AFS_Class)
2354 return true;
2355
Richard Smithb2f0f052016-10-10 18:54:32 +00002356 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002357 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002358
2359 assert(!R.empty() && "implicitly declared allocation functions not found");
2360 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2361
2362 // We do our own custom access checks below.
2363 R.suppressDiagnostics();
2364
2365 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002366 OperatorNew, /*Candidates=*/nullptr,
2367 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002368 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002369 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002370
Richard Smithb2f0f052016-10-10 18:54:32 +00002371 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002372 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002373 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002374 return false;
2375 }
2376
Richard Smithb2f0f052016-10-10 18:54:32 +00002377 // Note, the name of OperatorNew might have been changed from array to
2378 // non-array by resolveAllocationOverload.
2379 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2380 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2381 ? OO_Array_Delete
2382 : OO_Delete);
2383
Douglas Gregor6642ca22010-02-26 05:06:18 +00002384 // C++ [expr.new]p19:
2385 //
2386 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002387 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002388 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002389 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002390 // the scope of T. If this lookup fails to find the name, or if
2391 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002392 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002393 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002394 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002395 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002396 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002397 LookupQualifiedName(FoundDelete, RD);
2398 }
John McCallfb6f5262010-03-18 08:19:33 +00002399 if (FoundDelete.isAmbiguous())
2400 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002401
Richard Smithb2f0f052016-10-10 18:54:32 +00002402 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002403 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002404 if (DeleteScope == AFS_Class)
2405 return true;
2406
Douglas Gregor6642ca22010-02-26 05:06:18 +00002407 DeclareGlobalNewDelete();
2408 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2409 }
2410
2411 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002412
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002413 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002414
John McCalld3be2c82010-09-14 21:34:24 +00002415 // Whether we're looking for a placement operator delete is dictated
2416 // by whether we selected a placement operator new, not by whether
2417 // we had explicit placement arguments. This matters for things like
2418 // struct A { void *operator new(size_t, int = 0); ... };
2419 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002420 //
2421 // We don't have any definition for what a "placement allocation function"
2422 // is, but we assume it's any allocation function whose
2423 // parameter-declaration-clause is anything other than (size_t).
2424 //
2425 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2426 // This affects whether an exception from the constructor of an overaligned
2427 // type uses the sized or non-sized form of aligned operator delete.
2428 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2429 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002430
2431 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002432 // C++ [expr.new]p20:
2433 // A declaration of a placement deallocation function matches the
2434 // declaration of a placement allocation function if it has the
2435 // same number of parameters and, after parameter transformations
2436 // (8.3.5), all parameter types except the first are
2437 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002439 // To perform this comparison, we compute the function type that
2440 // the deallocation function should have, and use that type both
2441 // for template argument deduction and for comparison purposes.
2442 QualType ExpectedFunctionType;
2443 {
2444 const FunctionProtoType *Proto
2445 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002446
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002447 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002449 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2450 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002451
John McCalldb40c7f2010-12-14 08:05:40 +00002452 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002453 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002454 EPI.Variadic = Proto->isVariadic();
2455
Douglas Gregor6642ca22010-02-26 05:06:18 +00002456 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002457 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002458 }
2459
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002461 DEnd = FoundDelete.end();
2462 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002463 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002464 if (FunctionTemplateDecl *FnTmpl =
2465 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002466 // Perform template argument deduction to try to match the
2467 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002468 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002469 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2470 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002471 continue;
2472 } else
2473 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2474
Richard Smithbaa47832016-12-01 02:11:49 +00002475 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2476 ExpectedFunctionType,
2477 /*AdjustExcpetionSpec*/true),
2478 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002479 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002480 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002481
Richard Smithb2f0f052016-10-10 18:54:32 +00002482 if (getLangOpts().CUDA)
2483 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2484 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002485 // C++1y [expr.new]p22:
2486 // For a non-placement allocation function, the normal deallocation
2487 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002488 //
2489 // Per [expr.delete]p10, this lookup prefers a member operator delete
2490 // without a size_t argument, but prefers a non-member operator delete
2491 // with a size_t where possible (which it always is in this case).
2492 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2493 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2494 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2495 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2496 &BestDeallocFns);
2497 if (Selected)
2498 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2499 else {
2500 // If we failed to select an operator, all remaining functions are viable
2501 // but ambiguous.
2502 for (auto Fn : BestDeallocFns)
2503 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002504 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002505 }
2506
2507 // C++ [expr.new]p20:
2508 // [...] If the lookup finds a single matching deallocation
2509 // function, that function will be called; otherwise, no
2510 // deallocation function will be called.
2511 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002512 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002513
Richard Smithb2f0f052016-10-10 18:54:32 +00002514 // C++1z [expr.new]p23:
2515 // If the lookup finds a usual deallocation function (3.7.4.2)
2516 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002517 // as a placement deallocation function, would have been
2518 // selected as a match for the allocation function, the program
2519 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002520 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002521 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002522 UsualDeallocFnInfo Info(*this,
2523 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002524 // Core issue, per mail to core reflector, 2016-10-09:
2525 // If this is a member operator delete, and there is a corresponding
2526 // non-sized member operator delete, this isn't /really/ a sized
2527 // deallocation function, it just happens to have a size_t parameter.
2528 bool IsSizedDelete = Info.HasSizeT;
2529 if (IsSizedDelete && !FoundGlobalDelete) {
2530 auto NonSizedDelete =
2531 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2532 /*WantAlign*/Info.HasAlignValT);
2533 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2534 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2535 IsSizedDelete = false;
2536 }
2537
2538 if (IsSizedDelete) {
2539 SourceRange R = PlaceArgs.empty()
2540 ? SourceRange()
2541 : SourceRange(PlaceArgs.front()->getLocStart(),
2542 PlaceArgs.back()->getLocEnd());
2543 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2544 if (!OperatorDelete->isImplicit())
2545 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2546 << DeleteName;
2547 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002548 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002549
2550 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2551 Matches[0].first);
2552 } else if (!Matches.empty()) {
2553 // We found multiple suitable operators. Per [expr.new]p20, that means we
2554 // call no 'operator delete' function, but we should at least warn the user.
2555 // FIXME: Suppress this warning if the construction cannot throw.
2556 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2557 << DeleteName << AllocElemType;
2558
2559 for (auto &Match : Matches)
2560 Diag(Match.second->getLocation(),
2561 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002562 }
2563
Sebastian Redlfaf68082008-12-03 20:26:15 +00002564 return false;
2565}
2566
2567/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2568/// delete. These are:
2569/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002570/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002571/// void* operator new(std::size_t) throw(std::bad_alloc);
2572/// void* operator new[](std::size_t) throw(std::bad_alloc);
2573/// void operator delete(void *) throw();
2574/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002575/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002576/// void* operator new(std::size_t);
2577/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002578/// void operator delete(void *) noexcept;
2579/// void operator delete[](void *) noexcept;
2580/// // C++1y:
2581/// void* operator new(std::size_t);
2582/// void* operator new[](std::size_t);
2583/// void operator delete(void *) noexcept;
2584/// void operator delete[](void *) noexcept;
2585/// void operator delete(void *, std::size_t) noexcept;
2586/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002587/// @endcode
2588/// Note that the placement and nothrow forms of new are *not* implicitly
2589/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002590void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002591 if (GlobalNewDeleteDeclared)
2592 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002593
Douglas Gregor87f54062009-09-15 22:30:29 +00002594 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 // [...] The following allocation and deallocation functions (18.4) are
2596 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002597 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002598 //
Sebastian Redl37588092011-03-14 18:08:30 +00002599 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002600 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002601 // void* operator new[](std::size_t) throw(std::bad_alloc);
2602 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002603 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002604 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002605 // void* operator new(std::size_t);
2606 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002607 // void operator delete(void*) noexcept;
2608 // void operator delete[](void*) noexcept;
2609 // C++1y:
2610 // void* operator new(std::size_t);
2611 // void* operator new[](std::size_t);
2612 // void operator delete(void*) noexcept;
2613 // void operator delete[](void*) noexcept;
2614 // void operator delete(void*, std::size_t) noexcept;
2615 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002616 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002618 // new, operator new[], operator delete, operator delete[].
2619 //
2620 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2621 // "std" or "bad_alloc" as necessary to form the exception specification.
2622 // However, we do not make these implicit declarations visible to name
2623 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002624 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002625 // The "std::bad_alloc" class has not yet been declared, so build it
2626 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002627 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2628 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002629 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002630 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002631 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002632 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002633 }
Richard Smith59139022016-09-30 22:41:36 +00002634 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002635 // The "std::align_val_t" enum class has not yet been declared, so build it
2636 // implicitly.
2637 auto *AlignValT = EnumDecl::Create(
2638 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2639 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2640 AlignValT->setIntegerType(Context.getSizeType());
2641 AlignValT->setPromotionType(Context.getSizeType());
2642 AlignValT->setImplicit(true);
2643 StdAlignValT = AlignValT;
2644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002645
Sebastian Redlfaf68082008-12-03 20:26:15 +00002646 GlobalNewDeleteDeclared = true;
2647
2648 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2649 QualType SizeT = Context.getSizeType();
2650
Richard Smith96269c52016-09-29 22:49:46 +00002651 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2652 QualType Return, QualType Param) {
2653 llvm::SmallVector<QualType, 3> Params;
2654 Params.push_back(Param);
2655
2656 // Create up to four variants of the function (sized/aligned).
2657 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2658 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002659 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002660
2661 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2662 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2663 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002664 if (Sized)
2665 Params.push_back(SizeT);
2666
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002667 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002668 if (Aligned)
2669 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2670
2671 DeclareGlobalAllocationFunction(
2672 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2673
2674 if (Aligned)
2675 Params.pop_back();
2676 }
2677 }
2678 };
2679
2680 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2681 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2682 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2683 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002684}
2685
2686/// DeclareGlobalAllocationFunction - Declares a single implicit global
2687/// allocation function if it doesn't already exist.
2688void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002689 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002690 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002691 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2692
2693 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002694 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2695 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2696 Alloc != AllocEnd; ++Alloc) {
2697 // Only look at non-template functions, as it is the predefined,
2698 // non-templated allocation function we are trying to declare here.
2699 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002700 if (Func->getNumParams() == Params.size()) {
2701 llvm::SmallVector<QualType, 3> FuncParams;
2702 for (auto *P : Func->parameters())
2703 FuncParams.push_back(
2704 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2705 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002706 // Make the function visible to name lookup, even if we found it in
2707 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002708 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002709 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002710 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002711 }
Chandler Carruth93538422010-02-03 11:02:14 +00002712 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002713 }
2714 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002715
Richard Smithc015bc22014-02-07 22:39:53 +00002716 FunctionProtoType::ExtProtoInfo EPI;
2717
Richard Smithf8b417c2014-02-08 00:42:45 +00002718 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002719 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002720 = (Name.getCXXOverloadedOperator() == OO_New ||
2721 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002722 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002723 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002724 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002725 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002726 EPI.ExceptionSpec.Type = EST_Dynamic;
2727 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002728 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002729 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002730 EPI.ExceptionSpec =
2731 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002733
Artem Belevich07db5cf2016-10-21 20:34:05 +00002734 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2735 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2736 FunctionDecl *Alloc = FunctionDecl::Create(
2737 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2738 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2739 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002740 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002741 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002742
Artem Belevich07db5cf2016-10-21 20:34:05 +00002743 // Implicit sized deallocation functions always have default visibility.
2744 Alloc->addAttr(
2745 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
Artem Belevich07db5cf2016-10-21 20:34:05 +00002747 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2748 for (QualType T : Params) {
2749 ParamDecls.push_back(ParmVarDecl::Create(
2750 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2751 /*TInfo=*/nullptr, SC_None, nullptr));
2752 ParamDecls.back()->setImplicit();
2753 }
2754 Alloc->setParams(ParamDecls);
2755 if (ExtraAttr)
2756 Alloc->addAttr(ExtraAttr);
2757 Context.getTranslationUnitDecl()->addDecl(Alloc);
2758 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2759 };
2760
2761 if (!LangOpts.CUDA)
2762 CreateAllocationFunctionDecl(nullptr);
2763 else {
2764 // Host and device get their own declaration so each can be
2765 // defined or re-declared independently.
2766 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2767 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002768 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002769}
2770
Richard Smith1cdec012013-09-29 04:40:38 +00002771FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2772 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002773 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002774 DeclarationName Name) {
2775 DeclareGlobalNewDelete();
2776
2777 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2778 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2779
Richard Smithb2f0f052016-10-10 18:54:32 +00002780 // FIXME: It's possible for this to result in ambiguity, through a
2781 // user-declared variadic operator delete or the enable_if attribute. We
2782 // should probably not consider those cases to be usual deallocation
2783 // functions. But for now we just make an arbitrary choice in that case.
2784 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2785 Overaligned);
2786 assert(Result.FD && "operator delete missing from global scope?");
2787 return Result.FD;
2788}
Richard Smith1cdec012013-09-29 04:40:38 +00002789
Richard Smithb2f0f052016-10-10 18:54:32 +00002790FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2791 CXXRecordDecl *RD) {
2792 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002793
Richard Smithb2f0f052016-10-10 18:54:32 +00002794 FunctionDecl *OperatorDelete = nullptr;
2795 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2796 return nullptr;
2797 if (OperatorDelete)
2798 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002799
Richard Smithb2f0f052016-10-10 18:54:32 +00002800 // If there's no class-specific operator delete, look up the global
2801 // non-array delete.
2802 return FindUsualDeallocationFunction(
2803 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2804 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002805}
2806
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002807bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2808 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002809 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002810 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002811 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002812 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813
John McCall27b18f82009-11-17 02:14:36 +00002814 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002815 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002816
Chandler Carruthb6f99172010-06-28 00:30:51 +00002817 Found.suppressDiagnostics();
2818
Richard Smithb2f0f052016-10-10 18:54:32 +00002819 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002820
Richard Smithb2f0f052016-10-10 18:54:32 +00002821 // C++17 [expr.delete]p10:
2822 // If the deallocation functions have class scope, the one without a
2823 // parameter of type std::size_t is selected.
2824 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2825 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2826 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002827
Richard Smithb2f0f052016-10-10 18:54:32 +00002828 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002829 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002830 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002831
Richard Smithb2f0f052016-10-10 18:54:32 +00002832 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002833 if (Operator->isDeleted()) {
2834 if (Diagnose) {
2835 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002836 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002837 }
2838 return true;
2839 }
2840
Richard Smith921bd202012-02-26 09:11:52 +00002841 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002842 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002843 return true;
2844
John McCall66a87592010-08-04 00:31:26 +00002845 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002846 }
John McCall66a87592010-08-04 00:31:26 +00002847
Richard Smithb2f0f052016-10-10 18:54:32 +00002848 // We found multiple suitable operators; complain about the ambiguity.
2849 // FIXME: The standard doesn't say to do this; it appears that the intent
2850 // is that this should never happen.
2851 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002852 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002853 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2854 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002855 for (auto &Match : Matches)
2856 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002857 }
John McCall66a87592010-08-04 00:31:26 +00002858 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002859 }
2860
2861 // We did find operator delete/operator delete[] declarations, but
2862 // none of them were suitable.
2863 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002864 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002865 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2866 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
Richard Smithb2f0f052016-10-10 18:54:32 +00002868 for (NamedDecl *D : Found)
2869 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002870 diag::note_member_declared_here) << Name;
2871 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002872 return true;
2873 }
2874
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002876 return false;
2877}
2878
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002879namespace {
2880/// \brief Checks whether delete-expression, and new-expression used for
2881/// initializing deletee have the same array form.
2882class MismatchingNewDeleteDetector {
2883public:
2884 enum MismatchResult {
2885 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2886 NoMismatch,
2887 /// Indicates that variable is initialized with mismatching form of \a new.
2888 VarInitMismatches,
2889 /// Indicates that member is initialized with mismatching form of \a new.
2890 MemberInitMismatches,
2891 /// Indicates that 1 or more constructors' definitions could not been
2892 /// analyzed, and they will be checked again at the end of translation unit.
2893 AnalyzeLater
2894 };
2895
2896 /// \param EndOfTU True, if this is the final analysis at the end of
2897 /// translation unit. False, if this is the initial analysis at the point
2898 /// delete-expression was encountered.
2899 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002900 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002901 HasUndefinedConstructors(false) {}
2902
2903 /// \brief Checks whether pointee of a delete-expression is initialized with
2904 /// matching form of new-expression.
2905 ///
2906 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2907 /// point where delete-expression is encountered, then a warning will be
2908 /// issued immediately. If return value is \c AnalyzeLater at the point where
2909 /// delete-expression is seen, then member will be analyzed at the end of
2910 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2911 /// couldn't be analyzed. If at least one constructor initializes the member
2912 /// with matching type of new, the return value is \c NoMismatch.
2913 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2914 /// \brief Analyzes a class member.
2915 /// \param Field Class member to analyze.
2916 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2917 /// for deleting the \p Field.
2918 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002919 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002920 /// List of mismatching new-expressions used for initialization of the pointee
2921 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2922 /// Indicates whether delete-expression was in array form.
2923 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002924
2925private:
2926 const bool EndOfTU;
2927 /// \brief Indicates that there is at least one constructor without body.
2928 bool HasUndefinedConstructors;
2929 /// \brief Returns \c CXXNewExpr from given initialization expression.
2930 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002931 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002932 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2933 /// \brief Returns whether member is initialized with mismatching form of
2934 /// \c new either by the member initializer or in-class initialization.
2935 ///
2936 /// If bodies of all constructors are not visible at the end of translation
2937 /// unit or at least one constructor initializes member with the matching
2938 /// form of \c new, mismatch cannot be proven, and this function will return
2939 /// \c NoMismatch.
2940 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2941 /// \brief Returns whether variable is initialized with mismatching form of
2942 /// \c new.
2943 ///
2944 /// If variable is initialized with matching form of \c new or variable is not
2945 /// initialized with a \c new expression, this function will return true.
2946 /// If variable is initialized with mismatching form of \c new, returns false.
2947 /// \param D Variable to analyze.
2948 bool hasMatchingVarInit(const DeclRefExpr *D);
2949 /// \brief Checks whether the constructor initializes pointee with mismatching
2950 /// form of \c new.
2951 ///
2952 /// Returns true, if member is initialized with matching form of \c new in
2953 /// member initializer list. Returns false, if member is initialized with the
2954 /// matching form of \c new in this constructor's initializer or given
2955 /// constructor isn't defined at the point where delete-expression is seen, or
2956 /// member isn't initialized by the constructor.
2957 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2958 /// \brief Checks whether member is initialized with matching form of
2959 /// \c new in member initializer list.
2960 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2961 /// Checks whether member is initialized with mismatching form of \c new by
2962 /// in-class initializer.
2963 MismatchResult analyzeInClassInitializer();
2964};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002965}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002966
2967MismatchingNewDeleteDetector::MismatchResult
2968MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2969 NewExprs.clear();
2970 assert(DE && "Expected delete-expression");
2971 IsArrayForm = DE->isArrayForm();
2972 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2973 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2974 return analyzeMemberExpr(ME);
2975 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2976 if (!hasMatchingVarInit(D))
2977 return VarInitMismatches;
2978 }
2979 return NoMismatch;
2980}
2981
2982const CXXNewExpr *
2983MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2984 assert(E != nullptr && "Expected a valid initializer expression");
2985 E = E->IgnoreParenImpCasts();
2986 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2987 if (ILE->getNumInits() == 1)
2988 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2989 }
2990
2991 return dyn_cast_or_null<const CXXNewExpr>(E);
2992}
2993
2994bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2995 const CXXCtorInitializer *CI) {
2996 const CXXNewExpr *NE = nullptr;
2997 if (Field == CI->getMember() &&
2998 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2999 if (NE->isArray() == IsArrayForm)
3000 return true;
3001 else
3002 NewExprs.push_back(NE);
3003 }
3004 return false;
3005}
3006
3007bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3008 const CXXConstructorDecl *CD) {
3009 if (CD->isImplicit())
3010 return false;
3011 const FunctionDecl *Definition = CD;
3012 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3013 HasUndefinedConstructors = true;
3014 return EndOfTU;
3015 }
3016 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3017 if (hasMatchingNewInCtorInit(CI))
3018 return true;
3019 }
3020 return false;
3021}
3022
3023MismatchingNewDeleteDetector::MismatchResult
3024MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3025 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003026 const Expr *InitExpr = Field->getInClassInitializer();
3027 if (!InitExpr)
3028 return EndOfTU ? NoMismatch : AnalyzeLater;
3029 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003030 if (NE->isArray() != IsArrayForm) {
3031 NewExprs.push_back(NE);
3032 return MemberInitMismatches;
3033 }
3034 }
3035 return NoMismatch;
3036}
3037
3038MismatchingNewDeleteDetector::MismatchResult
3039MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3040 bool DeleteWasArrayForm) {
3041 assert(Field != nullptr && "Analysis requires a valid class member.");
3042 this->Field = Field;
3043 IsArrayForm = DeleteWasArrayForm;
3044 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3045 for (const auto *CD : RD->ctors()) {
3046 if (hasMatchingNewInCtor(CD))
3047 return NoMismatch;
3048 }
3049 if (HasUndefinedConstructors)
3050 return EndOfTU ? NoMismatch : AnalyzeLater;
3051 if (!NewExprs.empty())
3052 return MemberInitMismatches;
3053 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3054 : NoMismatch;
3055}
3056
3057MismatchingNewDeleteDetector::MismatchResult
3058MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3059 assert(ME != nullptr && "Expected a member expression");
3060 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3061 return analyzeField(F, IsArrayForm);
3062 return NoMismatch;
3063}
3064
3065bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3066 const CXXNewExpr *NE = nullptr;
3067 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3068 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3069 NE->isArray() != IsArrayForm) {
3070 NewExprs.push_back(NE);
3071 }
3072 }
3073 return NewExprs.empty();
3074}
3075
3076static void
3077DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3078 const MismatchingNewDeleteDetector &Detector) {
3079 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3080 FixItHint H;
3081 if (!Detector.IsArrayForm)
3082 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3083 else {
3084 SourceLocation RSquare = Lexer::findLocationAfterToken(
3085 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3086 SemaRef.getLangOpts(), true);
3087 if (RSquare.isValid())
3088 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3089 }
3090 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3091 << Detector.IsArrayForm << H;
3092
3093 for (const auto *NE : Detector.NewExprs)
3094 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3095 << Detector.IsArrayForm;
3096}
3097
3098void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3099 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3100 return;
3101 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3102 switch (Detector.analyzeDeleteExpr(DE)) {
3103 case MismatchingNewDeleteDetector::VarInitMismatches:
3104 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3105 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3106 break;
3107 }
3108 case MismatchingNewDeleteDetector::AnalyzeLater: {
3109 DeleteExprs[Detector.Field].push_back(
3110 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3111 break;
3112 }
3113 case MismatchingNewDeleteDetector::NoMismatch:
3114 break;
3115 }
3116}
3117
3118void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3119 bool DeleteWasArrayForm) {
3120 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3121 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3122 case MismatchingNewDeleteDetector::VarInitMismatches:
3123 llvm_unreachable("This analysis should have been done for class members.");
3124 case MismatchingNewDeleteDetector::AnalyzeLater:
3125 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3126 "translation unit.");
3127 case MismatchingNewDeleteDetector::MemberInitMismatches:
3128 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3129 break;
3130 case MismatchingNewDeleteDetector::NoMismatch:
3131 break;
3132 }
3133}
3134
Sebastian Redlbd150f42008-11-21 19:14:01 +00003135/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3136/// @code ::delete ptr; @endcode
3137/// or
3138/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003139ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003140Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003141 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003142 // C++ [expr.delete]p1:
3143 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003144 // non-explicit conversion function to a pointer type. The result has type
3145 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003146 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003147 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3148
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003149 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003151 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003152 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003153
John Wiegley01296292011-04-08 18:41:53 +00003154 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003155 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003156 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003157 if (Ex.isInvalid())
3158 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003159
John Wiegley01296292011-04-08 18:41:53 +00003160 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003161
Richard Smithccc11812013-05-21 19:05:48 +00003162 class DeleteConverter : public ContextualImplicitConverter {
3163 public:
3164 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Craig Toppere14c0f82014-03-12 04:55:44 +00003166 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003167 // FIXME: If we have an operator T* and an operator void*, we must pick
3168 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003169 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003170 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003171 return true;
3172 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003173 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003174
Richard Smithccc11812013-05-21 19:05:48 +00003175 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003176 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003177 return S.Diag(Loc, diag::err_delete_operand) << T;
3178 }
3179
3180 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003181 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003182 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3183 }
3184
3185 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003186 QualType T,
3187 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003188 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3189 }
3190
3191 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003192 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003193 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3194 << ConvTy;
3195 }
3196
3197 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003198 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003199 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3200 }
3201
3202 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003203 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003204 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3205 << ConvTy;
3206 }
3207
3208 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003209 QualType T,
3210 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003211 llvm_unreachable("conversion functions are permitted");
3212 }
3213 } Converter;
3214
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003215 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003216 if (Ex.isInvalid())
3217 return ExprError();
3218 Type = Ex.get()->getType();
3219 if (!Converter.match(Type))
3220 // FIXME: PerformContextualImplicitConversion should return ExprError
3221 // itself in this case.
3222 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003223
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003224 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003225 QualType PointeeElem = Context.getBaseElementType(Pointee);
3226
Alexander Richardson6d989432017-10-15 18:48:14 +00003227 if (Pointee.getAddressSpace() != LangAS::Default)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003228 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003229 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003230 << Pointee.getUnqualifiedType()
3231 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003232
Craig Topperc3ec1492014-05-26 06:22:03 +00003233 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003234 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003236 // effectively bans deletion of "void*". However, most compilers support
3237 // this, so we treat it as a warning unless we're in a SFINAE context.
3238 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003239 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003240 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003241 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003242 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003243 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003244 // FIXME: This can result in errors if the definition was imported from a
3245 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003246 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003247 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003248 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3249 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3250 }
3251 }
3252
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003253 if (Pointee->isArrayType() && !ArrayForm) {
3254 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003255 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003256 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003257 ArrayForm = true;
3258 }
3259
Anders Carlssona471db02009-08-16 20:29:29 +00003260 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3261 ArrayForm ? OO_Array_Delete : OO_Delete);
3262
Eli Friedmanae4280f2011-07-26 22:25:31 +00003263 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003265 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3266 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003267 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268
John McCall284c48f2011-01-27 09:37:56 +00003269 // If we're allocating an array of records, check whether the
3270 // usual operator delete[] has a size_t parameter.
3271 if (ArrayForm) {
3272 // If the user specifically asked to use the global allocator,
3273 // we'll need to do the lookup into the class.
3274 if (UseGlobal)
3275 UsualArrayDeleteWantsSize =
3276 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3277
3278 // Otherwise, the usual operator delete[] should be the
3279 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003280 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003281 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003282 UsualDeallocFnInfo(*this,
3283 DeclAccessPair::make(OperatorDelete, AS_public))
3284 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003285 }
3286
Richard Smitheec915d62012-02-18 04:13:32 +00003287 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003288 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003289 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003290 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003291 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3292 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003293 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003294
Nico Weber5a9259c2016-01-15 21:45:31 +00003295 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3296 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3297 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3298 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300
Richard Smithb2f0f052016-10-10 18:54:32 +00003301 if (!OperatorDelete) {
3302 bool IsComplete = isCompleteType(StartLoc, Pointee);
3303 bool CanProvideSize =
3304 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3305 Pointee.isDestructedType());
3306 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3307
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003308 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003309 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3310 Overaligned, DeleteName);
3311 }
Mike Stump11289f42009-09-09 15:08:12 +00003312
Eli Friedmanfa0df832012-02-02 03:46:19 +00003313 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003314
Richard Smith5b349582017-10-13 01:55:36 +00003315 // Check access and ambiguity of destructor if we're going to call it.
3316 // Note that this is required even for a virtual delete.
3317 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003318 if (PointeeRD) {
3319 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003320 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3321 PDiag(diag::err_access_dtor) << PointeeElem);
3322 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003323 }
3324 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003325
3326 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3327 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003328
3329 // Convert the operand to the type of the first parameter of operator
3330 // delete. This is only necessary if we selected a destroying operator
3331 // delete that we are going to call (non-virtually); converting to void*
3332 // is trivial and left to AST consumers to handle.
3333 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3334 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003335 Qualifiers Qs = Pointee.getQualifiers();
3336 if (Qs.hasCVRQualifiers()) {
3337 // Qualifiers are irrelevant to this conversion; we're only looking
3338 // for access and ambiguity.
3339 Qs.removeCVRQualifiers();
3340 QualType Unqual = Context.getPointerType(
3341 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3342 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3343 }
Richard Smith5b349582017-10-13 01:55:36 +00003344 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3345 if (Ex.isInvalid())
3346 return ExprError();
3347 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003348 }
3349
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003350 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003351 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3352 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003353 AnalyzeDeleteExprMismatch(Result);
3354 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003355}
3356
Eric Fiselierfa752f22018-03-21 19:19:48 +00003357static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3358 bool IsDelete,
3359 FunctionDecl *&Operator) {
3360
3361 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3362 IsDelete ? OO_Delete : OO_New);
3363
3364 LookupResult R(S, NewName, TheCall->getLocStart(), Sema::LookupOrdinaryName);
3365 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3366 assert(!R.empty() && "implicitly declared allocation functions not found");
3367 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3368
3369 // We do our own custom access checks below.
3370 R.suppressDiagnostics();
3371
3372 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3373 OverloadCandidateSet Candidates(R.getNameLoc(),
3374 OverloadCandidateSet::CSK_Normal);
3375 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3376 FnOvl != FnOvlEnd; ++FnOvl) {
3377 // Even member operator new/delete are implicitly treated as
3378 // static, so don't use AddMemberCandidate.
3379 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3380
3381 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3382 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3383 /*ExplicitTemplateArgs=*/nullptr, Args,
3384 Candidates,
3385 /*SuppressUserConversions=*/false);
3386 continue;
3387 }
3388
3389 FunctionDecl *Fn = cast<FunctionDecl>(D);
3390 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3391 /*SuppressUserConversions=*/false);
3392 }
3393
3394 SourceRange Range = TheCall->getSourceRange();
3395
3396 // Do the resolution.
3397 OverloadCandidateSet::iterator Best;
3398 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3399 case OR_Success: {
3400 // Got one!
3401 FunctionDecl *FnDecl = Best->Function;
3402 assert(R.getNamingClass() == nullptr &&
3403 "class members should not be considered");
3404
3405 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3406 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3407 << (IsDelete ? 1 : 0) << Range;
3408 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3409 << R.getLookupName() << FnDecl->getSourceRange();
3410 return true;
3411 }
3412
3413 Operator = FnDecl;
3414 return false;
3415 }
3416
3417 case OR_No_Viable_Function:
3418 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3419 << R.getLookupName() << Range;
3420 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3421 return true;
3422
3423 case OR_Ambiguous:
3424 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3425 << R.getLookupName() << Range;
3426 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3427 return true;
3428
3429 case OR_Deleted: {
3430 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3431 << Best->Function->isDeleted() << R.getLookupName()
3432 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3433 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3434 return true;
3435 }
3436 }
3437 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3438}
3439
3440ExprResult
3441Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3442 bool IsDelete) {
3443 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3444 if (!getLangOpts().CPlusPlus) {
3445 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3446 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3447 << "C++";
3448 return ExprError();
3449 }
3450 // CodeGen assumes it can find the global new and delete to call,
3451 // so ensure that they are declared.
3452 DeclareGlobalNewDelete();
3453
3454 FunctionDecl *OperatorNewOrDelete = nullptr;
3455 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3456 OperatorNewOrDelete))
3457 return ExprError();
3458 assert(OperatorNewOrDelete && "should be found");
3459
3460 TheCall->setType(OperatorNewOrDelete->getReturnType());
3461 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3462 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3463 InitializedEntity Entity =
3464 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3465 ExprResult Arg = PerformCopyInitialization(
3466 Entity, TheCall->getArg(i)->getLocStart(), TheCall->getArg(i));
3467 if (Arg.isInvalid())
3468 return ExprError();
3469 TheCall->setArg(i, Arg.get());
3470 }
3471 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3472 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3473 "Callee expected to be implicit cast to a builtin function pointer");
3474 Callee->setType(OperatorNewOrDelete->getType());
3475
3476 return TheCallResult;
3477}
3478
Nico Weber5a9259c2016-01-15 21:45:31 +00003479void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3480 bool IsDelete, bool CallCanBeVirtual,
3481 bool WarnOnNonAbstractTypes,
3482 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003483 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003484 return;
3485
3486 // C++ [expr.delete]p3:
3487 // In the first alternative (delete object), if the static type of the
3488 // object to be deleted is different from its dynamic type, the static
3489 // type shall be a base class of the dynamic type of the object to be
3490 // deleted and the static type shall have a virtual destructor or the
3491 // behavior is undefined.
3492 //
3493 const CXXRecordDecl *PointeeRD = dtor->getParent();
3494 // Note: a final class cannot be derived from, no issue there
3495 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3496 return;
3497
Nico Weberbf2260c2017-08-31 06:17:08 +00003498 // If the superclass is in a system header, there's nothing that can be done.
3499 // The `delete` (where we emit the warning) can be in a system header,
3500 // what matters for this warning is where the deleted type is defined.
3501 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3502 return;
3503
Nico Weber5a9259c2016-01-15 21:45:31 +00003504 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3505 if (PointeeRD->isAbstract()) {
3506 // If the class is abstract, we warn by default, because we're
3507 // sure the code has undefined behavior.
3508 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3509 << ClassType;
3510 } else if (WarnOnNonAbstractTypes) {
3511 // Otherwise, if this is not an array delete, it's a bit suspect,
3512 // but not necessarily wrong.
3513 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3514 << ClassType;
3515 }
3516 if (!IsDelete) {
3517 std::string TypeStr;
3518 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3519 Diag(DtorLoc, diag::note_delete_non_virtual)
3520 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3521 }
3522}
3523
Richard Smith03a4aa32016-06-23 19:02:52 +00003524Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3525 SourceLocation StmtLoc,
3526 ConditionKind CK) {
3527 ExprResult E =
3528 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3529 if (E.isInvalid())
3530 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003531 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3532 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003533}
3534
Douglas Gregor633caca2009-11-23 23:44:04 +00003535/// \brief Check the use of the given variable as a C++ condition in an if,
3536/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003537ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003538 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003539 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003540 if (ConditionVar->isInvalidDecl())
3541 return ExprError();
3542
Douglas Gregor633caca2009-11-23 23:44:04 +00003543 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544
Douglas Gregor633caca2009-11-23 23:44:04 +00003545 // C++ [stmt.select]p2:
3546 // The declarator shall not specify a function or an array.
3547 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003549 diag::err_invalid_use_of_function_type)
3550 << ConditionVar->getSourceRange());
3551 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003553 diag::err_invalid_use_of_array_type)
3554 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003555
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003556 ExprResult Condition = DeclRefExpr::Create(
3557 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3558 /*enclosing*/ false, ConditionVar->getLocation(),
3559 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003560
Eli Friedmanfa0df832012-02-02 03:46:19 +00003561 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003562
Richard Smith03a4aa32016-06-23 19:02:52 +00003563 switch (CK) {
3564 case ConditionKind::Boolean:
3565 return CheckBooleanCondition(StmtLoc, Condition.get());
3566
Richard Smithb130fe72016-06-23 19:16:49 +00003567 case ConditionKind::ConstexprIf:
3568 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3569
Richard Smith03a4aa32016-06-23 19:02:52 +00003570 case ConditionKind::Switch:
3571 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573
Richard Smith03a4aa32016-06-23 19:02:52 +00003574 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003575}
3576
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003577/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003578ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003579 // C++ 6.4p4:
3580 // The value of a condition that is an initialized declaration in a statement
3581 // other than a switch statement is the value of the declared variable
3582 // implicitly converted to type bool. If that conversion is ill-formed, the
3583 // program is ill-formed.
3584 // The value of a condition that is an expression is the value of the
3585 // expression, implicitly converted to bool.
3586 //
Richard Smithb130fe72016-06-23 19:16:49 +00003587 // FIXME: Return this value to the caller so they don't need to recompute it.
3588 llvm::APSInt Value(/*BitWidth*/1);
3589 return (IsConstexpr && !CondExpr->isValueDependent())
3590 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3591 CCEK_ConstexprIf)
3592 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003593}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003594
3595/// Helper function to determine whether this is the (deprecated) C++
3596/// conversion from a string literal to a pointer to non-const char or
3597/// non-const wchar_t (for narrow and wide string literals,
3598/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003599bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003600Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3601 // Look inside the implicit cast, if it exists.
3602 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3603 From = Cast->getSubExpr();
3604
3605 // A string literal (2.13.4) that is not a wide string literal can
3606 // be converted to an rvalue of type "pointer to char"; a wide
3607 // string literal can be converted to an rvalue of type "pointer
3608 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003609 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003610 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003611 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003612 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003613 // This conversion is considered only when there is an
3614 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003615 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3616 switch (StrLit->getKind()) {
3617 case StringLiteral::UTF8:
3618 case StringLiteral::UTF16:
3619 case StringLiteral::UTF32:
3620 // We don't allow UTF literals to be implicitly converted
3621 break;
3622 case StringLiteral::Ascii:
3623 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3624 ToPointeeType->getKind() == BuiltinType::Char_S);
3625 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003626 return Context.typesAreCompatible(Context.getWideCharType(),
3627 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003628 }
3629 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003630 }
3631
3632 return false;
3633}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003634
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003636 SourceLocation CastLoc,
3637 QualType Ty,
3638 CastKind Kind,
3639 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003640 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003641 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003642 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003643 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003644 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003645 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003646 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003647 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Richard Smith72d74052013-07-20 19:41:36 +00003649 if (S.RequireNonAbstractType(CastLoc, Ty,
3650 diag::err_allocation_of_abstract_type))
3651 return ExprError();
3652
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003653 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003654 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Richard Smith5179eb72016-06-28 19:03:57 +00003656 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3657 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003658 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003659 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003660
Richard Smithf8adcdc2014-07-17 05:12:35 +00003661 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003662 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003663 ConstructorArgs, HadMultipleCandidates,
3664 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3665 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003666 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003667 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003669 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
John McCalle3027922010-08-25 11:45:40 +00003672 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003673 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Richard Smithd3f2d322015-02-24 21:16:19 +00003675 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003676 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003677 return ExprError();
3678
Douglas Gregora4253922010-04-16 22:17:36 +00003679 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003680 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3681 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003682 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003683 if (Result.isInvalid())
3684 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003685 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003686 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3687 CK_UserDefinedConversion, Result.get(),
3688 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003689
Douglas Gregor668443e2011-01-20 00:18:04 +00003690 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003691 }
3692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693}
Douglas Gregora4253922010-04-16 22:17:36 +00003694
Douglas Gregor5fb53972009-01-14 15:45:31 +00003695/// PerformImplicitConversion - Perform an implicit conversion of the
3696/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003697/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003698/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003699/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003700ExprResult
3701Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003702 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003703 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003704 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003705 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003706 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003707 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3708 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003709 if (Res.isInvalid())
3710 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003711 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003712 break;
John Wiegley01296292011-04-08 18:41:53 +00003713 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003714
Anders Carlsson110b07b2009-09-15 06:28:28 +00003715 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003717 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003718 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003719 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003720 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003721 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003722 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723
Anders Carlsson110b07b2009-09-15 06:28:28 +00003724 // If the user-defined conversion is specified by a conversion function,
3725 // the initial standard conversion sequence converts the source type to
3726 // the implicit object parameter of the conversion function.
3727 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003728 } else {
3729 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003730 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003731 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003732 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003734 // initial standard conversion sequence converts the source type to
3735 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003736 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738 }
Richard Smith72d74052013-07-20 19:41:36 +00003739 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003740 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003741 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003742 PerformImplicitConversion(From, BeforeToType,
3743 ICS.UserDefined.Before, AA_Converting,
3744 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003745 if (Res.isInvalid())
3746 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003747 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
3750 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003751 = BuildCXXCastArgument(*this,
3752 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003753 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003754 CastKind, cast<CXXMethodDecl>(FD),
3755 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003756 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003757 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003758
3759 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003760 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003761
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003762 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003763
Richard Smith507840d2011-11-29 22:48:16 +00003764 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3765 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003766 }
John McCall0d1da222010-01-12 00:44:57 +00003767
3768 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003769 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003770 PDiag(diag::err_typecheck_ambiguous_condition)
3771 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003772 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregor39c16d42008-10-24 04:54:22 +00003774 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003775 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003776
3777 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003778 bool Diagnosed =
3779 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3780 From->getType(), From, Action);
3781 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003782 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003783 }
3784
3785 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003786 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003787}
3788
Richard Smith507840d2011-11-29 22:48:16 +00003789/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003790/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003791/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003792/// expression. Flavor is the context in which we're performing this
3793/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003794ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003795Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003796 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003797 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003798 CheckedConversionKind CCK) {
3799 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003800
Mike Stump87c57ac2009-05-16 07:39:55 +00003801 // Overall FIXME: we are recomputing too many types here and doing far too
3802 // much extra work. What this means is that we need to keep track of more
3803 // information that is computed when we try the implicit conversion initially,
3804 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003805 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003806
Douglas Gregor2fe98832008-11-03 19:09:14 +00003807 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003808 // FIXME: When can ToType be a reference type?
3809 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003810 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003811 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003812 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003813 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003814 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003815 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003816 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003817 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3818 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003819 ConstructorArgs, /*HadMultipleCandidates*/ false,
3820 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3821 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003822 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003823 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003824 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3825 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003826 From, /*HadMultipleCandidates*/ false,
3827 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3828 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003829 }
3830
Douglas Gregor980fb162010-04-29 18:24:40 +00003831 // Resolve overloaded function references.
3832 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3833 DeclAccessPair Found;
3834 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3835 true, Found);
3836 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003837 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003838
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003839 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003840 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003841
Douglas Gregor980fb162010-04-29 18:24:40 +00003842 From = FixOverloadedFunctionReference(From, Found, Fn);
3843 FromType = From->getType();
3844 }
3845
Richard Smitha23ab512013-05-23 00:30:41 +00003846 // If we're converting to an atomic type, first convert to the corresponding
3847 // non-atomic type.
3848 QualType ToAtomicType;
3849 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3850 ToAtomicType = ToType;
3851 ToType = ToAtomic->getValueType();
3852 }
3853
George Burgess IV8d141e02015-12-14 22:00:49 +00003854 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003855 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003856 switch (SCS.First) {
3857 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003858 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3859 FromType = FromAtomic->getValueType().getUnqualifiedType();
3860 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3861 From, /*BasePath=*/nullptr, VK_RValue);
3862 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003863 break;
3864
Eli Friedman946b7b52012-01-24 22:51:26 +00003865 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003866 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003867 ExprResult FromRes = DefaultLvalueConversion(From);
3868 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003869 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003870 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003871 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003872 }
John McCall34376a62010-12-04 03:47:34 +00003873
Douglas Gregor39c16d42008-10-24 04:54:22 +00003874 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003875 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003876 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003877 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003878 break;
3879
3880 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003881 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003882 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003883 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003884 break;
3885
3886 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003887 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003888 }
3889
Richard Smith507840d2011-11-29 22:48:16 +00003890 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003891 switch (SCS.Second) {
3892 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003893 // C++ [except.spec]p5:
3894 // [For] assignment to and initialization of pointers to functions,
3895 // pointers to member functions, and references to functions: the
3896 // target entity shall allow at least the exceptions allowed by the
3897 // source value in the assignment or initialization.
3898 switch (Action) {
3899 case AA_Assigning:
3900 case AA_Initializing:
3901 // Note, function argument passing and returning are initialization.
3902 case AA_Passing:
3903 case AA_Returning:
3904 case AA_Sending:
3905 case AA_Passing_CFAudited:
3906 if (CheckExceptionSpecCompatibility(From, ToType))
3907 return ExprError();
3908 break;
3909
3910 case AA_Casting:
3911 case AA_Converting:
3912 // Casts and implicit conversions are not initialization, so are not
3913 // checked for exception specification mismatches.
3914 break;
3915 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003916 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003917 break;
3918
3919 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003920 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003921 if (ToType->isBooleanType()) {
3922 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3923 SCS.Second == ICK_Integral_Promotion &&
3924 "only enums with fixed underlying type can promote to bool");
3925 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003926 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003927 } else {
3928 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003929 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003930 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003931 break;
3932
3933 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003934 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003935 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003936 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003937 break;
3938
3939 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003940 case ICK_Complex_Conversion: {
3941 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3942 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3943 CastKind CK;
3944 if (FromEl->isRealFloatingType()) {
3945 if (ToEl->isRealFloatingType())
3946 CK = CK_FloatingComplexCast;
3947 else
3948 CK = CK_FloatingComplexToIntegralComplex;
3949 } else if (ToEl->isRealFloatingType()) {
3950 CK = CK_IntegralComplexToFloatingComplex;
3951 } else {
3952 CK = CK_IntegralComplexCast;
3953 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003954 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003955 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003956 break;
John McCall8cb679e2010-11-15 09:13:47 +00003957 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003958
Douglas Gregor39c16d42008-10-24 04:54:22 +00003959 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003960 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003961 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003962 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003963 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003964 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003965 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003966 break;
3967
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003968 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003969 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003970 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003971 break;
3972
John McCall31168b02011-06-15 23:02:42 +00003973 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003974 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003975 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003976 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003977 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003978 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003979 diag::ext_typecheck_convert_incompatible_pointer)
3980 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003981 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003982 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003983 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003984 diag::ext_typecheck_convert_incompatible_pointer)
3985 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003986 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003987
Douglas Gregor33823722011-06-11 01:09:30 +00003988 if (From->getType()->isObjCObjectPointerType() &&
3989 ToType->isObjCObjectPointerType())
3990 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00003991 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3992 !CheckObjCARCUnavailableWeakConversion(ToType,
3993 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003994 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003995 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003996 diag::err_arc_weak_unavailable_assign);
3997 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003998 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003999 diag::err_arc_convesion_of_weak_unavailable)
4000 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00004001 << From->getSourceRange();
4002 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004003
Richard Smith354abec2017-12-08 23:29:59 +00004004 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004005 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004006 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004007 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004008
4009 // Make sure we extend blocks if necessary.
4010 // FIXME: doing this here is really ugly.
4011 if (Kind == CK_BlockPointerToObjCPointerCast) {
4012 ExprResult E = From;
4013 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004014 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004015 }
Brian Kelley11352a82017-03-29 18:09:02 +00004016 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4017 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004018 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004019 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004020 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004023 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004024 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004025 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004026 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004027 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004028 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004029 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004030
4031 // We may not have been able to figure out what this member pointer resolved
4032 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004033 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004034 (void)isCompleteType(From->getExprLoc(), From->getType());
4035 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004036 }
David Majnemerd96b9972014-08-08 00:10:39 +00004037
Richard Smith507840d2011-11-29 22:48:16 +00004038 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004039 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004040 break;
4041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004043 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004044 // Perform half-to-boolean conversion via float.
4045 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004046 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004047 FromType = Context.FloatTy;
4048 }
4049
Richard Smith507840d2011-11-29 22:48:16 +00004050 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004051 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004052 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004053 break;
4054
Douglas Gregor88d292c2010-05-13 16:44:06 +00004055 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004056 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004058 ToType.getNonReferenceType(),
4059 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004061 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00004062 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004063 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004064
Richard Smith507840d2011-11-29 22:48:16 +00004065 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4066 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004067 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004068 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004069 }
4070
Douglas Gregor46188682010-05-18 22:42:18 +00004071 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004072 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004073 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004074 break;
4075
George Burgess IVdf1ed002016-01-13 01:52:39 +00004076 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004077 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004078 Expr *Elem = prepareVectorSplat(ToType, From).get();
4079 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4080 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004081 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregor46188682010-05-18 22:42:18 +00004084 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004085 // Case 1. x -> _Complex y
4086 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4087 QualType ElType = ToComplex->getElementType();
4088 bool isFloatingComplex = ElType->isRealFloatingType();
4089
4090 // x -> y
4091 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4092 // do nothing
4093 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004094 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004095 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004096 } else {
4097 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004098 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004099 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004100 }
4101 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004102 From = ImpCastExprToType(From, ToType,
4103 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004104 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004105
4106 // Case 2. _Complex x -> y
4107 } else {
4108 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4109 assert(FromComplex);
4110
4111 QualType ElType = FromComplex->getElementType();
4112 bool isFloatingComplex = ElType->isRealFloatingType();
4113
4114 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004115 From = ImpCastExprToType(From, ElType,
4116 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004117 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004118 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004119
4120 // x -> y
4121 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4122 // do nothing
4123 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004124 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004125 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004126 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004127 } else {
4128 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004129 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004130 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004131 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004132 }
4133 }
Douglas Gregor46188682010-05-18 22:42:18 +00004134 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004135
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004136 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004137 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004138 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004139 break;
4140 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004141
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004142 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004143 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004144 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004145 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4146 if (FromRes.isInvalid())
4147 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004148 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004149 assert ((ConvTy == Sema::Compatible) &&
4150 "Improper transparent union conversion");
4151 (void)ConvTy;
4152 break;
4153 }
4154
Guy Benyei259f9f42013-02-07 16:05:33 +00004155 case ICK_Zero_Event_Conversion:
4156 From = ImpCastExprToType(From, ToType,
4157 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004158 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004159 break;
4160
Egor Churaev89831422016-12-23 14:55:49 +00004161 case ICK_Zero_Queue_Conversion:
4162 From = ImpCastExprToType(From, ToType,
4163 CK_ZeroToOCLQueue,
4164 From->getValueKind()).get();
4165 break;
4166
Douglas Gregor46188682010-05-18 22:42:18 +00004167 case ICK_Lvalue_To_Rvalue:
4168 case ICK_Array_To_Pointer:
4169 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004170 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004171 case ICK_Qualification:
4172 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004173 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004174 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004175 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004176 }
4177
4178 switch (SCS.Third) {
4179 case ICK_Identity:
4180 // Nothing to do.
4181 break;
4182
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004183 case ICK_Function_Conversion:
4184 // If both sides are functions (or pointers/references to them), there could
4185 // be incompatible exception declarations.
4186 if (CheckExceptionSpecCompatibility(From, ToType))
4187 return ExprError();
4188
4189 From = ImpCastExprToType(From, ToType, CK_NoOp,
4190 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4191 break;
4192
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004193 case ICK_Qualification: {
4194 // The qualification keeps the category of the inner expression, unless the
4195 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004196 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004197 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004198 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004199 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004200
Douglas Gregore981bb02011-03-14 16:13:32 +00004201 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004202 !getLangOpts().WritableStrings) {
4203 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4204 ? diag::ext_deprecated_string_literal_conversion
4205 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004206 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004207 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004208
Douglas Gregor39c16d42008-10-24 04:54:22 +00004209 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004210 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004211
Douglas Gregor39c16d42008-10-24 04:54:22 +00004212 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004213 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004214 }
4215
Douglas Gregor298f43d2012-04-12 20:42:30 +00004216 // If this conversion sequence involved a scalar -> atomic conversion, perform
4217 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004218 if (!ToAtomicType.isNull()) {
4219 assert(Context.hasSameType(
4220 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4221 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004222 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004223 }
4224
George Burgess IV8d141e02015-12-14 22:00:49 +00004225 // If this conversion sequence succeeded and involved implicitly converting a
4226 // _Nullable type to a _Nonnull one, complain.
4227 if (CCK == CCK_ImplicitConversion)
4228 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4229 From->getLocStart());
4230
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004231 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004232}
4233
Chandler Carruth8e172c62011-05-01 06:51:22 +00004234/// \brief Check the completeness of a type in a unary type trait.
4235///
4236/// If the particular type trait requires a complete type, tries to complete
4237/// it. If completing the type fails, a diagnostic is emitted and false
4238/// returned. If completing the type succeeds or no completion was required,
4239/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004240static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004241 SourceLocation Loc,
4242 QualType ArgTy) {
4243 // C++0x [meta.unary.prop]p3:
4244 // For all of the class templates X declared in this Clause, instantiating
4245 // that template with a template argument that is a class template
4246 // specialization may result in the implicit instantiation of the template
4247 // argument if and only if the semantics of X require that the argument
4248 // must be a complete type.
4249 // We apply this rule to all the type trait expressions used to implement
4250 // these class templates. We also try to follow any GCC documented behavior
4251 // in these expressions to ensure portability of standard libraries.
4252 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004253 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004254 // is_complete_type somewhat obviously cannot require a complete type.
4255 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004256 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004257
4258 // These traits are modeled on the type predicates in C++0x
4259 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4260 // requiring a complete type, as whether or not they return true cannot be
4261 // impacted by the completeness of the type.
4262 case UTT_IsVoid:
4263 case UTT_IsIntegral:
4264 case UTT_IsFloatingPoint:
4265 case UTT_IsArray:
4266 case UTT_IsPointer:
4267 case UTT_IsLvalueReference:
4268 case UTT_IsRvalueReference:
4269 case UTT_IsMemberFunctionPointer:
4270 case UTT_IsMemberObjectPointer:
4271 case UTT_IsEnum:
4272 case UTT_IsUnion:
4273 case UTT_IsClass:
4274 case UTT_IsFunction:
4275 case UTT_IsReference:
4276 case UTT_IsArithmetic:
4277 case UTT_IsFundamental:
4278 case UTT_IsObject:
4279 case UTT_IsScalar:
4280 case UTT_IsCompound:
4281 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004282 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004283
4284 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4285 // which requires some of its traits to have the complete type. However,
4286 // the completeness of the type cannot impact these traits' semantics, and
4287 // so they don't require it. This matches the comments on these traits in
4288 // Table 49.
4289 case UTT_IsConst:
4290 case UTT_IsVolatile:
4291 case UTT_IsSigned:
4292 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004293
4294 // This type trait always returns false, checking the type is moot.
4295 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004296 return true;
4297
David Majnemer213bea32015-11-16 06:58:51 +00004298 // C++14 [meta.unary.prop]:
4299 // If T is a non-union class type, T shall be a complete type.
4300 case UTT_IsEmpty:
4301 case UTT_IsPolymorphic:
4302 case UTT_IsAbstract:
4303 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4304 if (!RD->isUnion())
4305 return !S.RequireCompleteType(
4306 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4307 return true;
4308
4309 // C++14 [meta.unary.prop]:
4310 // If T is a class type, T shall be a complete type.
4311 case UTT_IsFinal:
4312 case UTT_IsSealed:
4313 if (ArgTy->getAsCXXRecordDecl())
4314 return !S.RequireCompleteType(
4315 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4316 return true;
4317
Richard Smithf03e9082017-06-01 00:28:16 +00004318 // C++1z [meta.unary.prop]:
4319 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004320 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004321 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004322 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004323 case UTT_IsStandardLayout:
4324 case UTT_IsPOD:
4325 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004326 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4327 // or an array of unknown bound. But GCC actually imposes the same constraints
4328 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004329 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004330 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004331 case UTT_HasNothrowConstructor:
4332 case UTT_HasNothrowCopy:
4333 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004334 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004335 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004336 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004337 case UTT_HasTrivialCopy:
4338 case UTT_HasTrivialDestructor:
4339 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004340 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4341 LLVM_FALLTHROUGH;
4342
4343 // C++1z [meta.unary.prop]:
4344 // T shall be a complete type, cv void, or an array of unknown bound.
4345 case UTT_IsDestructible:
4346 case UTT_IsNothrowDestructible:
4347 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004348 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004349 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004350 return true;
4351
4352 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004353 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004354 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004355}
4356
Joao Matosc9523d42013-03-27 01:34:16 +00004357static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4358 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004359 bool (CXXRecordDecl::*HasTrivial)() const,
4360 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004361 bool (CXXMethodDecl::*IsDesiredOp)() const)
4362{
4363 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4364 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4365 return true;
4366
4367 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4368 DeclarationNameInfo NameInfo(Name, KeyLoc);
4369 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4370 if (Self.LookupQualifiedName(Res, RD)) {
4371 bool FoundOperator = false;
4372 Res.suppressDiagnostics();
4373 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4374 Op != OpEnd; ++Op) {
4375 if (isa<FunctionTemplateDecl>(*Op))
4376 continue;
4377
4378 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4379 if((Operator->*IsDesiredOp)()) {
4380 FoundOperator = true;
4381 const FunctionProtoType *CPT =
4382 Operator->getType()->getAs<FunctionProtoType>();
4383 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004384 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004385 return false;
4386 }
4387 }
4388 return FoundOperator;
4389 }
4390 return false;
4391}
4392
Alp Toker95e7ff22014-01-01 05:57:51 +00004393static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004394 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004395 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004396
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004397 ASTContext &C = Self.Context;
4398 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004399 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004400 // Type trait expressions corresponding to the primary type category
4401 // predicates in C++0x [meta.unary.cat].
4402 case UTT_IsVoid:
4403 return T->isVoidType();
4404 case UTT_IsIntegral:
4405 return T->isIntegralType(C);
4406 case UTT_IsFloatingPoint:
4407 return T->isFloatingType();
4408 case UTT_IsArray:
4409 return T->isArrayType();
4410 case UTT_IsPointer:
4411 return T->isPointerType();
4412 case UTT_IsLvalueReference:
4413 return T->isLValueReferenceType();
4414 case UTT_IsRvalueReference:
4415 return T->isRValueReferenceType();
4416 case UTT_IsMemberFunctionPointer:
4417 return T->isMemberFunctionPointerType();
4418 case UTT_IsMemberObjectPointer:
4419 return T->isMemberDataPointerType();
4420 case UTT_IsEnum:
4421 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004422 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004423 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004424 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004425 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004426 case UTT_IsFunction:
4427 return T->isFunctionType();
4428
4429 // Type trait expressions which correspond to the convenient composition
4430 // predicates in C++0x [meta.unary.comp].
4431 case UTT_IsReference:
4432 return T->isReferenceType();
4433 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004434 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004435 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004436 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004437 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004438 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004439 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004440 // Note: semantic analysis depends on Objective-C lifetime types to be
4441 // considered scalar types. However, such types do not actually behave
4442 // like scalar types at run time (since they may require retain/release
4443 // operations), so we report them as non-scalar.
4444 if (T->isObjCLifetimeType()) {
4445 switch (T.getObjCLifetime()) {
4446 case Qualifiers::OCL_None:
4447 case Qualifiers::OCL_ExplicitNone:
4448 return true;
4449
4450 case Qualifiers::OCL_Strong:
4451 case Qualifiers::OCL_Weak:
4452 case Qualifiers::OCL_Autoreleasing:
4453 return false;
4454 }
4455 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004456
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004457 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004458 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004459 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004460 case UTT_IsMemberPointer:
4461 return T->isMemberPointerType();
4462
4463 // Type trait expressions which correspond to the type property predicates
4464 // in C++0x [meta.unary.prop].
4465 case UTT_IsConst:
4466 return T.isConstQualified();
4467 case UTT_IsVolatile:
4468 return T.isVolatileQualified();
4469 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004470 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004471 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004472 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004473 case UTT_IsStandardLayout:
4474 return T->isStandardLayoutType();
4475 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004476 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004477 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004478 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004479 case UTT_IsEmpty:
4480 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4481 return !RD->isUnion() && RD->isEmpty();
4482 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004483 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004484 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004485 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004486 return false;
4487 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004488 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004489 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004490 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004491 case UTT_IsAggregate:
4492 // Report vector extensions and complex types as aggregates because they
4493 // support aggregate initialization. GCC mirrors this behavior for vectors
4494 // but not _Complex.
4495 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4496 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004497 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4498 // even then only when it is used with the 'interface struct ...' syntax
4499 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004500 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004501 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004502 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004503 case UTT_IsSealed:
4504 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004505 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004506 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004507 case UTT_IsSigned:
4508 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004509 case UTT_IsUnsigned:
4510 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004511
4512 // Type trait expressions which query classes regarding their construction,
4513 // destruction, and copying. Rather than being based directly on the
4514 // related type predicates in the standard, they are specified by both
4515 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4516 // specifications.
4517 //
4518 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4519 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004520 //
4521 // Note that these builtins do not behave as documented in g++: if a class
4522 // has both a trivial and a non-trivial special member of a particular kind,
4523 // they return false! For now, we emulate this behavior.
4524 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4525 // does not correctly compute triviality in the presence of multiple special
4526 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004527 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004528 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4529 // If __is_pod (type) is true then the trait is true, else if type is
4530 // a cv class or union type (or array thereof) with a trivial default
4531 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004532 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004533 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004534 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4535 return RD->hasTrivialDefaultConstructor() &&
4536 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004537 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004538 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004539 // This trait is implemented by MSVC 2012 and needed to parse the
4540 // standard library headers. Specifically this is used as the logic
4541 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004542 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004543 return true;
4544 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4545 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4546 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004547 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004548 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4549 // If __is_pod (type) is true or type is a reference type then
4550 // the trait is true, else if type is a cv class or union type
4551 // with a trivial copy constructor ([class.copy]) then the trait
4552 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004553 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004554 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004555 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4556 return RD->hasTrivialCopyConstructor() &&
4557 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004558 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004559 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004560 // This trait is implemented by MSVC 2012 and needed to parse the
4561 // standard library headers. Specifically it is used as the logic
4562 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004563 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004564 return true;
4565 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4566 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4567 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004568 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004569 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4570 // If type is const qualified or is a reference type then the
4571 // trait is false. Otherwise if __is_pod (type) is true then the
4572 // trait is true, else if type is a cv class or union type with
4573 // a trivial copy assignment ([class.copy]) then the trait is
4574 // true, else it is false.
4575 // Note: the const and reference restrictions are interesting,
4576 // given that const and reference members don't prevent a class
4577 // from having a trivial copy assignment operator (but do cause
4578 // errors if the copy assignment operator is actually used, q.v.
4579 // [class.copy]p12).
4580
Richard Smith92f241f2012-12-08 02:53:02 +00004581 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004582 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004583 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004584 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004585 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4586 return RD->hasTrivialCopyAssignment() &&
4587 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004588 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004589 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004590 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004591 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004592 // C++14 [meta.unary.prop]:
4593 // For reference types, is_destructible<T>::value is true.
4594 if (T->isReferenceType())
4595 return true;
4596
4597 // Objective-C++ ARC: autorelease types don't require destruction.
4598 if (T->isObjCLifetimeType() &&
4599 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4600 return true;
4601
4602 // C++14 [meta.unary.prop]:
4603 // For incomplete types and function types, is_destructible<T>::value is
4604 // false.
4605 if (T->isIncompleteType() || T->isFunctionType())
4606 return false;
4607
Richard Smithf03e9082017-06-01 00:28:16 +00004608 // A type that requires destruction (via a non-trivial destructor or ARC
4609 // lifetime semantics) is not trivially-destructible.
4610 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4611 return false;
4612
David Majnemerac73de92015-08-11 03:03:28 +00004613 // C++14 [meta.unary.prop]:
4614 // For object types and given U equal to remove_all_extents_t<T>, if the
4615 // expression std::declval<U&>().~U() is well-formed when treated as an
4616 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4617 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4618 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4619 if (!Destructor)
4620 return false;
4621 // C++14 [dcl.fct.def.delete]p2:
4622 // A program that refers to a deleted function implicitly or
4623 // explicitly, other than to declare it, is ill-formed.
4624 if (Destructor->isDeleted())
4625 return false;
4626 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4627 return false;
4628 if (UTT == UTT_IsNothrowDestructible) {
4629 const FunctionProtoType *CPT =
4630 Destructor->getType()->getAs<FunctionProtoType>();
4631 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004632 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004633 return false;
4634 }
4635 }
4636 return true;
4637
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004638 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004639 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004640 // If __is_pod (type) is true or type is a reference type
4641 // then the trait is true, else if type is a cv class or union
4642 // type (or array thereof) with a trivial destructor
4643 // ([class.dtor]) then the trait is true, else it is
4644 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004645 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004646 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004647
John McCall31168b02011-06-15 23:02:42 +00004648 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004649 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004650 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4651 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004652
Richard Smith92f241f2012-12-08 02:53:02 +00004653 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4654 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004655 return false;
4656 // TODO: Propagate nothrowness for implicitly declared special members.
4657 case UTT_HasNothrowAssign:
4658 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4659 // If type is const qualified or is a reference type then the
4660 // trait is false. Otherwise if __has_trivial_assign (type)
4661 // is true then the trait is true, else if type is a cv class
4662 // or union type with copy assignment operators that are known
4663 // not to throw an exception then the trait is true, else it is
4664 // false.
4665 if (C.getBaseElementType(T).isConstQualified())
4666 return false;
4667 if (T->isReferenceType())
4668 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004669 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004670 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004671
Joao Matosc9523d42013-03-27 01:34:16 +00004672 if (const RecordType *RT = T->getAs<RecordType>())
4673 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4674 &CXXRecordDecl::hasTrivialCopyAssignment,
4675 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4676 &CXXMethodDecl::isCopyAssignmentOperator);
4677 return false;
4678 case UTT_HasNothrowMoveAssign:
4679 // This trait is implemented by MSVC 2012 and needed to parse the
4680 // standard library headers. Specifically this is used as the logic
4681 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004682 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004683 return true;
4684
4685 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4686 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4687 &CXXRecordDecl::hasTrivialMoveAssignment,
4688 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4689 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004690 return false;
4691 case UTT_HasNothrowCopy:
4692 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4693 // If __has_trivial_copy (type) is true then the trait is true, else
4694 // if type is a cv class or union type with copy constructors that are
4695 // known not to throw an exception then the trait is true, else it is
4696 // false.
John McCall31168b02011-06-15 23:02:42 +00004697 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004698 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004699 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4700 if (RD->hasTrivialCopyConstructor() &&
4701 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004702 return true;
4703
4704 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004705 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004706 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004707 // A template constructor is never a copy constructor.
4708 // FIXME: However, it may actually be selected at the actual overload
4709 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004710 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004711 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004712 // UsingDecl itself is not a constructor
4713 if (isa<UsingDecl>(ND))
4714 continue;
4715 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004716 if (Constructor->isCopyConstructor(FoundTQs)) {
4717 FoundConstructor = true;
4718 const FunctionProtoType *CPT
4719 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004720 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4721 if (!CPT)
4722 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004723 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004724 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004725 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004726 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004727 }
4728 }
4729
Richard Smith938f40b2011-06-11 17:19:42 +00004730 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004731 }
4732 return false;
4733 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004734 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004735 // If __has_trivial_constructor (type) is true then the trait is
4736 // true, else if type is a cv class or union type (or array
4737 // thereof) with a default constructor that is known not to
4738 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004739 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004740 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004741 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4742 if (RD->hasTrivialDefaultConstructor() &&
4743 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004744 return true;
4745
Alp Tokerb4bca412014-01-20 00:23:47 +00004746 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004747 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004748 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004749 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004750 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004751 // UsingDecl itself is not a constructor
4752 if (isa<UsingDecl>(ND))
4753 continue;
4754 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004755 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004756 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004757 const FunctionProtoType *CPT
4758 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004759 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4760 if (!CPT)
4761 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004762 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004763 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004764 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004765 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004766 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004767 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004768 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004769 }
4770 return false;
4771 case UTT_HasVirtualDestructor:
4772 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4773 // If type is a class type with a virtual destructor ([class.dtor])
4774 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004775 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004776 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004777 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004778 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004779
4780 // These type trait expressions are modeled on the specifications for the
4781 // Embarcadero C++0x type trait functions:
4782 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4783 case UTT_IsCompleteType:
4784 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4785 // Returns True if and only if T is a complete type at the point of the
4786 // function call.
4787 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004788 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004789 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004790 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004791}
Sebastian Redl5822f082009-02-07 20:10:22 +00004792
Alp Tokercbb90342013-12-13 20:49:58 +00004793static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4794 QualType RhsT, SourceLocation KeyLoc);
4795
Douglas Gregor29c42f22012-02-24 07:38:34 +00004796static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4797 ArrayRef<TypeSourceInfo *> Args,
4798 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004799 if (Kind <= UTT_Last)
4800 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4801
Eric Fiselier1af6c112018-01-12 00:09:37 +00004802 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4803 // traits to avoid duplication.
4804 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004805 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4806 Args[1]->getType(), RParenLoc);
4807
Douglas Gregor29c42f22012-02-24 07:38:34 +00004808 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004809 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004810 case clang::TT_IsConstructible:
4811 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004812 case clang::TT_IsTriviallyConstructible: {
4813 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004814 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004815 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004816 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004817 // definition for is_constructible, as defined below, is known to call
4818 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004819 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004820 // The predicate condition for a template specialization
4821 // is_constructible<T, Args...> shall be satisfied if and only if the
4822 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004823 // variable t:
4824 //
4825 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004826 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004827
4828 // Precondition: T and all types in the parameter pack Args shall be
4829 // complete types, (possibly cv-qualified) void, or arrays of
4830 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004831 for (const auto *TSI : Args) {
4832 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004833 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004834 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004835
Simon Pilgrim75c26882016-09-30 14:25:09 +00004836 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004837 diag::err_incomplete_type_used_in_type_trait_expr))
4838 return false;
4839 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004840
David Majnemer9658ecc2015-11-13 05:32:43 +00004841 // Make sure the first argument is not incomplete nor a function type.
4842 QualType T = Args[0]->getType();
4843 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004844 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004845
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004846 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004847 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004848 if (RD && RD->isAbstract())
4849 return false;
4850
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004851 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4852 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004853 ArgExprs.reserve(Args.size() - 1);
4854 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004855 QualType ArgTy = Args[I]->getType();
4856 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4857 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004858 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004859 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4860 ArgTy.getNonLValueExprType(S.Context),
4861 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004862 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004863 for (Expr &E : OpaqueArgExprs)
4864 ArgExprs.push_back(&E);
4865
Simon Pilgrim75c26882016-09-30 14:25:09 +00004866 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004867 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004868 EnterExpressionEvaluationContext Unevaluated(
4869 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004870 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4871 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4872 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4873 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4874 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004875 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004876 if (Init.Failed())
4877 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004878
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004879 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004880 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4881 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004882
Alp Toker73287bf2014-01-20 00:24:09 +00004883 if (Kind == clang::TT_IsConstructible)
4884 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004885
Eric Fiselier1af6c112018-01-12 00:09:37 +00004886 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4887 if (!T->isReferenceType())
4888 return false;
4889
4890 return !Init.isDirectReferenceBinding();
4891 }
4892
Alp Toker73287bf2014-01-20 00:24:09 +00004893 if (Kind == clang::TT_IsNothrowConstructible)
4894 return S.canThrow(Result.get()) == CT_Cannot;
4895
4896 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004897 // Under Objective-C ARC and Weak, if the destination has non-trivial
4898 // Objective-C lifetime, this is a non-trivial construction.
4899 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004900 return false;
4901
4902 // The initialization succeeded; now make sure there are no non-trivial
4903 // calls.
4904 return !Result.get()->hasNonTrivialCall(S.Context);
4905 }
4906
4907 llvm_unreachable("unhandled type trait");
4908 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004909 }
Alp Tokercbb90342013-12-13 20:49:58 +00004910 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004911 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004912
Douglas Gregor29c42f22012-02-24 07:38:34 +00004913 return false;
4914}
4915
Simon Pilgrim75c26882016-09-30 14:25:09 +00004916ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4917 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004918 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004919 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004920
Alp Toker95e7ff22014-01-01 05:57:51 +00004921 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4922 *this, Kind, KWLoc, Args[0]->getType()))
4923 return ExprError();
4924
Douglas Gregor29c42f22012-02-24 07:38:34 +00004925 bool Dependent = false;
4926 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4927 if (Args[I]->getType()->isDependentType()) {
4928 Dependent = true;
4929 break;
4930 }
4931 }
Alp Tokercbb90342013-12-13 20:49:58 +00004932
4933 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004934 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004935 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4936
4937 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4938 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004939}
4940
Alp Toker88f64e62013-12-13 21:19:30 +00004941ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4942 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004943 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004944 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004945 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004946
Douglas Gregor29c42f22012-02-24 07:38:34 +00004947 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4948 TypeSourceInfo *TInfo;
4949 QualType T = GetTypeFromParser(Args[I], &TInfo);
4950 if (!TInfo)
4951 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004952
4953 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004954 }
Alp Tokercbb90342013-12-13 20:49:58 +00004955
Douglas Gregor29c42f22012-02-24 07:38:34 +00004956 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4957}
4958
Alp Tokercbb90342013-12-13 20:49:58 +00004959static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4960 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004961 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4962 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004963
4964 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004965 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004966 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004967 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004968 // Base and Derived are not unions and name the same class type without
4969 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004970
John McCall388ef532011-01-28 22:02:36 +00004971 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004972 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004973 if (!rhsRecord || !lhsRecord) {
4974 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4975 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4976 if (!LHSObjTy || !RHSObjTy)
4977 return false;
4978
4979 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4980 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4981 if (!BaseInterface || !DerivedInterface)
4982 return false;
4983
4984 if (Self.RequireCompleteType(
4985 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4986 return false;
4987
4988 return BaseInterface->isSuperClassOf(DerivedInterface);
4989 }
John McCall388ef532011-01-28 22:02:36 +00004990
4991 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4992 == (lhsRecord == rhsRecord));
4993
4994 if (lhsRecord == rhsRecord)
4995 return !lhsRecord->getDecl()->isUnion();
4996
4997 // C++0x [meta.rel]p2:
4998 // If Base and Derived are class types and are different types
4999 // (ignoring possible cv-qualifiers) then Derived shall be a
5000 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005001 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005002 diag::err_incomplete_type_used_in_type_trait_expr))
5003 return false;
5004
5005 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5006 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5007 }
John Wiegley65497cc2011-04-27 23:09:49 +00005008 case BTT_IsSame:
5009 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005010 case BTT_TypeCompatible: {
5011 // GCC ignores cv-qualifiers on arrays for this builtin.
5012 Qualifiers LhsQuals, RhsQuals;
5013 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5014 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5015 return Self.Context.typesAreCompatible(Lhs, Rhs);
5016 }
John Wiegley65497cc2011-04-27 23:09:49 +00005017 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005018 case BTT_IsConvertibleTo: {
5019 // C++0x [meta.rel]p4:
5020 // Given the following function prototype:
5021 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005022 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005023 // typename add_rvalue_reference<T>::type create();
5024 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005025 // the predicate condition for a template specialization
5026 // is_convertible<From, To> shall be satisfied if and only if
5027 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005028 // well-formed, including any implicit conversions to the return
5029 // type of the function:
5030 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005031 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005032 // return create<From>();
5033 // }
5034 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005035 // Access checking is performed as if in a context unrelated to To and
5036 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005037 // of the return-statement (including conversions to the return type)
5038 // is considered.
5039 //
5040 // We model the initialization as a copy-initialization of a temporary
5041 // of the appropriate type, which for this expression is identical to the
5042 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005043
5044 // Functions aren't allowed to return function or array types.
5045 if (RhsT->isFunctionType() || RhsT->isArrayType())
5046 return false;
5047
5048 // A return statement in a void function must have void type.
5049 if (RhsT->isVoidType())
5050 return LhsT->isVoidType();
5051
5052 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005053 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005054 return false;
5055
5056 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005057 if (LhsT->isObjectType() || LhsT->isFunctionType())
5058 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005059
5060 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005061 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005062 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005063 Expr::getValueKindForType(LhsT));
5064 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005065 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005066 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005067
5068 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005069 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005070 EnterExpressionEvaluationContext Unevaluated(
5071 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005072 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5073 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005074 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005075 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005076 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005077
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005078 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005079 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5080 }
Alp Toker73287bf2014-01-20 00:24:09 +00005081
David Majnemerb3d96882016-05-23 17:21:55 +00005082 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005083 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005084 case BTT_IsTriviallyAssignable: {
5085 // C++11 [meta.unary.prop]p3:
5086 // is_trivially_assignable is defined as:
5087 // is_assignable<T, U>::value is true and the assignment, as defined by
5088 // is_assignable, is known to call no operation that is not trivial
5089 //
5090 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005091 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005092 // treated as an unevaluated operand (Clause 5).
5093 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005094 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005095 // void, or arrays of unknown bound.
5096 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005097 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005098 diag::err_incomplete_type_used_in_type_trait_expr))
5099 return false;
5100 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005101 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005102 diag::err_incomplete_type_used_in_type_trait_expr))
5103 return false;
5104
5105 // cv void is never assignable.
5106 if (LhsT->isVoidType() || RhsT->isVoidType())
5107 return false;
5108
Simon Pilgrim75c26882016-09-30 14:25:09 +00005109 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005110 // declval<U>().
5111 if (LhsT->isObjectType() || LhsT->isFunctionType())
5112 LhsT = Self.Context.getRValueReferenceType(LhsT);
5113 if (RhsT->isObjectType() || RhsT->isFunctionType())
5114 RhsT = Self.Context.getRValueReferenceType(RhsT);
5115 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5116 Expr::getValueKindForType(LhsT));
5117 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5118 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005119
5120 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005121 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005122 EnterExpressionEvaluationContext Unevaluated(
5123 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005124 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005125 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005126 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5127 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005128 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5129 return false;
5130
David Majnemerb3d96882016-05-23 17:21:55 +00005131 if (BTT == BTT_IsAssignable)
5132 return true;
5133
Alp Toker73287bf2014-01-20 00:24:09 +00005134 if (BTT == BTT_IsNothrowAssignable)
5135 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005136
Alp Toker73287bf2014-01-20 00:24:09 +00005137 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005138 // Under Objective-C ARC and Weak, if the destination has non-trivial
5139 // Objective-C lifetime, this is a non-trivial assignment.
5140 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005141 return false;
5142
5143 return !Result.get()->hasNonTrivialCall(Self.Context);
5144 }
5145
5146 llvm_unreachable("unhandled type trait");
5147 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005148 }
Alp Tokercbb90342013-12-13 20:49:58 +00005149 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005150 }
5151 llvm_unreachable("Unknown type trait or not implemented");
5152}
5153
John Wiegley6242b6a2011-04-28 00:16:57 +00005154ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5155 SourceLocation KWLoc,
5156 ParsedType Ty,
5157 Expr* DimExpr,
5158 SourceLocation RParen) {
5159 TypeSourceInfo *TSInfo;
5160 QualType T = GetTypeFromParser(Ty, &TSInfo);
5161 if (!TSInfo)
5162 TSInfo = Context.getTrivialTypeSourceInfo(T);
5163
5164 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5165}
5166
5167static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5168 QualType T, Expr *DimExpr,
5169 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005170 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005171
5172 switch(ATT) {
5173 case ATT_ArrayRank:
5174 if (T->isArrayType()) {
5175 unsigned Dim = 0;
5176 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5177 ++Dim;
5178 T = AT->getElementType();
5179 }
5180 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005181 }
John Wiegleyd3522222011-04-28 02:06:46 +00005182 return 0;
5183
John Wiegley6242b6a2011-04-28 00:16:57 +00005184 case ATT_ArrayExtent: {
5185 llvm::APSInt Value;
5186 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005187 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005188 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005189 false).isInvalid())
5190 return 0;
5191 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005192 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5193 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005194 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005195 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005196 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005197
5198 if (T->isArrayType()) {
5199 unsigned D = 0;
5200 bool Matched = false;
5201 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5202 if (Dim == D) {
5203 Matched = true;
5204 break;
5205 }
5206 ++D;
5207 T = AT->getElementType();
5208 }
5209
John Wiegleyd3522222011-04-28 02:06:46 +00005210 if (Matched && T->isArrayType()) {
5211 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5212 return CAT->getSize().getLimitedValue();
5213 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005214 }
John Wiegleyd3522222011-04-28 02:06:46 +00005215 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005216 }
5217 }
5218 llvm_unreachable("Unknown type trait or not implemented");
5219}
5220
5221ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5222 SourceLocation KWLoc,
5223 TypeSourceInfo *TSInfo,
5224 Expr* DimExpr,
5225 SourceLocation RParen) {
5226 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005227
Chandler Carruthc5276e52011-05-01 08:48:21 +00005228 // FIXME: This should likely be tracked as an APInt to remove any host
5229 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005230 uint64_t Value = 0;
5231 if (!T->isDependentType())
5232 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5233
Chandler Carruthc5276e52011-05-01 08:48:21 +00005234 // While the specification for these traits from the Embarcadero C++
5235 // compiler's documentation says the return type is 'unsigned int', Clang
5236 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5237 // compiler, there is no difference. On several other platforms this is an
5238 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005239 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5240 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005241}
5242
John Wiegleyf9f65842011-04-25 06:54:41 +00005243ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005244 SourceLocation KWLoc,
5245 Expr *Queried,
5246 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005247 // If error parsing the expression, ignore.
5248 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005249 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005250
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005251 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005252
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005253 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005254}
5255
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005256static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5257 switch (ET) {
5258 case ET_IsLValueExpr: return E->isLValue();
5259 case ET_IsRValueExpr: return E->isRValue();
5260 }
5261 llvm_unreachable("Expression trait not covered by switch");
5262}
5263
John Wiegleyf9f65842011-04-25 06:54:41 +00005264ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005265 SourceLocation KWLoc,
5266 Expr *Queried,
5267 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005268 if (Queried->isTypeDependent()) {
5269 // Delay type-checking for type-dependent expressions.
5270 } else if (Queried->getType()->isPlaceholderType()) {
5271 ExprResult PE = CheckPlaceholderExpr(Queried);
5272 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005273 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005274 }
5275
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005276 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005277
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005278 return new (Context)
5279 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005280}
5281
Richard Trieu82402a02011-09-15 21:56:47 +00005282QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005283 ExprValueKind &VK,
5284 SourceLocation Loc,
5285 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005286 assert(!LHS.get()->getType()->isPlaceholderType() &&
5287 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005288 "placeholders should have been weeded out by now");
5289
Richard Smith4baaa5a2016-12-03 01:14:32 +00005290 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5291 // temporary materialization conversion otherwise.
5292 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005293 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005294 else if (LHS.get()->isRValue())
5295 LHS = TemporaryMaterializationConversion(LHS.get());
5296 if (LHS.isInvalid())
5297 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005298
5299 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005300 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005301 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005302
Sebastian Redl5822f082009-02-07 20:10:22 +00005303 const char *OpSpelling = isIndirect ? "->*" : ".*";
5304 // C++ 5.5p2
5305 // The binary operator .* [p3: ->*] binds its second operand, which shall
5306 // be of type "pointer to member of T" (where T is a completely-defined
5307 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005308 QualType RHSType = RHS.get()->getType();
5309 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005310 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005311 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005312 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005313 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005314 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005315
Sebastian Redl5822f082009-02-07 20:10:22 +00005316 QualType Class(MemPtr->getClass(), 0);
5317
Douglas Gregord07ba342010-10-13 20:41:14 +00005318 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5319 // member pointer points must be completely-defined. However, there is no
5320 // reason for this semantic distinction, and the rule is not enforced by
5321 // other compilers. Therefore, we do not check this property, as it is
5322 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005323
Sebastian Redl5822f082009-02-07 20:10:22 +00005324 // C++ 5.5p2
5325 // [...] to its first operand, which shall be of class T or of a class of
5326 // which T is an unambiguous and accessible base class. [p3: a pointer to
5327 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005328 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005329 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005330 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5331 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005332 else {
5333 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005334 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005335 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005336 return QualType();
5337 }
5338 }
5339
Richard Trieu82402a02011-09-15 21:56:47 +00005340 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005341 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005342 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5343 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005344 return QualType();
5345 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005346
Richard Smith0f59cb32015-12-18 21:45:41 +00005347 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005348 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005349 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005350 return QualType();
5351 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005352
5353 CXXCastPath BasePath;
5354 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5355 SourceRange(LHS.get()->getLocStart(),
5356 RHS.get()->getLocEnd()),
5357 &BasePath))
5358 return QualType();
5359
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005360 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005361 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5362 if (isIndirect)
5363 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005364 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005365 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005366 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005367 }
5368
Richard Trieu82402a02011-09-15 21:56:47 +00005369 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005370 // Diagnose use of pointer-to-member type which when used as
5371 // the functional cast in a pointer-to-member expression.
5372 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5373 return QualType();
5374 }
John McCall7decc9e2010-11-18 06:31:45 +00005375
Sebastian Redl5822f082009-02-07 20:10:22 +00005376 // C++ 5.5p2
5377 // The result is an object or a function of the type specified by the
5378 // second operand.
5379 // The cv qualifiers are the union of those in the pointer and the left side,
5380 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005381 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005382 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005383
Douglas Gregor1d042092011-01-26 16:40:18 +00005384 // C++0x [expr.mptr.oper]p6:
5385 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005386 // ill-formed if the second operand is a pointer to member function with
5387 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5388 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005389 // is a pointer to member function with ref-qualifier &&.
5390 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5391 switch (Proto->getRefQualifier()) {
5392 case RQ_None:
5393 // Do nothing
5394 break;
5395
5396 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005397 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5398 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5399 if (Proto->isConst())
5400 Diag(Loc, getLangOpts().CPlusPlus2a
5401 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5402 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5403 else
5404 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5405 << RHSType << 1 << LHS.get()->getSourceRange();
5406 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005407 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005408
Douglas Gregor1d042092011-01-26 16:40:18 +00005409 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005410 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005411 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005412 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005413 break;
5414 }
5415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005416
John McCall7decc9e2010-11-18 06:31:45 +00005417 // C++ [expr.mptr.oper]p6:
5418 // The result of a .* expression whose second operand is a pointer
5419 // to a data member is of the same value category as its
5420 // first operand. The result of a .* expression whose second
5421 // operand is a pointer to a member function is a prvalue. The
5422 // result of an ->* expression is an lvalue if its second operand
5423 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005424 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005425 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005426 return Context.BoundMemberTy;
5427 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005428 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005429 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005430 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005431 }
John McCall7decc9e2010-11-18 06:31:45 +00005432
Sebastian Redl5822f082009-02-07 20:10:22 +00005433 return Result;
5434}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005435
Richard Smith2414bca2016-04-25 19:30:37 +00005436/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005437///
5438/// This is part of the parameter validation for the ? operator. If either
5439/// value operand is a class type, the two operands are attempted to be
5440/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005441/// It returns true if the program is ill-formed and has already been diagnosed
5442/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005443static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5444 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005445 bool &HaveConversion,
5446 QualType &ToType) {
5447 HaveConversion = false;
5448 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449
5450 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005451 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005452 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005453 // The process for determining whether an operand expression E1 of type T1
5454 // can be converted to match an operand expression E2 of type T2 is defined
5455 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005456 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5457 // implicitly converted to type "lvalue reference to T2", subject to the
5458 // constraint that in the conversion the reference must bind directly to
5459 // an lvalue.
5460 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005461 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005462 // the constraint that the reference must bind directly.
5463 if (To->isLValue() || To->isXValue()) {
5464 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5465 : Self.Context.getRValueReferenceType(ToType);
5466
Douglas Gregor838fcc32010-03-26 20:14:36 +00005467 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005469 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005470 if (InitSeq.isDirectReferenceBinding()) {
5471 ToType = T;
5472 HaveConversion = true;
5473 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Douglas Gregor838fcc32010-03-26 20:14:36 +00005476 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005477 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005478 }
John McCall65eb8792010-02-25 01:37:24 +00005479
Sebastian Redl1a99f442009-04-16 17:51:27 +00005480 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5481 // -- if E1 and E2 have class type, and the underlying class types are
5482 // the same or one is a base class of the other:
5483 QualType FTy = From->getType();
5484 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005485 const RecordType *FRec = FTy->getAs<RecordType>();
5486 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005487 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005488 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5489 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5490 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005491 // E1 can be converted to match E2 if the class of T2 is the
5492 // same type as, or a base class of, the class of T1, and
5493 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005494 if (FRec == TRec || FDerivedFromT) {
5495 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005496 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005497 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005498 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005499 HaveConversion = true;
5500 return false;
5501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005502
Douglas Gregor838fcc32010-03-26 20:14:36 +00005503 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005504 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005507
Douglas Gregor838fcc32010-03-26 20:14:36 +00005508 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
Douglas Gregor838fcc32010-03-26 20:14:36 +00005511 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5512 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005514 // an rvalue).
5515 //
5516 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5517 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005518 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005519
Douglas Gregor838fcc32010-03-26 20:14:36 +00005520 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005521 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005522 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005523 ToType = TTy;
5524 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005525 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005526
Sebastian Redl1a99f442009-04-16 17:51:27 +00005527 return false;
5528}
5529
5530/// \brief Try to find a common type for two according to C++0x 5.16p5.
5531///
5532/// This is part of the parameter validation for the ? operator. If either
5533/// value operand is a class type, overload resolution is used to find a
5534/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005535static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005536 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005537 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005538 OverloadCandidateSet CandidateSet(QuestionLoc,
5539 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005540 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005541 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005542
5543 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005544 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005545 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005546 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005547 ExprResult LHSRes = Self.PerformImplicitConversion(
5548 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5549 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005550 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005551 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005552 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005553
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005554 ExprResult RHSRes = Self.PerformImplicitConversion(
5555 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5556 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005557 if (RHSRes.isInvalid())
5558 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005559 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005560 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005561 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005562 return false;
John Wiegley01296292011-04-08 18:41:53 +00005563 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005564
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005565 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005566
5567 // Emit a better diagnostic if one of the expressions is a null pointer
5568 // constant and the other is a pointer type. In this case, the user most
5569 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005570 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005571 return true;
5572
5573 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005574 << LHS.get()->getType() << RHS.get()->getType()
5575 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005576 return true;
5577
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005578 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005579 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005580 << LHS.get()->getType() << RHS.get()->getType()
5581 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005582 // FIXME: Print the possible common types by printing the return types of
5583 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005584 break;
5585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005586 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005587 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005588 }
5589 return true;
5590}
5591
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005592/// \brief Perform an "extended" implicit conversion as returned by
5593/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005594static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005595 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005596 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005597 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005598 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005599 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005600 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005601 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005602 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005603
John Wiegley01296292011-04-08 18:41:53 +00005604 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005605 return false;
5606}
5607
Sebastian Redl1a99f442009-04-16 17:51:27 +00005608/// \brief Check the operands of ?: under C++ semantics.
5609///
5610/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5611/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005612QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5613 ExprResult &RHS, ExprValueKind &VK,
5614 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005615 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005616 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5617 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005618
Richard Smith45edb702012-08-07 22:06:48 +00005619 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005620 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005621 //
5622 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5623 // a is that of a integer vector with the same number of elements and
5624 // size as the vectors of b and c. If one of either b or c is a scalar
5625 // it is implicitly converted to match the type of the vector.
5626 // Otherwise the expression is ill-formed. If both b and c are scalars,
5627 // then b and c are checked and converted to the type of a if possible.
5628 // Unlike the OpenCL ?: operator, the expression is evaluated as
5629 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005630 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005631 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005632 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005633 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005634 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005635 }
5636
John McCall7decc9e2010-11-18 06:31:45 +00005637 // Assume r-value.
5638 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005639 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005640
Sebastian Redl1a99f442009-04-16 17:51:27 +00005641 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005642 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005643 return Context.DependentTy;
5644
Richard Smith45edb702012-08-07 22:06:48 +00005645 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005646 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005647 QualType LTy = LHS.get()->getType();
5648 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005649 bool LVoid = LTy->isVoidType();
5650 bool RVoid = RTy->isVoidType();
5651 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005652 // ... one of the following shall hold:
5653 // -- The second or the third operand (but not both) is a (possibly
5654 // parenthesized) throw-expression; the result is of the type
5655 // and value category of the other.
5656 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5657 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5658 if (LThrow != RThrow) {
5659 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5660 VK = NonThrow->getValueKind();
5661 // DR (no number yet): the result is a bit-field if the
5662 // non-throw-expression operand is a bit-field.
5663 OK = NonThrow->getObjectKind();
5664 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005665 }
5666
Sebastian Redl1a99f442009-04-16 17:51:27 +00005667 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005668 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005669 if (LVoid && RVoid)
5670 return Context.VoidTy;
5671
5672 // Neither holds, error.
5673 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5674 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005675 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005676 return QualType();
5677 }
5678
5679 // Neither is void.
5680
Richard Smithf2b084f2012-08-08 06:13:49 +00005681 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005682 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005683 // either has (cv) class type [...] an attempt is made to convert each of
5684 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005686 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005687 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005688 QualType L2RType, R2LType;
5689 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005690 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005691 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005692 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005693 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005694
Sebastian Redl1a99f442009-04-16 17:51:27 +00005695 // If both can be converted, [...] the program is ill-formed.
5696 if (HaveL2R && HaveR2L) {
5697 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005698 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005699 return QualType();
5700 }
5701
5702 // If exactly one conversion is possible, that conversion is applied to
5703 // the chosen operand and the converted operands are used in place of the
5704 // original operands for the remainder of this section.
5705 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005706 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005707 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005708 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005709 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005710 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005711 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005712 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005713 }
5714 }
5715
Richard Smithf2b084f2012-08-08 06:13:49 +00005716 // C++11 [expr.cond]p3
5717 // if both are glvalues of the same value category and the same type except
5718 // for cv-qualification, an attempt is made to convert each of those
5719 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005720 // FIXME:
5721 // Resolving a defect in P0012R1: we extend this to cover all cases where
5722 // one of the operands is reference-compatible with the other, in order
5723 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005724 ExprValueKind LVK = LHS.get()->getValueKind();
5725 ExprValueKind RVK = RHS.get()->getValueKind();
5726 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005727 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005728 // DerivedToBase was already handled by the class-specific case above.
5729 // FIXME: Should we allow ObjC conversions here?
5730 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5731 if (CompareReferenceRelationship(
5732 QuestionLoc, LTy, RTy, DerivedToBase,
5733 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005734 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5735 // [...] subject to the constraint that the reference must bind
5736 // directly [...]
5737 !RHS.get()->refersToBitField() &&
5738 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005739 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005740 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005741 } else if (CompareReferenceRelationship(
5742 QuestionLoc, RTy, LTy, DerivedToBase,
5743 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005744 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5745 !LHS.get()->refersToBitField() &&
5746 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005747 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5748 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005749 }
5750 }
5751
5752 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005753 // If the second and third operands are glvalues of the same value
5754 // category and have the same type, the result is of that type and
5755 // value category and it is a bit-field if the second or the third
5756 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005757 // We only extend this to bitfields, not to the crazy other kinds of
5758 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005759 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005760 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005761 LHS.get()->isOrdinaryOrBitFieldObject() &&
5762 RHS.get()->isOrdinaryOrBitFieldObject()) {
5763 VK = LHS.get()->getValueKind();
5764 if (LHS.get()->getObjectKind() == OK_BitField ||
5765 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005766 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005767
5768 // If we have function pointer types, unify them anyway to unify their
5769 // exception specifications, if any.
5770 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5771 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005772 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005773 /*ConvertArgs*/false);
5774 LTy = Context.getQualifiedType(LTy, Qs);
5775
5776 assert(!LTy.isNull() && "failed to find composite pointer type for "
5777 "canonically equivalent function ptr types");
5778 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5779 }
5780
John McCall7decc9e2010-11-18 06:31:45 +00005781 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005782 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005783
Richard Smithf2b084f2012-08-08 06:13:49 +00005784 // C++11 [expr.cond]p5
5785 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005786 // do not have the same type, and either has (cv) class type, ...
5787 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5788 // ... overload resolution is used to determine the conversions (if any)
5789 // to be applied to the operands. If the overload resolution fails, the
5790 // program is ill-formed.
5791 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5792 return QualType();
5793 }
5794
Richard Smithf2b084f2012-08-08 06:13:49 +00005795 // C++11 [expr.cond]p6
5796 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005797 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005798 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5799 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005800 if (LHS.isInvalid() || RHS.isInvalid())
5801 return QualType();
5802 LTy = LHS.get()->getType();
5803 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005804
5805 // After those conversions, one of the following shall hold:
5806 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005807 // is of that type. If the operands have class type, the result
5808 // is a prvalue temporary of the result type, which is
5809 // copy-initialized from either the second operand or the third
5810 // operand depending on the value of the first operand.
5811 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5812 if (LTy->isRecordType()) {
5813 // The operands have class type. Make a temporary copy.
5814 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005815
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5817 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005818 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005819 if (LHSCopy.isInvalid())
5820 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821
5822 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5823 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005824 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005825 if (RHSCopy.isInvalid())
5826 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827
John Wiegley01296292011-04-08 18:41:53 +00005828 LHS = LHSCopy;
5829 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005830 }
5831
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005832 // If we have function pointer types, unify them anyway to unify their
5833 // exception specifications, if any.
5834 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5835 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5836 assert(!LTy.isNull() && "failed to find composite pointer type for "
5837 "canonically equivalent function ptr types");
5838 }
5839
Sebastian Redl1a99f442009-04-16 17:51:27 +00005840 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005841 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005842
Douglas Gregor46188682010-05-18 22:42:18 +00005843 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005844 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005845 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5846 /*AllowBothBool*/true,
5847 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005848
Sebastian Redl1a99f442009-04-16 17:51:27 +00005849 // -- The second and third operands have arithmetic or enumeration type;
5850 // the usual arithmetic conversions are performed to bring them to a
5851 // common type, and the result is of that type.
5852 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005853 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005854 if (LHS.isInvalid() || RHS.isInvalid())
5855 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005856 if (ResTy.isNull()) {
5857 Diag(QuestionLoc,
5858 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5859 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5860 return QualType();
5861 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005862
5863 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5864 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5865
5866 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005867 }
5868
5869 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005870 // type and the other is a null pointer constant, or both are null
5871 // pointer constants, at least one of which is non-integral; pointer
5872 // conversions and qualification conversions are performed to bring them
5873 // to their composite pointer type. The result is of the composite
5874 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005875 // -- The second and third operands have pointer to member type, or one has
5876 // pointer to member type and the other is a null pointer constant;
5877 // pointer to member conversions and qualification conversions are
5878 // performed to bring them to a common type, whose cv-qualification
5879 // shall match the cv-qualification of either the second or the third
5880 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005881 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5882 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005883 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005884
Douglas Gregor697a3912010-04-01 22:47:07 +00005885 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005886 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5887 if (!Composite.isNull())
5888 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005889
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005890 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005891 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005892 return QualType();
5893
Sebastian Redl1a99f442009-04-16 17:51:27 +00005894 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005895 << LHS.get()->getType() << RHS.get()->getType()
5896 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005897 return QualType();
5898}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005899
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005900static FunctionProtoType::ExceptionSpecInfo
5901mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5902 FunctionProtoType::ExceptionSpecInfo ESI2,
5903 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5904 ExceptionSpecificationType EST1 = ESI1.Type;
5905 ExceptionSpecificationType EST2 = ESI2.Type;
5906
5907 // If either of them can throw anything, that is the result.
5908 if (EST1 == EST_None) return ESI1;
5909 if (EST2 == EST_None) return ESI2;
5910 if (EST1 == EST_MSAny) return ESI1;
5911 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005912 if (EST1 == EST_NoexceptFalse) return ESI1;
5913 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005914
5915 // If either of them is non-throwing, the result is the other.
5916 if (EST1 == EST_DynamicNone) return ESI2;
5917 if (EST2 == EST_DynamicNone) return ESI1;
5918 if (EST1 == EST_BasicNoexcept) return ESI2;
5919 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005920 if (EST1 == EST_NoexceptTrue) return ESI2;
5921 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005922
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005923 // If we're left with value-dependent computed noexcept expressions, we're
5924 // stuck. Before C++17, we can just drop the exception specification entirely,
5925 // since it's not actually part of the canonical type. And this should never
5926 // happen in C++17, because it would mean we were computing the composite
5927 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00005928 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005929 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005930 "computing composite pointer type of dependent types");
5931 return FunctionProtoType::ExceptionSpecInfo();
5932 }
5933
5934 // Switch over the possibilities so that people adding new values know to
5935 // update this function.
5936 switch (EST1) {
5937 case EST_None:
5938 case EST_DynamicNone:
5939 case EST_MSAny:
5940 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00005941 case EST_DependentNoexcept:
5942 case EST_NoexceptFalse:
5943 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005944 llvm_unreachable("handled above");
5945
5946 case EST_Dynamic: {
5947 // This is the fun case: both exception specifications are dynamic. Form
5948 // the union of the two lists.
5949 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5950 llvm::SmallPtrSet<QualType, 8> Found;
5951 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5952 for (QualType E : Exceptions)
5953 if (Found.insert(S.Context.getCanonicalType(E)).second)
5954 ExceptionTypeStorage.push_back(E);
5955
5956 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5957 Result.Exceptions = ExceptionTypeStorage;
5958 return Result;
5959 }
5960
5961 case EST_Unevaluated:
5962 case EST_Uninstantiated:
5963 case EST_Unparsed:
5964 llvm_unreachable("shouldn't see unresolved exception specifications here");
5965 }
5966
5967 llvm_unreachable("invalid ExceptionSpecificationType");
5968}
5969
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005970/// \brief Find a merged pointer type and convert the two expressions to it.
5971///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005972/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005973/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005974/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005975/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005976///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005977/// \param Loc The location of the operator requiring these two expressions to
5978/// be converted to the composite pointer type.
5979///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005980/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005981QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005982 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005983 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005984 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005985
5986 // C++1z [expr]p14:
5987 // The composite pointer type of two operands p1 and p2 having types T1
5988 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005989 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005990
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005991 // where at least one is a pointer or pointer to member type or
5992 // std::nullptr_t is:
5993 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5994 T1->isNullPtrType();
5995 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5996 T2->isNullPtrType();
5997 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005998 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005999
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006000 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6001 // This can't actually happen, following the standard, but we also use this
6002 // to implement the end of [expr.conv], which hits this case.
6003 //
6004 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6005 if (T1IsPointerLike &&
6006 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006007 if (ConvertArgs)
6008 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6009 ? CK_NullToMemberPointer
6010 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006011 return T1;
6012 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006013 if (T2IsPointerLike &&
6014 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006015 if (ConvertArgs)
6016 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6017 ? CK_NullToMemberPointer
6018 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006019 return T2;
6020 }
Mike Stump11289f42009-09-09 15:08:12 +00006021
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006022 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006023 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006024 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006025 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6026 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006027
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006028 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6029 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6030 // the union of cv1 and cv2;
6031 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6032 // "pointer to function", where the function types are otherwise the same,
6033 // "pointer to function";
6034 // FIXME: This rule is defective: it should also permit removing noexcept
6035 // from a pointer to member function. As a Clang extension, we also
6036 // permit removing 'noreturn', so we generalize this rule to;
6037 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6038 // "pointer to member function" and the pointee types can be unified
6039 // by a function pointer conversion, that conversion is applied
6040 // before checking the following rules.
6041 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6042 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6043 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6044 // respectively;
6045 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6046 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6047 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6048 // T1 or the cv-combined type of T1 and T2, respectively;
6049 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6050 // T2;
6051 //
6052 // If looked at in the right way, these bullets all do the same thing.
6053 // What we do here is, we build the two possible cv-combined types, and try
6054 // the conversions in both directions. If only one works, or if the two
6055 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006056 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006057 //
6058 // Note that this will fail to find a composite pointer type for "pointer
6059 // to void" and "pointer to function". We can't actually perform the final
6060 // conversion in this case, even though a composite pointer type formally
6061 // exists.
6062 SmallVector<unsigned, 4> QualifierUnion;
6063 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006064 QualType Composite1 = T1;
6065 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006066 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006067 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006068 const PointerType *Ptr1, *Ptr2;
6069 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6070 (Ptr2 = Composite2->getAs<PointerType>())) {
6071 Composite1 = Ptr1->getPointeeType();
6072 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006074 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006075 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006076 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006077 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006078
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006079 QualifierUnion.push_back(
6080 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006081 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006082 continue;
6083 }
Mike Stump11289f42009-09-09 15:08:12 +00006084
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006085 const MemberPointerType *MemPtr1, *MemPtr2;
6086 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6087 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6088 Composite1 = MemPtr1->getPointeeType();
6089 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006090
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006091 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006093 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006094 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006095
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006096 QualifierUnion.push_back(
6097 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6098 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6099 MemPtr2->getClass()));
6100 continue;
6101 }
Mike Stump11289f42009-09-09 15:08:12 +00006102
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006103 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006104
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006105 // Cannot unwrap any more types.
6106 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006107 }
Mike Stump11289f42009-09-09 15:08:12 +00006108
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006109 // Apply the function pointer conversion to unify the types. We've already
6110 // unwrapped down to the function types, and we want to merge rather than
6111 // just convert, so do this ourselves rather than calling
6112 // IsFunctionConversion.
6113 //
6114 // FIXME: In order to match the standard wording as closely as possible, we
6115 // currently only do this under a single level of pointers. Ideally, we would
6116 // allow this in general, and set NeedConstBefore to the relevant depth on
6117 // the side(s) where we changed anything.
6118 if (QualifierUnion.size() == 1) {
6119 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6120 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6121 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6122 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6123
6124 // The result is noreturn if both operands are.
6125 bool Noreturn =
6126 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6127 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6128 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6129
6130 // The result is nothrow if both operands are.
6131 SmallVector<QualType, 8> ExceptionTypeStorage;
6132 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6133 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6134 ExceptionTypeStorage);
6135
6136 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6137 FPT1->getParamTypes(), EPI1);
6138 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6139 FPT2->getParamTypes(), EPI2);
6140 }
6141 }
6142 }
6143
Richard Smith5e9746f2016-10-21 22:00:42 +00006144 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006145 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006146 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006147 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006148 for (unsigned I = 0; I != NeedConstBefore; ++I)
6149 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006150 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006152
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006153 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006154 auto MOC = MemberOfClass.rbegin();
6155 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6156 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6157 auto Classes = *MOC++;
6158 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006159 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006160 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006161 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006162 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006163 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006164 } else {
6165 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006166 Composite1 =
6167 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6168 Composite2 =
6169 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006170 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006171 }
6172
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006173 struct Conversion {
6174 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006175 Expr *&E1, *&E2;
6176 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006177 InitializedEntity Entity;
6178 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006179 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006180 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006181
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006182 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6183 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006184 : S(S), E1(E1), E2(E2), Composite(Composite),
6185 Entity(InitializedEntity::InitializeTemporary(Composite)),
6186 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6187 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6188 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006189
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006190 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006191 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6192 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006193 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006194 E1 = E1Result.getAs<Expr>();
6195
6196 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6197 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006198 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006199 E2 = E2Result.getAs<Expr>();
6200
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006201 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006202 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006203 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006204
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006205 // Try to convert to each composite pointer type.
6206 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006207 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6208 if (ConvertArgs && C1.perform())
6209 return QualType();
6210 return C1.Composite;
6211 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006212 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006213
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006214 if (C1.Viable == C2.Viable) {
6215 // Either Composite1 and Composite2 are viable and are different, or
6216 // neither is viable.
6217 // FIXME: How both be viable and different?
6218 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006219 }
6220
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006221 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006222 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6223 return QualType();
6224
6225 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006226}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006227
John McCalldadc5752010-08-24 06:29:42 +00006228ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006229 if (!E)
6230 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006231
John McCall31168b02011-06-15 23:02:42 +00006232 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6233
6234 // If the result is a glvalue, we shouldn't bind it.
6235 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006236 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006237
John McCall31168b02011-06-15 23:02:42 +00006238 // In ARC, calls that return a retainable type can return retained,
6239 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006240 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006241 E->getType()->isObjCRetainableType()) {
6242
6243 bool ReturnsRetained;
6244
6245 // For actual calls, we compute this by examining the type of the
6246 // called value.
6247 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6248 Expr *Callee = Call->getCallee()->IgnoreParens();
6249 QualType T = Callee->getType();
6250
6251 if (T == Context.BoundMemberTy) {
6252 // Handle pointer-to-members.
6253 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6254 T = BinOp->getRHS()->getType();
6255 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6256 T = Mem->getMemberDecl()->getType();
6257 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006258
John McCall31168b02011-06-15 23:02:42 +00006259 if (const PointerType *Ptr = T->getAs<PointerType>())
6260 T = Ptr->getPointeeType();
6261 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6262 T = Ptr->getPointeeType();
6263 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6264 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006265
John McCall31168b02011-06-15 23:02:42 +00006266 const FunctionType *FTy = T->getAs<FunctionType>();
6267 assert(FTy && "call to value not of function type?");
6268 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6269
6270 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6271 // type always produce a +1 object.
6272 } else if (isa<StmtExpr>(E)) {
6273 ReturnsRetained = true;
6274
Ted Kremeneke65b0862012-03-06 20:05:56 +00006275 // We hit this case with the lambda conversion-to-block optimization;
6276 // we don't want any extra casts here.
6277 } else if (isa<CastExpr>(E) &&
6278 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006279 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006280
John McCall31168b02011-06-15 23:02:42 +00006281 // For message sends and property references, we try to find an
6282 // actual method. FIXME: we should infer retention by selector in
6283 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006284 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006285 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006286 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6287 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006288 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6289 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006290 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006291 // Don't do reclaims if we're using the zero-element array
6292 // constant.
6293 if (ArrayLit->getNumElements() == 0 &&
6294 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6295 return E;
6296
Ted Kremeneke65b0862012-03-06 20:05:56 +00006297 D = ArrayLit->getArrayWithObjectsMethod();
6298 } else if (ObjCDictionaryLiteral *DictLit
6299 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006300 // Don't do reclaims if we're using the zero-element dictionary
6301 // constant.
6302 if (DictLit->getNumElements() == 0 &&
6303 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6304 return E;
6305
Ted Kremeneke65b0862012-03-06 20:05:56 +00006306 D = DictLit->getDictWithObjectsMethod();
6307 }
John McCall31168b02011-06-15 23:02:42 +00006308
6309 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006310
6311 // Don't do reclaims on performSelector calls; despite their
6312 // return type, the invoked method doesn't necessarily actually
6313 // return an object.
6314 if (!ReturnsRetained &&
6315 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006316 return E;
John McCall31168b02011-06-15 23:02:42 +00006317 }
6318
John McCall16de4d22011-11-14 19:53:16 +00006319 // Don't reclaim an object of Class type.
6320 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006321 return E;
John McCall16de4d22011-11-14 19:53:16 +00006322
Tim Shen4a05bb82016-06-21 20:29:17 +00006323 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006324
John McCall2d637d22011-09-10 06:18:15 +00006325 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6326 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006327 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6328 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006329 }
6330
David Blaikiebbafb8a2012-03-11 07:00:24 +00006331 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006332 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006333
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006334 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6335 // a fast path for the common case that the type is directly a RecordType.
6336 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006337 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006338 while (!RT) {
6339 switch (T->getTypeClass()) {
6340 case Type::Record:
6341 RT = cast<RecordType>(T);
6342 break;
6343 case Type::ConstantArray:
6344 case Type::IncompleteArray:
6345 case Type::VariableArray:
6346 case Type::DependentSizedArray:
6347 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6348 break;
6349 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006350 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006351 }
6352 }
Mike Stump11289f42009-09-09 15:08:12 +00006353
Richard Smithfd555f62012-02-22 02:04:18 +00006354 // That should be enough to guarantee that this type is complete, if we're
6355 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006356 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006357 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006358 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006359
6360 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006361 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006362
John McCall31168b02011-06-15 23:02:42 +00006363 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006364 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006365 CheckDestructorAccess(E->getExprLoc(), Destructor,
6366 PDiag(diag::err_access_dtor_temp)
6367 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006368 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6369 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006370
Richard Smithfd555f62012-02-22 02:04:18 +00006371 // If destructor is trivial, we can avoid the extra copy.
6372 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006373 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006374
John McCall28fc7092011-11-10 05:35:25 +00006375 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006376 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006377 }
Richard Smitheec915d62012-02-18 04:13:32 +00006378
6379 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006380 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6381
6382 if (IsDecltype)
6383 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6384
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006385 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006386}
6387
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006388ExprResult
John McCall5d413782010-12-06 08:20:24 +00006389Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006390 if (SubExpr.isInvalid())
6391 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006392
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006393 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006394}
6395
John McCall28fc7092011-11-10 05:35:25 +00006396Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006397 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006398
Eli Friedman3bda6b12012-02-02 23:15:15 +00006399 CleanupVarDeclMarking();
6400
John McCall28fc7092011-11-10 05:35:25 +00006401 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6402 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006403 assert(Cleanup.exprNeedsCleanups() ||
6404 ExprCleanupObjects.size() == FirstCleanup);
6405 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006406 return SubExpr;
6407
Craig Topper5fc8fc22014-08-27 06:28:36 +00006408 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6409 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006410
Tim Shen4a05bb82016-06-21 20:29:17 +00006411 auto *E = ExprWithCleanups::Create(
6412 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006413 DiscardCleanupsInEvaluationContext();
6414
6415 return E;
6416}
6417
John McCall5d413782010-12-06 08:20:24 +00006418Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006419 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006420
Eli Friedman3bda6b12012-02-02 23:15:15 +00006421 CleanupVarDeclMarking();
6422
Tim Shen4a05bb82016-06-21 20:29:17 +00006423 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006424 return SubStmt;
6425
6426 // FIXME: In order to attach the temporaries, wrap the statement into
6427 // a StmtExpr; currently this is only used for asm statements.
6428 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6429 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006430 CompoundStmt *CompStmt = CompoundStmt::Create(
6431 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006432 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6433 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006434 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006435}
6436
Richard Smithfd555f62012-02-22 02:04:18 +00006437/// Process the expression contained within a decltype. For such expressions,
6438/// certain semantic checks on temporaries are delayed until this point, and
6439/// are omitted for the 'topmost' call in the decltype expression. If the
6440/// topmost call bound a temporary, strip that temporary off the expression.
6441ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006442 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006443
6444 // C++11 [expr.call]p11:
6445 // If a function call is a prvalue of object type,
6446 // -- if the function call is either
6447 // -- the operand of a decltype-specifier, or
6448 // -- the right operand of a comma operator that is the operand of a
6449 // decltype-specifier,
6450 // a temporary object is not introduced for the prvalue.
6451
6452 // Recursively rebuild ParenExprs and comma expressions to strip out the
6453 // outermost CXXBindTemporaryExpr, if any.
6454 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6455 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6456 if (SubExpr.isInvalid())
6457 return ExprError();
6458 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006459 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006460 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006461 }
6462 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6463 if (BO->getOpcode() == BO_Comma) {
6464 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6465 if (RHS.isInvalid())
6466 return ExprError();
6467 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006468 return E;
6469 return new (Context) BinaryOperator(
6470 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006471 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006472 }
6473 }
6474
6475 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006476 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6477 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006478 if (TopCall)
6479 E = TopCall;
6480 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006481 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006482
6483 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006484 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006485
Richard Smithf86b0ae2012-07-28 19:54:11 +00006486 // In MS mode, don't perform any extra checking of call return types within a
6487 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006488 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006489 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006490
Richard Smithfd555f62012-02-22 02:04:18 +00006491 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006492 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6493 I != N; ++I) {
6494 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006495 if (Call == TopCall)
6496 continue;
6497
David Majnemerced8bdf2015-02-25 17:36:15 +00006498 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006499 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006500 Call, Call->getDirectCallee()))
6501 return ExprError();
6502 }
6503
6504 // Now all relevant types are complete, check the destructors are accessible
6505 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006506 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6507 I != N; ++I) {
6508 CXXBindTemporaryExpr *Bind =
6509 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006510 if (Bind == TopBind)
6511 continue;
6512
6513 CXXTemporary *Temp = Bind->getTemporary();
6514
6515 CXXRecordDecl *RD =
6516 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6517 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6518 Temp->setDestructor(Destructor);
6519
Richard Smith7d847b12012-05-11 22:20:10 +00006520 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6521 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006522 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006523 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006524 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6525 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006526
6527 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006528 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006529 }
6530
6531 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006532 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006533}
6534
Richard Smith79c927b2013-11-06 19:31:51 +00006535/// Note a set of 'operator->' functions that were used for a member access.
6536static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006537 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006538 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6539 // FIXME: Make this configurable?
6540 unsigned Limit = 9;
6541 if (OperatorArrows.size() > Limit) {
6542 // Produce Limit-1 normal notes and one 'skipping' note.
6543 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6544 SkipCount = OperatorArrows.size() - (Limit - 1);
6545 }
6546
6547 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6548 if (I == SkipStart) {
6549 S.Diag(OperatorArrows[I]->getLocation(),
6550 diag::note_operator_arrows_suppressed)
6551 << SkipCount;
6552 I += SkipCount;
6553 } else {
6554 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6555 << OperatorArrows[I]->getCallResultType();
6556 ++I;
6557 }
6558 }
6559}
6560
Nico Weber964d3322015-02-16 22:35:45 +00006561ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6562 SourceLocation OpLoc,
6563 tok::TokenKind OpKind,
6564 ParsedType &ObjectType,
6565 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006566 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006567 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006568 if (Result.isInvalid()) return ExprError();
6569 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006570
John McCall526ab472011-10-25 17:37:35 +00006571 Result = CheckPlaceholderExpr(Base);
6572 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006573 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006574
John McCallb268a282010-08-23 23:25:46 +00006575 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006576 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006577 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006578 // If we have a pointer to a dependent type and are using the -> operator,
6579 // the object type is the type that the pointer points to. We might still
6580 // have enough information about that type to do something useful.
6581 if (OpKind == tok::arrow)
6582 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6583 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
John McCallba7bf592010-08-24 05:47:05 +00006585 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006586 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006587 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006588 }
Mike Stump11289f42009-09-09 15:08:12 +00006589
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006590 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006591 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006592 // returned, with the original second operand.
6593 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006594 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006595 bool NoArrowOperatorFound = false;
6596 bool FirstIteration = true;
6597 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006598 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006599 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006600 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006601 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006603 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006604 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6605 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006606 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006607 noteOperatorArrows(*this, OperatorArrows);
6608 Diag(OpLoc, diag::note_operator_arrow_depth)
6609 << getLangOpts().ArrowDepth;
6610 return ExprError();
6611 }
6612
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006613 Result = BuildOverloadedArrowExpr(
6614 S, Base, OpLoc,
6615 // When in a template specialization and on the first loop iteration,
6616 // potentially give the default diagnostic (with the fixit in a
6617 // separate note) instead of having the error reported back to here
6618 // and giving a diagnostic with a fixit attached to the error itself.
6619 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006620 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006621 : &NoArrowOperatorFound);
6622 if (Result.isInvalid()) {
6623 if (NoArrowOperatorFound) {
6624 if (FirstIteration) {
6625 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006626 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006627 << FixItHint::CreateReplacement(OpLoc, ".");
6628 OpKind = tok::period;
6629 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006630 }
6631 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6632 << BaseType << Base->getSourceRange();
6633 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006634 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006635 Diag(CD->getLocStart(),
6636 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006637 }
6638 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006639 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006640 }
John McCallb268a282010-08-23 23:25:46 +00006641 Base = Result.get();
6642 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006643 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006644 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006645 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006646 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006647 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6648 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006649 return ExprError();
6650 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006651 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006652 }
Mike Stump11289f42009-09-09 15:08:12 +00006653
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006654 if (OpKind == tok::arrow &&
6655 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006656 BaseType = BaseType->getPointeeType();
6657 }
Mike Stump11289f42009-09-09 15:08:12 +00006658
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006659 // Objective-C properties allow "." access on Objective-C pointer types,
6660 // so adjust the base type to the object type itself.
6661 if (BaseType->isObjCObjectPointerType())
6662 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006663
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006664 // C++ [basic.lookup.classref]p2:
6665 // [...] If the type of the object expression is of pointer to scalar
6666 // type, the unqualified-id is looked up in the context of the complete
6667 // postfix-expression.
6668 //
6669 // This also indicates that we could be parsing a pseudo-destructor-name.
6670 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006671 // expressions or normal member (ivar or property) access expressions, and
6672 // it's legal for the type to be incomplete if this is a pseudo-destructor
6673 // call. We'll do more incomplete-type checks later in the lookup process,
6674 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006675 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006676 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006677 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006678 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006679 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006680 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006681 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006682 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006683 }
Mike Stump11289f42009-09-09 15:08:12 +00006684
Douglas Gregor3024f072012-04-16 07:05:22 +00006685 // The object type must be complete (or dependent), or
6686 // C++11 [expr.prim.general]p3:
6687 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006688 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006689 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006690 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006691 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006692 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006693 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006695 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006696 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006697 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006698 // type C (or of pointer to a class type C), the unqualified-id is looked
6699 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006700 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006701 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006702}
6703
Simon Pilgrim75c26882016-09-30 14:25:09 +00006704static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006705 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006706 if (Base->hasPlaceholderType()) {
6707 ExprResult result = S.CheckPlaceholderExpr(Base);
6708 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006709 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006710 }
6711 ObjectType = Base->getType();
6712
David Blaikie1d578782011-12-16 16:03:09 +00006713 // C++ [expr.pseudo]p2:
6714 // The left-hand side of the dot operator shall be of scalar type. The
6715 // left-hand side of the arrow operator shall be of pointer to scalar type.
6716 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006717 // Note that this is rather different from the normal handling for the
6718 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006719 if (OpKind == tok::arrow) {
6720 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6721 ObjectType = Ptr->getPointeeType();
6722 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006723 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006724 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6725 << ObjectType << true
6726 << FixItHint::CreateReplacement(OpLoc, ".");
6727 if (S.isSFINAEContext())
6728 return true;
6729
6730 OpKind = tok::period;
6731 }
6732 }
6733
6734 return false;
6735}
6736
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006737/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6738/// pointer objects.
6739static bool
6740canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6741 QualType DestructedType) {
6742 // If this is a record type, check if its destructor is callable.
6743 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6744 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6745 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6746 return false;
6747 }
6748
6749 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6750 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6751 DestructedType->isVectorType();
6752}
6753
John McCalldadc5752010-08-24 06:29:42 +00006754ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006755 SourceLocation OpLoc,
6756 tok::TokenKind OpKind,
6757 const CXXScopeSpec &SS,
6758 TypeSourceInfo *ScopeTypeInfo,
6759 SourceLocation CCLoc,
6760 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006761 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006762 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Eli Friedman0ce4de42012-01-25 04:35:06 +00006764 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006765 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6766 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
Douglas Gregorc5c57342012-09-10 14:57:06 +00006768 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6769 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006770 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006771 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006772 else {
Nico Weber58829272012-01-23 05:50:57 +00006773 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6774 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006775 return ExprError();
6776 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006777 }
6778
6779 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006780 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006781 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006782 if (DestructedTypeInfo) {
6783 QualType DestructedType = DestructedTypeInfo->getType();
6784 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006785 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006786 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6787 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006788 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6789 // Foo *foo;
6790 // foo.~Foo();
6791 if (OpKind == tok::period && ObjectType->isPointerType() &&
6792 Context.hasSameUnqualifiedType(DestructedType,
6793 ObjectType->getPointeeType())) {
6794 auto Diagnostic =
6795 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6796 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006797
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006798 // Issue a fixit only when the destructor is valid.
6799 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6800 *this, DestructedType))
6801 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6802
6803 // Recover by setting the object type to the destructed type and the
6804 // operator to '->'.
6805 ObjectType = DestructedType;
6806 OpKind = tok::arrow;
6807 } else {
6808 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6809 << ObjectType << DestructedType << Base->getSourceRange()
6810 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6811
6812 // Recover by setting the destructed type to the object type.
6813 DestructedType = ObjectType;
6814 DestructedTypeInfo =
6815 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6816 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6817 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006818 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006819 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006820
John McCall31168b02011-06-15 23:02:42 +00006821 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6822 // Okay: just pretend that the user provided the correctly-qualified
6823 // type.
6824 } else {
6825 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6826 << ObjectType << DestructedType << Base->getSourceRange()
6827 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6828 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006829
John McCall31168b02011-06-15 23:02:42 +00006830 // Recover by setting the destructed type to the object type.
6831 DestructedType = ObjectType;
6832 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6833 DestructedTypeStart);
6834 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6835 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006836 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006839 // C++ [expr.pseudo]p2:
6840 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6841 // form
6842 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006844 //
6845 // shall designate the same scalar type.
6846 if (ScopeTypeInfo) {
6847 QualType ScopeType = ScopeTypeInfo->getType();
6848 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006849 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006850
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006851 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006852 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006853 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006854 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006855
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006856 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006857 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006858 }
6859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860
John McCallb268a282010-08-23 23:25:46 +00006861 Expr *Result
6862 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6863 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006864 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006865 ScopeTypeInfo,
6866 CCLoc,
6867 TildeLoc,
6868 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869
David Majnemerced8bdf2015-02-25 17:36:15 +00006870 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006871}
6872
John McCalldadc5752010-08-24 06:29:42 +00006873ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006874 SourceLocation OpLoc,
6875 tok::TokenKind OpKind,
6876 CXXScopeSpec &SS,
6877 UnqualifiedId &FirstTypeName,
6878 SourceLocation CCLoc,
6879 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006880 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006881 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6882 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006883 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006884 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6885 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006886 "Invalid second type name in pseudo-destructor");
6887
Eli Friedman0ce4de42012-01-25 04:35:06 +00006888 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006889 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6890 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006891
6892 // Compute the object type that we should use for name lookup purposes. Only
6893 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006894 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006895 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006896 if (ObjectType->isRecordType())
6897 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006898 else if (ObjectType->isDependentType())
6899 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
6902 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006903 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006904 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006905 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006906 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006907 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006909 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006910 S, &SS, true, false, ObjectTypePtrForLookup,
6911 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006912 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006913 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6914 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006915 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006916 // couldn't find anything useful in scope. Just store the identifier and
6917 // it's location, and we'll perform (qualified) name lookup again at
6918 // template instantiation time.
6919 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6920 SecondTypeName.StartLocation);
6921 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006923 diag::err_pseudo_dtor_destructor_non_type)
6924 << SecondTypeName.Identifier << ObjectType;
6925 if (isSFINAEContext())
6926 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006927
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006928 // Recover by assuming we had the right type all along.
6929 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006930 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006931 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006932 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006933 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006934 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006935 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006936 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006937 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006938 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006939 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006940 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006941 TemplateId->TemplateNameLoc,
6942 TemplateId->LAngleLoc,
6943 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006944 TemplateId->RAngleLoc,
6945 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006946 if (T.isInvalid() || !T.get()) {
6947 // Recover by assuming we had the right type all along.
6948 DestructedType = ObjectType;
6949 } else
6950 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
6953 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006954 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006955 if (!DestructedType.isNull()) {
6956 if (!DestructedTypeInfo)
6957 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006958 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006959 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006962 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006963 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006964 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006965 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006966 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006967 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006969 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006970 S, &SS, true, false, ObjectTypePtrForLookup,
6971 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006972 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006973 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006974 diag::err_pseudo_dtor_destructor_non_type)
6975 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006977 if (isSFINAEContext())
6978 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006979
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006980 // Just drop this type. It's unnecessary anyway.
6981 ScopeType = QualType();
6982 } else
6983 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006984 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006985 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006986 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006987 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006988 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006989 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006990 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006991 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006992 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006993 TemplateId->TemplateNameLoc,
6994 TemplateId->LAngleLoc,
6995 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006996 TemplateId->RAngleLoc,
6997 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006998 if (T.isInvalid() || !T.get()) {
6999 // Recover by dropping this type.
7000 ScopeType = QualType();
7001 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007003 }
7004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007005
Douglas Gregor90ad9222010-02-24 23:02:30 +00007006 if (!ScopeType.isNull() && !ScopeTypeInfo)
7007 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7008 FirstTypeName.StartLocation);
7009
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010
John McCallb268a282010-08-23 23:25:46 +00007011 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007012 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007013 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007014}
7015
David Blaikie1d578782011-12-16 16:03:09 +00007016ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7017 SourceLocation OpLoc,
7018 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007019 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007020 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007021 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007022 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7023 return ExprError();
7024
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007025 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7026 false);
David Blaikie1d578782011-12-16 16:03:09 +00007027
7028 TypeLocBuilder TLB;
7029 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7030 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7031 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7032 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7033
7034 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007035 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007036 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007037}
7038
John Wiegley01296292011-04-08 18:41:53 +00007039ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007040 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007041 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00007042 if (Method->getParent()->isLambda() &&
7043 Method->getConversionType()->isBlockPointerType()) {
7044 // This is a lambda coversion to block pointer; check if the argument
7045 // is a LambdaExpr.
7046 Expr *SubE = E;
7047 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7048 if (CE && CE->getCastKind() == CK_NoOp)
7049 SubE = CE->getSubExpr();
7050 SubE = SubE->IgnoreParens();
7051 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7052 SubE = BE->getSubExpr();
7053 if (isa<LambdaExpr>(SubE)) {
7054 // For the conversion to block pointer on a lambda expression, we
7055 // construct a special BlockLiteral instead; this doesn't really make
7056 // a difference in ARC, but outside of ARC the resulting block literal
7057 // follows the normal lifetime rules for block literals instead of being
7058 // autoreleased.
7059 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007060 PushExpressionEvaluationContext(
7061 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00007062 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
7063 E->getExprLoc(),
7064 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00007065 PopExpressionEvaluationContext();
7066
Eli Friedman98b01ed2012-03-01 04:01:32 +00007067 if (Exp.isInvalid())
7068 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
7069 return Exp;
7070 }
7071 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007072
Craig Topperc3ec1492014-05-26 06:22:03 +00007073 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00007074 FoundDecl, Method);
7075 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00007076 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00007077
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007078 MemberExpr *ME = new (Context) MemberExpr(
7079 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7080 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007081 if (HadMultipleCandidates)
7082 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007083 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007084
Alp Toker314cc812014-01-25 16:55:45 +00007085 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007086 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7087 ResultType = ResultType.getNonLValueExprType(Context);
7088
Douglas Gregor27381f32009-11-23 12:27:39 +00007089 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00007090 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00007091 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00007092
7093 if (CheckFunctionCall(Method, CE,
7094 Method->getType()->castAs<FunctionProtoType>()))
7095 return ExprError();
7096
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007097 return CE;
7098}
7099
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007100ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7101 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007102 // If the operand is an unresolved lookup expression, the expression is ill-
7103 // formed per [over.over]p1, because overloaded function names cannot be used
7104 // without arguments except in explicit contexts.
7105 ExprResult R = CheckPlaceholderExpr(Operand);
7106 if (R.isInvalid())
7107 return R;
7108
7109 // The operand may have been modified when checking the placeholder type.
7110 Operand = R.get();
7111
Richard Smith51ec0cf2017-02-21 01:17:38 +00007112 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007113 // The expression operand for noexcept is in an unevaluated expression
7114 // context, so side effects could result in unintended consequences.
7115 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7116 }
7117
Richard Smithf623c962012-04-17 00:58:00 +00007118 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007119 return new (Context)
7120 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007121}
7122
7123ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7124 Expr *Operand, SourceLocation RParen) {
7125 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007126}
7127
Eli Friedmanf798f652012-05-24 22:04:19 +00007128static bool IsSpecialDiscardedValue(Expr *E) {
7129 // In C++11, discarded-value expressions of a certain form are special,
7130 // according to [expr]p10:
7131 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7132 // expression is an lvalue of volatile-qualified type and it has
7133 // one of the following forms:
7134 E = E->IgnoreParens();
7135
Eli Friedmanc49c2262012-05-24 22:36:31 +00007136 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007137 if (isa<DeclRefExpr>(E))
7138 return true;
7139
Eli Friedmanc49c2262012-05-24 22:36:31 +00007140 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007141 if (isa<ArraySubscriptExpr>(E))
7142 return true;
7143
Eli Friedmanc49c2262012-05-24 22:36:31 +00007144 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007145 if (isa<MemberExpr>(E))
7146 return true;
7147
Eli Friedmanc49c2262012-05-24 22:36:31 +00007148 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007149 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7150 if (UO->getOpcode() == UO_Deref)
7151 return true;
7152
7153 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007154 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007155 if (BO->isPtrMemOp())
7156 return true;
7157
Eli Friedmanc49c2262012-05-24 22:36:31 +00007158 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007159 if (BO->getOpcode() == BO_Comma)
7160 return IsSpecialDiscardedValue(BO->getRHS());
7161 }
7162
Eli Friedmanc49c2262012-05-24 22:36:31 +00007163 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007164 // operands are one of the above, or
7165 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7166 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7167 IsSpecialDiscardedValue(CO->getFalseExpr());
7168 // The related edge case of "*x ?: *x".
7169 if (BinaryConditionalOperator *BCO =
7170 dyn_cast<BinaryConditionalOperator>(E)) {
7171 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7172 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7173 IsSpecialDiscardedValue(BCO->getFalseExpr());
7174 }
7175
7176 // Objective-C++ extensions to the rule.
7177 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7178 return true;
7179
7180 return false;
7181}
7182
John McCall34376a62010-12-04 03:47:34 +00007183/// Perform the conversions required for an expression used in a
7184/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007185ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007186 if (E->hasPlaceholderType()) {
7187 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007188 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007189 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007190 }
7191
John McCallfee942d2010-12-02 02:07:15 +00007192 // C99 6.3.2.1:
7193 // [Except in specific positions,] an lvalue that does not have
7194 // array type is converted to the value stored in the
7195 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007196 if (E->isRValue()) {
7197 // In C, function designators (i.e. expressions of function type)
7198 // are r-values, but we still want to do function-to-pointer decay
7199 // on them. This is both technically correct and convenient for
7200 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007201 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007202 return DefaultFunctionArrayConversion(E);
7203
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007204 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007205 }
John McCallfee942d2010-12-02 02:07:15 +00007206
Eli Friedmanf798f652012-05-24 22:04:19 +00007207 if (getLangOpts().CPlusPlus) {
7208 // The C++11 standard defines the notion of a discarded-value expression;
7209 // normally, we don't need to do anything to handle it, but if it is a
7210 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7211 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007212 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007213 E->getType().isVolatileQualified() &&
7214 IsSpecialDiscardedValue(E)) {
7215 ExprResult Res = DefaultLvalueConversion(E);
7216 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007217 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007218 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007219 }
Richard Smith122f88d2016-12-06 23:52:28 +00007220
7221 // C++1z:
7222 // If the expression is a prvalue after this optional conversion, the
7223 // temporary materialization conversion is applied.
7224 //
7225 // We skip this step: IR generation is able to synthesize the storage for
7226 // itself in the aggregate case, and adding the extra node to the AST is
7227 // just clutter.
7228 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7229 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007230 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007231 }
John McCall34376a62010-12-04 03:47:34 +00007232
7233 // GCC seems to also exclude expressions of incomplete enum type.
7234 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7235 if (!T->getDecl()->isComplete()) {
7236 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007237 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007238 return E;
John McCall34376a62010-12-04 03:47:34 +00007239 }
7240 }
7241
John Wiegley01296292011-04-08 18:41:53 +00007242 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7243 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007244 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007245 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007246
John McCallca61b652010-12-04 12:29:11 +00007247 if (!E->getType()->isVoidType())
7248 RequireCompleteType(E->getExprLoc(), E->getType(),
7249 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007250 return E;
John McCall34376a62010-12-04 03:47:34 +00007251}
7252
Faisal Valia17d19f2013-11-07 05:17:06 +00007253// If we can unambiguously determine whether Var can never be used
7254// in a constant expression, return true.
7255// - if the variable and its initializer are non-dependent, then
7256// we can unambiguously check if the variable is a constant expression.
7257// - if the initializer is not value dependent - we can determine whether
7258// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007259// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007260// never be a constant expression.
7261// - FXIME: if the initializer is dependent, we can still do some analysis and
7262// identify certain cases unambiguously as non-const by using a Visitor:
7263// - such as those that involve odr-use of a ParmVarDecl, involve a new
7264// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007265static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007266 ASTContext &Context) {
7267 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007268 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007269
7270 // If there is no initializer - this can not be a constant expression.
7271 if (!Var->getAnyInitializer(DefVD)) return true;
7272 assert(DefVD);
7273 if (DefVD->isWeak()) return false;
7274 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007275
Faisal Valia17d19f2013-11-07 05:17:06 +00007276 Expr *Init = cast<Expr>(Eval->Value);
7277
7278 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007279 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7280 // of value-dependent expressions, and use it here to determine whether the
7281 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007282 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007283 }
7284
Simon Pilgrim75c26882016-09-30 14:25:09 +00007285 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007286}
7287
Simon Pilgrim75c26882016-09-30 14:25:09 +00007288/// \brief Check if the current lambda has any potential captures
7289/// that must be captured by any of its enclosing lambdas that are ready to
7290/// capture. If there is a lambda that can capture a nested
7291/// potential-capture, go ahead and do so. Also, check to see if any
7292/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007293/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007294
Faisal Valiab3d6462013-12-07 20:22:44 +00007295static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7296 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7297
Simon Pilgrim75c26882016-09-30 14:25:09 +00007298 assert(!S.isUnevaluatedContext());
7299 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007300#ifndef NDEBUG
7301 DeclContext *DC = S.CurContext;
7302 while (DC && isa<CapturedDecl>(DC))
7303 DC = DC->getParent();
7304 assert(
7305 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007306 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007307#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007308
7309 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7310
Faisal Valiab3d6462013-12-07 20:22:44 +00007311 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007312 // lambda (within a generic outer lambda), must be captured by an
7313 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007314 const unsigned NumPotentialCaptures =
7315 CurrentLSI->getNumPotentialVariableCaptures();
7316 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007317 Expr *VarExpr = nullptr;
7318 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007319 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007320 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007321 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007322 // need to check enclosing lambda's for speculative captures.
7323 // For e.g.:
7324 // Even though 'x' is not odr-used, it should be captured.
7325 // int test() {
7326 // const int x = 10;
7327 // auto L = [=](auto a) {
7328 // (void) +x + a;
7329 // };
7330 // }
7331 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007332 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007333 continue;
7334
7335 // If we have a capture-capable lambda for the variable, go ahead and
7336 // capture the variable in that lambda (and all its enclosing lambdas).
7337 if (const Optional<unsigned> Index =
7338 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007339 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007340 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7341 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7342 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007343 }
7344 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007345 VariableCanNeverBeAConstantExpression(Var, S.Context);
7346 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7347 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007348 // can not be used in a constant expression - which means
7349 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007350 // capture violation early, if the variable is un-captureable.
7351 // This is purely for diagnosing errors early. Otherwise, this
7352 // error would get diagnosed when the lambda becomes capture ready.
7353 QualType CaptureType, DeclRefType;
7354 SourceLocation ExprLoc = VarExpr->getExprLoc();
7355 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007356 /*EllipsisLoc*/ SourceLocation(),
7357 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007358 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007359 // We will never be able to capture this variable, and we need
7360 // to be able to in any and all instantiations, so diagnose it.
7361 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007362 /*EllipsisLoc*/ SourceLocation(),
7363 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007364 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007365 }
7366 }
7367 }
7368
Faisal Valiab3d6462013-12-07 20:22:44 +00007369 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007370 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007371 // If we have a capture-capable lambda for 'this', go ahead and capture
7372 // 'this' in that lambda (and all its enclosing lambdas).
7373 if (const Optional<unsigned> Index =
7374 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007375 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007376 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7377 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7378 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7379 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007380 }
7381 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007382
7383 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007384 CurrentLSI->clearPotentialCaptures();
7385}
7386
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007387static ExprResult attemptRecovery(Sema &SemaRef,
7388 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007389 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007390 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7391 Consumer.getLookupResult().getLookupKind());
7392 const CXXScopeSpec *SS = Consumer.getSS();
7393 CXXScopeSpec NewSS;
7394
7395 // Use an approprate CXXScopeSpec for building the expr.
7396 if (auto *NNS = TC.getCorrectionSpecifier())
7397 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7398 else if (SS && !TC.WillReplaceSpecifier())
7399 NewSS = *SS;
7400
Richard Smithde6d6c42015-12-29 19:43:10 +00007401 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007402 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007403 R.addDecl(ND);
7404 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007405 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007406 CXXRecordDecl *Record = nullptr;
7407 if (auto *NNS = TC.getCorrectionSpecifier())
7408 Record = NNS->getAsType()->getAsCXXRecordDecl();
7409 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007410 Record =
7411 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7412 if (Record)
7413 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007414
7415 // Detect and handle the case where the decl might be an implicit
7416 // member.
7417 bool MightBeImplicitMember;
7418 if (!Consumer.isAddressOfOperand())
7419 MightBeImplicitMember = true;
7420 else if (!NewSS.isEmpty())
7421 MightBeImplicitMember = false;
7422 else if (R.isOverloadedResult())
7423 MightBeImplicitMember = false;
7424 else if (R.isUnresolvableResult())
7425 MightBeImplicitMember = true;
7426 else
7427 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7428 isa<IndirectFieldDecl>(ND) ||
7429 isa<MSPropertyDecl>(ND);
7430
7431 if (MightBeImplicitMember)
7432 return SemaRef.BuildPossibleImplicitMemberExpr(
7433 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007434 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007435 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7436 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7437 Ivar->getIdentifier());
7438 }
7439 }
7440
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007441 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7442 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007443}
7444
Kaelyn Takata6c759512014-10-27 18:07:37 +00007445namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007446class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7447 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7448
7449public:
7450 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7451 : TypoExprs(TypoExprs) {}
7452 bool VisitTypoExpr(TypoExpr *TE) {
7453 TypoExprs.insert(TE);
7454 return true;
7455 }
7456};
7457
Kaelyn Takata6c759512014-10-27 18:07:37 +00007458class TransformTypos : public TreeTransform<TransformTypos> {
7459 typedef TreeTransform<TransformTypos> BaseTransform;
7460
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007461 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7462 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007463 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007464 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007465 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007466 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007467
7468 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7469 /// If the TypoExprs were successfully corrected, then the diagnostics should
7470 /// suggest the corrections. Otherwise the diagnostics will not suggest
7471 /// anything (having been passed an empty TypoCorrection).
7472 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007473 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007474 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007475 if (State.DiagHandler) {
7476 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7477 ExprResult Replacement = TransformCache[TE];
7478
7479 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7480 // TypoCorrection, replacing the existing decls. This ensures the right
7481 // NamedDecl is used in diagnostics e.g. in the case where overload
7482 // resolution was used to select one from several possible decls that
7483 // had been stored in the TypoCorrection.
7484 if (auto *ND = getDeclFromExpr(
7485 Replacement.isInvalid() ? nullptr : Replacement.get()))
7486 TC.setCorrectionDecl(ND);
7487
7488 State.DiagHandler(TC);
7489 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007490 SemaRef.clearDelayedTypo(TE);
7491 }
7492 }
7493
7494 /// \brief If corrections for the first TypoExpr have been exhausted for a
7495 /// given combination of the other TypoExprs, retry those corrections against
7496 /// the next combination of substitutions for the other TypoExprs by advancing
7497 /// to the next potential correction of the second TypoExpr. For the second
7498 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7499 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7500 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7501 /// TransformCache). Returns true if there is still any untried combinations
7502 /// of corrections.
7503 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7504 for (auto TE : TypoExprs) {
7505 auto &State = SemaRef.getTypoExprState(TE);
7506 TransformCache.erase(TE);
7507 if (!State.Consumer->finished())
7508 return true;
7509 State.Consumer->resetCorrectionStream();
7510 }
7511 return false;
7512 }
7513
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007514 NamedDecl *getDeclFromExpr(Expr *E) {
7515 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7516 E = OverloadResolution[OE];
7517
7518 if (!E)
7519 return nullptr;
7520 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007521 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007522 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007523 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007524 // FIXME: Add any other expr types that could be be seen by the delayed typo
7525 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007526 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007527 return nullptr;
7528 }
7529
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007530 ExprResult TryTransform(Expr *E) {
7531 Sema::SFINAETrap Trap(SemaRef);
7532 ExprResult Res = TransformExpr(E);
7533 if (Trap.hasErrorOccurred() || Res.isInvalid())
7534 return ExprError();
7535
7536 return ExprFilter(Res.get());
7537 }
7538
Kaelyn Takata6c759512014-10-27 18:07:37 +00007539public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007540 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7541 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007542
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007543 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7544 MultiExprArg Args,
7545 SourceLocation RParenLoc,
7546 Expr *ExecConfig = nullptr) {
7547 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7548 RParenLoc, ExecConfig);
7549 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007550 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007551 Expr *ResultCall = Result.get();
7552 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7553 ResultCall = BE->getSubExpr();
7554 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7555 OverloadResolution[OE] = CE->getCallee();
7556 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007557 }
7558 return Result;
7559 }
7560
Kaelyn Takata6c759512014-10-27 18:07:37 +00007561 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7562
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007563 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7564
Kaelyn Takata6c759512014-10-27 18:07:37 +00007565 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007566 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007567 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007568 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007569
Kaelyn Takata6c759512014-10-27 18:07:37 +00007570 // Exit if either the transform was valid or if there were no TypoExprs
7571 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007572 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007573 !CheckAndAdvanceTypoExprCorrectionStreams())
7574 break;
7575 }
7576
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007577 // Ensure none of the TypoExprs have multiple typo correction candidates
7578 // with the same edit length that pass all the checks and filters.
7579 // TODO: Properly handle various permutations of possible corrections when
7580 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007581 // Also, disable typo correction while attempting the transform when
7582 // handling potentially ambiguous typo corrections as any new TypoExprs will
7583 // have been introduced by the application of one of the correction
7584 // candidates and add little to no value if corrected.
7585 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007586 while (!AmbiguousTypoExprs.empty()) {
7587 auto TE = AmbiguousTypoExprs.back();
7588 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007589 auto &State = SemaRef.getTypoExprState(TE);
7590 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007591 TransformCache.erase(TE);
7592 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007593 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007594 TransformCache.erase(TE);
7595 Res = ExprError();
7596 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007597 }
7598 AmbiguousTypoExprs.remove(TE);
7599 State.Consumer->restoreSavedPosition();
7600 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007601 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007602 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007603
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007604 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007605 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007606 FindTypoExprs(TypoExprs).TraverseStmt(E);
7607
Kaelyn Takata6c759512014-10-27 18:07:37 +00007608 EmitAllDiagnostics();
7609
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007610 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007611 }
7612
7613 ExprResult TransformTypoExpr(TypoExpr *E) {
7614 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7615 // cached transformation result if there is one and the TypoExpr isn't the
7616 // first one that was encountered.
7617 auto &CacheEntry = TransformCache[E];
7618 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7619 return CacheEntry;
7620 }
7621
7622 auto &State = SemaRef.getTypoExprState(E);
7623 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7624
7625 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7626 // typo correction and return it.
7627 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007628 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007629 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007630 // FIXME: If we would typo-correct to an invalid declaration, it's
7631 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007632 ExprResult NE = State.RecoveryHandler ?
7633 State.RecoveryHandler(SemaRef, E, TC) :
7634 attemptRecovery(SemaRef, *State.Consumer, TC);
7635 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007636 // Check whether there may be a second viable correction with the same
7637 // edit distance; if so, remember this TypoExpr may have an ambiguous
7638 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007639 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007640 if ((Next = State.Consumer->peekNextCorrection()) &&
7641 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7642 AmbiguousTypoExprs.insert(E);
7643 } else {
7644 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007645 }
7646 assert(!NE.isUnset() &&
7647 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007648 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007649 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007650 }
7651 return CacheEntry = ExprError();
7652 }
7653};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007654}
Faisal Valia17d19f2013-11-07 05:17:06 +00007655
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007656ExprResult
7657Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7658 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007659 // If the current evaluation context indicates there are uncorrected typos
7660 // and the current expression isn't guaranteed to not have typos, try to
7661 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007662 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007663 (E->isTypeDependent() || E->isValueDependent() ||
7664 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007665 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7666 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7667 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007668 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007669 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007670 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007671 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007672 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007673 ExprEvalContexts.back().NumTypos -= TyposResolved;
7674 return Result;
7675 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007676 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007677 }
7678 return E;
7679}
7680
Richard Smith945f8d32013-01-14 22:39:08 +00007681ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007682 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007683 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007684 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007685 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007686
7687 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007688 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007689
7690 // If we are an init-expression in a lambdas init-capture, we should not
7691 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007692 // containing full-expression is done).
7693 // template<class ... Ts> void test(Ts ... t) {
7694 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7695 // return a;
7696 // }() ...);
7697 // }
7698 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7699 // when we parse the lambda introducer, and teach capturing (but not
7700 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7701 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7702 // lambda where we've entered the introducer but not the body, or represent a
7703 // lambda where we've entered the body, depending on where the
7704 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007705 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007706 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007707 return ExprError();
7708
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007709 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007710 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007711 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007712 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007713 if (FullExpr.isInvalid())
7714 return ExprError();
7715 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007716
Richard Smith945f8d32013-01-14 22:39:08 +00007717 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007718 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007719 if (FullExpr.isInvalid())
7720 return ExprError();
7721
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007722 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007723 if (FullExpr.isInvalid())
7724 return ExprError();
7725 }
John Wiegley01296292011-04-08 18:41:53 +00007726
Kaelyn Takata49d84322014-11-11 23:26:56 +00007727 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7728 if (FullExpr.isInvalid())
7729 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007730
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007731 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007732
Simon Pilgrim75c26882016-09-30 14:25:09 +00007733 // At the end of this full expression (which could be a deeply nested
7734 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007735 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007736 // Consider the following code:
7737 // void f(int, int);
7738 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007739 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007740 // const int x = 10, y = 20;
7741 // auto L = [=](auto a) {
7742 // auto M = [=](auto b) {
7743 // f(x, b); <-- requires x to be captured by L and M
7744 // f(y, a); <-- requires y to be captured by L, but not all Ms
7745 // };
7746 // };
7747 // }
7748
Simon Pilgrim75c26882016-09-30 14:25:09 +00007749 // FIXME: Also consider what happens for something like this that involves
7750 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007751 // void f() {
7752 // const int n = 0;
7753 // auto L = [&](auto a) {
7754 // +n + ({ 0; a; });
7755 // };
7756 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007757 //
7758 // Here, we see +n, and then the full-expression 0; ends, so we don't
7759 // capture n (and instead remove it from our list of potential captures),
7760 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007761 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007762
Alexey Bataev31939e32016-11-11 12:36:20 +00007763 LambdaScopeInfo *const CurrentLSI =
7764 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007765 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007766 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007767 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007768 // By ensuring we are in the context of a lambda's call operator
7769 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007770 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007771 // PR, a proper fix would entail :
7772 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007773 // - Add to Sema an integer holding the smallest (outermost) scope
7774 // index that we are *lexically* within, and save/restore/set to
7775 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007776 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007777 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007778 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007779 DeclContext *DC = CurContext;
7780 while (DC && isa<CapturedDecl>(DC))
7781 DC = DC->getParent();
7782 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007783 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007784 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007785 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7786 *this);
John McCall5d413782010-12-06 08:20:24 +00007787 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007788}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007789
7790StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7791 if (!FullStmt) return StmtError();
7792
John McCall5d413782010-12-06 08:20:24 +00007793 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007794}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007795
Simon Pilgrim75c26882016-09-30 14:25:09 +00007796Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007797Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7798 CXXScopeSpec &SS,
7799 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007800 DeclarationName TargetName = TargetNameInfo.getName();
7801 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007802 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007803
Douglas Gregor43edb322011-10-24 22:31:10 +00007804 // If the name itself is dependent, then the result is dependent.
7805 if (TargetName.isDependentName())
7806 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007807
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007808 // Do the redeclaration lookup in the current scope.
7809 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7810 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007811 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007812 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007813
Douglas Gregor43edb322011-10-24 22:31:10 +00007814 switch (R.getResultKind()) {
7815 case LookupResult::Found:
7816 case LookupResult::FoundOverloaded:
7817 case LookupResult::FoundUnresolvedValue:
7818 case LookupResult::Ambiguous:
7819 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007820
Douglas Gregor43edb322011-10-24 22:31:10 +00007821 case LookupResult::NotFound:
7822 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007823
Douglas Gregor43edb322011-10-24 22:31:10 +00007824 case LookupResult::NotFoundInCurrentInstantiation:
7825 return IER_Dependent;
7826 }
David Blaikie8a40f702012-01-17 06:56:22 +00007827
7828 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007829}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007830
Simon Pilgrim75c26882016-09-30 14:25:09 +00007831Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007832Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7833 bool IsIfExists, CXXScopeSpec &SS,
7834 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007835 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007836
Richard Smith151c4562016-12-20 21:35:28 +00007837 // Check for an unexpanded parameter pack.
7838 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7839 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7840 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007841 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007842
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007843 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7844}