blob: 4baf52f5b78fb3449333fafb17bb9a6bf1019442 [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 &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000698 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000699 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000700
Justin Lebar2a8db342016-09-28 22:45:54 +0000701 // Exceptions aren't allowed in CUDA device code.
702 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000703 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
704 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000705
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000706 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
707 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
708
John Wiegley01296292011-04-08 18:41:53 +0000709 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000710 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
711 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000712 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000713
714 // Initialize the exception result. This implicitly weeds out
715 // abstract types or types with inaccessible copy constructors.
716
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
720 //
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or
723 // catch-clause
724 // parameter) whose scope does not extend beyond the end of the
725 // innermost enclosing try-block (if there is one), the copy/move
726 // operation from the operand to the exception object (15.1) can be
727 // omitted by constructing the automatic object directly into the
728 // exception object
729 const VarDecl *NRVOVariable = nullptr;
730 if (IsThrownVarInScope)
731 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
732
733 InitializedEntity Entity = InitializedEntity::InitializeException(
734 OpLoc, ExceptionObjectTy,
735 /*NRVO=*/NRVOVariable != nullptr);
736 ExprResult Res = PerformMoveOrCopyInitialization(
737 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
738 if (Res.isInvalid())
739 return ExprError();
740 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000741 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000742
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000743 return new (Context)
744 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000745}
746
David Majnemere7a818f2015-03-06 18:53:55 +0000747static void
748collectPublicBases(CXXRecordDecl *RD,
749 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
750 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
751 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
752 bool ParentIsPublic) {
753 for (const CXXBaseSpecifier &BS : RD->bases()) {
754 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
755 bool NewSubobject;
756 // Virtual bases constitute the same subobject. Non-virtual bases are
757 // always distinct subobjects.
758 if (BS.isVirtual())
759 NewSubobject = VBases.insert(BaseDecl).second;
760 else
761 NewSubobject = true;
762
763 if (NewSubobject)
764 ++SubobjectsSeen[BaseDecl];
765
766 // Only add subobjects which have public access throughout the entire chain.
767 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
768 if (PublicPath)
769 PublicSubobjectsSeen.insert(BaseDecl);
770
771 // Recurse on to each base subobject.
772 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 PublicPath);
774 }
775}
776
777static void getUnambiguousPublicSubobjects(
778 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
779 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
780 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
781 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
782 SubobjectsSeen[RD] = 1;
783 PublicSubobjectsSeen.insert(RD);
784 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
785 /*ParentIsPublic=*/true);
786
787 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
788 // Skip ambiguous objects.
789 if (SubobjectsSeen[PublicSubobject] > 1)
790 continue;
791
792 Objects.push_back(PublicSubobject);
793 }
794}
795
Sebastian Redl4de47b42009-04-27 20:27:31 +0000796/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
798 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000799 // If the type of the exception would be an incomplete type or a pointer
800 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000801 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000802 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000803 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000804 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000805 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000806 }
807 if (!isPointer || !Ty->isVoidType()) {
808 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000809 isPointer ? diag::err_throw_incomplete_ptr
810 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000811 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000812 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000813
David Majnemerd09a51c2015-03-03 01:50:05 +0000814 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000815 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000816 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000817 }
818
Eli Friedman91a3d272010-06-03 20:39:03 +0000819 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000820 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
821 if (!RD)
822 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000823
Douglas Gregor88d292c2010-05-13 16:44:06 +0000824 // If we are throwing a polymorphic class type or pointer thereof,
825 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000826 MarkVTableUsed(ThrowLoc, RD);
827
Eli Friedman36ebbec2010-10-12 20:32:36 +0000828 // If a pointer is thrown, the referenced object will not be destroyed.
829 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000830 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000831
Richard Smitheec915d62012-02-18 04:13:32 +0000832 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000833 if (!RD->hasIrrelevantDestructor()) {
834 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
835 MarkFunctionReferenced(E->getExprLoc(), Destructor);
836 CheckDestructorAccess(E->getExprLoc(), Destructor,
837 PDiag(diag::err_access_dtor_exception) << Ty);
838 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000839 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000840 }
841 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000842
David Majnemerdfa6d202015-03-11 18:36:39 +0000843 // The MSVC ABI creates a list of all types which can catch the exception
844 // object. This list also references the appropriate copy constructor to call
845 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000847 // We are only interested in the public, unambiguous bases contained within
848 // the exception object. Bases which are ambiguous or otherwise
849 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000850 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
851 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000852
David Majnemere7a818f2015-03-06 18:53:55 +0000853 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000854 // Attempt to lookup the copy constructor. Various pieces of machinery
855 // will spring into action, like template instantiation, which means this
856 // cannot be a simple walk of the class's decls. Instead, we must perform
857 // lookup and overload resolution.
858 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
859 if (!CD)
860 continue;
861
862 // Mark the constructor referenced as it is used by this throw expression.
863 MarkFunctionReferenced(E->getExprLoc(), CD);
864
865 // Skip this copy constructor if it is trivial, we don't need to record it
866 // in the catchable type data.
867 if (CD->isTrivial())
868 continue;
869
870 // The copy constructor is non-trivial, create a mapping from this class
871 // type to this constructor.
872 // N.B. The selection of copy constructor is not sensitive to this
873 // particular throw-site. Lookup will be performed at the catch-site to
874 // ensure that the copy constructor is, in fact, accessible (via
875 // friendship or any other means).
876 Context.addCopyConstructorForExceptionObject(Subobject, CD);
877
878 // We don't keep the instantiated default argument expressions around so
879 // we must rebuild them here.
880 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000881 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
882 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000883 }
884 }
885 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000886
David Majnemerba3e5ec2015-03-13 18:26:17 +0000887 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000888}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000889
Faisal Vali67b04462016-06-11 16:41:54 +0000890static QualType adjustCVQualifiersForCXXThisWithinLambda(
891 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
892 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
893
894 QualType ClassType = ThisTy->getPointeeType();
895 LambdaScopeInfo *CurLSI = nullptr;
896 DeclContext *CurDC = CurSemaContext;
897
898 // Iterate through the stack of lambdas starting from the innermost lambda to
899 // the outermost lambda, checking if '*this' is ever captured by copy - since
900 // that could change the cv-qualifiers of the '*this' object.
901 // The object referred to by '*this' starts out with the cv-qualifiers of its
902 // member function. We then start with the innermost lambda and iterate
903 // outward checking to see if any lambda performs a by-copy capture of '*this'
904 // - and if so, any nested lambda must respect the 'constness' of that
905 // capturing lamdbda's call operator.
906 //
907
Faisal Vali999f27e2017-05-02 20:56:34 +0000908 // Since the FunctionScopeInfo stack is representative of the lexical
909 // nesting of the lambda expressions during initial parsing (and is the best
910 // place for querying information about captures about lambdas that are
911 // partially processed) and perhaps during instantiation of function templates
912 // that contain lambda expressions that need to be transformed BUT not
913 // necessarily during instantiation of a nested generic lambda's function call
914 // operator (which might even be instantiated at the end of the TU) - at which
915 // time the DeclContext tree is mature enough to query capture information
916 // reliably - we use a two pronged approach to walk through all the lexically
917 // enclosing lambda expressions:
918 //
919 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
920 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
921 // enclosed by the call-operator of the LSI below it on the stack (while
922 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
923 // the stack represents the innermost lambda.
924 //
925 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
926 // represents a lambda's call operator. If it does, we must be instantiating
927 // a generic lambda's call operator (represented by the Current LSI, and
928 // should be the only scenario where an inconsistency between the LSI and the
929 // DeclContext should occur), so climb out the DeclContexts if they
930 // represent lambdas, while querying the corresponding closure types
931 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000932
Faisal Vali999f27e2017-05-02 20:56:34 +0000933 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000934 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000935 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
936 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
937 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000938 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
939 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000940
941 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000942 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000943
Faisal Vali67b04462016-06-11 16:41:54 +0000944 auto C = CurLSI->getCXXThisCapture();
945
946 if (C.isCopyCapture()) {
947 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
948 if (CurLSI->CallOperator->isConst())
949 ClassType.addConst();
950 return ASTCtx.getPointerType(ClassType);
951 }
952 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000953
954 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
955 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000956 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +0000957 assert(CurLSI && "While computing 'this' capture-type for a generic "
958 "lambda, we must have a corresponding LambdaScopeInfo");
959 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
960 "While computing 'this' capture-type for a generic lambda, when we "
961 "run out of enclosing LSI's, yet the enclosing DC is a "
962 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
963 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +0000964 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000965
Faisal Vali67b04462016-06-11 16:41:54 +0000966 auto IsThisCaptured =
967 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
968 IsConst = false;
969 IsByCopy = false;
970 for (auto &&C : Closure->captures()) {
971 if (C.capturesThis()) {
972 if (C.getCaptureKind() == LCK_StarThis)
973 IsByCopy = true;
974 if (Closure->getLambdaCallOperator()->isConst())
975 IsConst = true;
976 return true;
977 }
978 }
979 return false;
980 };
981
982 bool IsByCopyCapture = false;
983 bool IsConstCapture = false;
984 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
985 while (Closure &&
986 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
987 if (IsByCopyCapture) {
988 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
989 if (IsConstCapture)
990 ClassType.addConst();
991 return ASTCtx.getPointerType(ClassType);
992 }
993 Closure = isLambdaCallOperator(Closure->getParent())
994 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
995 : nullptr;
996 }
997 }
998 return ASTCtx.getPointerType(ClassType);
999}
1000
Eli Friedman73a04092012-01-07 04:59:52 +00001001QualType Sema::getCurrentThisType() {
1002 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001003 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001004
Richard Smith938f40b2011-06-11 17:19:42 +00001005 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1006 if (method && method->isInstance())
1007 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001008 }
Faisal Validc6b5962016-03-21 09:25:37 +00001009
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001010 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001011 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001012
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001013 assert(isa<CXXRecordDecl>(DC) &&
1014 "Trying to get 'this' type from static method?");
1015
1016 // This is a lambda call operator that is being instantiated as a default
1017 // initializer. DC must point to the enclosing class type, so we can recover
1018 // the 'this' type from it.
1019
1020 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1021 // There are no cv-qualifiers for 'this' within default initializers,
1022 // per [expr.prim.general]p4.
1023 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001024 }
Faisal Vali67b04462016-06-11 16:41:54 +00001025
1026 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1027 // might need to be adjusted if the lambda or any of its enclosing lambda's
1028 // captures '*this' by copy.
1029 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1030 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1031 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001032 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001033}
1034
Simon Pilgrim75c26882016-09-30 14:25:09 +00001035Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001036 Decl *ContextDecl,
1037 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001038 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001039 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1040{
1041 if (!Enabled || !ContextDecl)
1042 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001043
1044 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001045 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1046 Record = Template->getTemplatedDecl();
1047 else
1048 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001049
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001050 // We care only for CVR qualifiers here, so cut everything else.
1051 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001052 S.CXXThisTypeOverride
1053 = S.Context.getPointerType(
1054 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001055
Douglas Gregor3024f072012-04-16 07:05:22 +00001056 this->Enabled = true;
1057}
1058
1059
1060Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1061 if (Enabled) {
1062 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1063 }
1064}
1065
Faisal Validc6b5962016-03-21 09:25:37 +00001066static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1067 QualType ThisTy, SourceLocation Loc,
1068 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001069
Faisal Vali67b04462016-06-11 16:41:54 +00001070 QualType AdjustedThisTy = ThisTy;
1071 // The type of the corresponding data member (not a 'this' pointer if 'by
1072 // copy').
1073 QualType CaptureThisFieldTy = ThisTy;
1074 if (ByCopy) {
1075 // If we are capturing the object referred to by '*this' by copy, ignore any
1076 // cv qualifiers inherited from the type of the member function for the type
1077 // of the closure-type's corresponding data member and any use of 'this'.
1078 CaptureThisFieldTy = ThisTy->getPointeeType();
1079 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1080 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1081 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001082
Faisal Vali67b04462016-06-11 16:41:54 +00001083 FieldDecl *Field = FieldDecl::Create(
1084 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1085 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1086 ICIS_NoInit);
1087
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001088 Field->setImplicit(true);
1089 Field->setAccess(AS_private);
1090 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001091 Expr *This =
1092 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001093 if (ByCopy) {
1094 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1095 UO_Deref,
1096 This).get();
1097 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001098 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001099 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1100 InitializationSequence Init(S, Entity, InitKind, StarThis);
1101 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1102 if (ER.isInvalid()) return nullptr;
1103 return ER.get();
1104 }
1105 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001106}
1107
Simon Pilgrim75c26882016-09-30 14:25:09 +00001108bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001109 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1110 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001111 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001112 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001113 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001114
Faisal Validc6b5962016-03-21 09:25:37 +00001115 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001116
Reid Kleckner87a31802018-03-12 21:43:02 +00001117 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1118 ? *FunctionScopeIndexToStopAt
1119 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001120
Simon Pilgrim75c26882016-09-30 14:25:09 +00001121 // Check that we can capture the *enclosing object* (referred to by '*this')
1122 // by the capturing-entity/closure (lambda/block/etc) at
1123 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1124
1125 // Note: The *enclosing object* can only be captured by-value by a
1126 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001127 // [*this] { ... }.
1128 // Every other capture of the *enclosing object* results in its by-reference
1129 // capture.
1130
1131 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1132 // stack), we can capture the *enclosing object* only if:
1133 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1134 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001135 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001136 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001137 // -- or, there is some enclosing closure 'E' that has already captured the
1138 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001139 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001140 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001141 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001142
1143
Faisal Validc6b5962016-03-21 09:25:37 +00001144 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001145 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001146 if (CapturingScopeInfo *CSI =
1147 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1148 if (CSI->CXXThisCaptureIndex != 0) {
1149 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001150 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001151 break;
1152 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001153 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1154 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1155 // This context can't implicitly capture 'this'; fail out.
1156 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001157 Diag(Loc, diag::err_this_capture)
1158 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001159 return true;
1160 }
Eli Friedman20139d32012-01-11 02:36:31 +00001161 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001162 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001163 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001164 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001165 (Explicit && idx == MaxFunctionScopesIndex)) {
1166 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1167 // iteration through can be an explicit capture, all enclosing closures,
1168 // if any, must perform implicit captures.
1169
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001170 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001171 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001172 continue;
1173 }
Eli Friedman20139d32012-01-11 02:36:31 +00001174 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001175 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001176 Diag(Loc, diag::err_this_capture)
1177 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001178 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001179 }
Eli Friedman73a04092012-01-07 04:59:52 +00001180 break;
1181 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001182 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001183
1184 // If we got here, then the closure at MaxFunctionScopesIndex on the
1185 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1186 // (including implicit by-reference captures in any enclosing closures).
1187
1188 // In the loop below, respect the ByCopy flag only for the closure requesting
1189 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001190 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001191 // implicitly capturing the *enclosing object* by reference (see loop
1192 // above)).
1193 assert((!ByCopy ||
1194 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1195 "Only a lambda can capture the enclosing object (referred to by "
1196 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001197 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1198 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001199 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001200 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1201 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001202 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001203 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001204
Faisal Validc6b5962016-03-21 09:25:37 +00001205 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1206 // For lambda expressions, build a field and an initializing expression,
1207 // and capture the *enclosing object* by copy only if this is the first
1208 // iteration.
1209 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1210 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001211
Faisal Validc6b5962016-03-21 09:25:37 +00001212 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001213 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001214 ThisExpr =
1215 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1216 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001217
Faisal Validc6b5962016-03-21 09:25:37 +00001218 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001219 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001220 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001221 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001222}
1223
Richard Smith938f40b2011-06-11 17:19:42 +00001224ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001225 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1226 /// is a non-lvalue expression whose value is the address of the object for
1227 /// which the function is called.
1228
Douglas Gregor09deffa2011-10-18 16:47:30 +00001229 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001230 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001231
Eli Friedman73a04092012-01-07 04:59:52 +00001232 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001233 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001234}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001235
Douglas Gregor3024f072012-04-16 07:05:22 +00001236bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1237 // If we're outside the body of a member function, then we'll have a specified
1238 // type for 'this'.
1239 if (CXXThisTypeOverride.isNull())
1240 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001241
Douglas Gregor3024f072012-04-16 07:05:22 +00001242 // Determine whether we're looking into a class that's currently being
1243 // defined.
1244 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1245 return Class && Class->isBeingDefined();
1246}
1247
Vedant Kumara14a1f92018-01-17 18:53:51 +00001248/// Parse construction of a specified type.
1249/// Can be interpreted either as function-style casting ("int(x)")
1250/// or class type construction ("ClassType(x,y,z)")
1251/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001252ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001253Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001254 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001255 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001256 SourceLocation RParenOrBraceLoc,
1257 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001258 if (!TypeRep)
1259 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
John McCall97513962010-01-15 18:39:57 +00001261 TypeSourceInfo *TInfo;
1262 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1263 if (!TInfo)
1264 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001265
Vedant Kumara14a1f92018-01-17 18:53:51 +00001266 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1267 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001268 // Avoid creating a non-type-dependent expression that contains typos.
1269 // Non-type-dependent expressions are liable to be discarded without
1270 // checking for embedded typos.
1271 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1272 !Result.get()->isTypeDependent())
1273 Result = CorrectDelayedTyposInExpr(Result.get());
1274 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001275}
1276
Douglas Gregor2b88c112010-09-08 00:15:04 +00001277ExprResult
1278Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001279 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001280 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001281 SourceLocation RParenOrBraceLoc,
1282 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001283 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001284 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001285
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001286 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001287 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1288 // directly. We work around this by dropping the locations of the braces.
1289 SourceRange Locs = ListInitialization
1290 ? SourceRange()
1291 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1292 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1293 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001294 }
1295
Richard Smith600b5262017-01-26 20:40:47 +00001296 assert((!ListInitialization ||
1297 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1298 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001299 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001300
Richard Smith60437622017-02-09 19:17:44 +00001301 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1302 InitializationKind Kind =
1303 Exprs.size()
1304 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001305 ? InitializationKind::CreateDirectList(
1306 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1307 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1308 RParenOrBraceLoc)
1309 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1310 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001311
1312 // C++1z [expr.type.conv]p1:
1313 // If the type is a placeholder for a deduced class type, [...perform class
1314 // template argument deduction...]
1315 DeducedType *Deduced = Ty->getContainedDeducedType();
1316 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1317 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1318 Kind, Exprs);
1319 if (Ty.isNull())
1320 return ExprError();
1321 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1322 }
1323
Douglas Gregordd04d332009-01-16 18:33:17 +00001324 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001325 // If the expression list is a parenthesized single expression, the type
1326 // conversion expression is equivalent (in definedness, and if defined in
1327 // meaning) to the corresponding cast expression.
1328 if (Exprs.size() == 1 && !ListInitialization &&
1329 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001330 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001331 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1332 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001333 }
1334
Richard Smith49a6b6e2017-03-24 01:14:25 +00001335 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001336 QualType ElemTy = Ty;
1337 if (Ty->isArrayType()) {
1338 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001339 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1340 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001341 ElemTy = Context.getBaseElementType(Ty);
1342 }
1343
Richard Smith49a6b6e2017-03-24 01:14:25 +00001344 // There doesn't seem to be an explicit rule against this but sanity demands
1345 // we only construct objects with object types.
1346 if (Ty->isFunctionType())
1347 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1348 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001349
Richard Smith49a6b6e2017-03-24 01:14:25 +00001350 // C++17 [expr.type.conv]p2:
1351 // If the type is cv void and the initializer is (), the expression is a
1352 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001353 if (!Ty->isVoidType() &&
1354 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001355 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001356 return ExprError();
1357
Richard Smith49a6b6e2017-03-24 01:14:25 +00001358 // Otherwise, the expression is a prvalue of the specified type whose
1359 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001360 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1361 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001362
Richard Smith49a6b6e2017-03-24 01:14:25 +00001363 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001364 return Result;
1365
1366 Expr *Inner = Result.get();
1367 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1368 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001369 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1370 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001371 // If we created a CXXTemporaryObjectExpr, that node also represents the
1372 // functional cast. Otherwise, create an explicit cast to represent
1373 // the syntactic form of a functional-style cast that was used here.
1374 //
1375 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1376 // would give a more consistent AST representation than using a
1377 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1378 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001379 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001380 SourceRange Locs = ListInitialization
1381 ? SourceRange()
1382 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001383 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001384 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1385 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001386 }
1387
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001388 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001389}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001390
Richard Smithb2f0f052016-10-10 18:54:32 +00001391/// \brief Determine whether the given function is a non-placement
1392/// deallocation function.
1393static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001394 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1395 return Method->isUsualDeallocationFunction();
1396
1397 if (FD->getOverloadedOperator() != OO_Delete &&
1398 FD->getOverloadedOperator() != OO_Array_Delete)
1399 return false;
1400
1401 unsigned UsualParams = 1;
1402
1403 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1404 S.Context.hasSameUnqualifiedType(
1405 FD->getParamDecl(UsualParams)->getType(),
1406 S.Context.getSizeType()))
1407 ++UsualParams;
1408
1409 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1410 S.Context.hasSameUnqualifiedType(
1411 FD->getParamDecl(UsualParams)->getType(),
1412 S.Context.getTypeDeclType(S.getStdAlignValT())))
1413 ++UsualParams;
1414
1415 return UsualParams == FD->getNumParams();
1416}
1417
1418namespace {
1419 struct UsualDeallocFnInfo {
1420 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001421 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001422 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001423 Destroying(false), HasSizeT(false), HasAlignValT(false),
1424 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001425 // A function template declaration is never a usual deallocation function.
1426 if (!FD)
1427 return;
Richard Smith5b349582017-10-13 01:55:36 +00001428 unsigned NumBaseParams = 1;
1429 if (FD->isDestroyingOperatorDelete()) {
1430 Destroying = true;
1431 ++NumBaseParams;
1432 }
1433 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001434 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001435 else if (FD->getNumParams() == NumBaseParams + 1) {
1436 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001437 HasAlignValT = !HasSizeT;
1438 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001439
1440 // In CUDA, determine how much we'd like / dislike to call this.
1441 if (S.getLangOpts().CUDA)
1442 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1443 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001444 }
1445
1446 operator bool() const { return FD; }
1447
Richard Smithf75dcbe2016-10-11 00:21:10 +00001448 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1449 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001450 // C++ P0722:
1451 // A destroying operator delete is preferred over a non-destroying
1452 // operator delete.
1453 if (Destroying != Other.Destroying)
1454 return Destroying;
1455
Richard Smithf75dcbe2016-10-11 00:21:10 +00001456 // C++17 [expr.delete]p10:
1457 // If the type has new-extended alignment, a function with a parameter
1458 // of type std::align_val_t is preferred; otherwise a function without
1459 // such a parameter is preferred
1460 if (HasAlignValT != Other.HasAlignValT)
1461 return HasAlignValT == WantAlign;
1462
1463 if (HasSizeT != Other.HasSizeT)
1464 return HasSizeT == WantSize;
1465
1466 // Use CUDA call preference as a tiebreaker.
1467 return CUDAPref > Other.CUDAPref;
1468 }
1469
Richard Smithb2f0f052016-10-10 18:54:32 +00001470 DeclAccessPair Found;
1471 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001472 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001473 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001474 };
1475}
1476
1477/// Determine whether a type has new-extended alignment. This may be called when
1478/// the type is incomplete (for a delete-expression with an incomplete pointee
1479/// type), in which case it will conservatively return false if the alignment is
1480/// not known.
1481static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1482 return S.getLangOpts().AlignedAllocation &&
1483 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1484 S.getASTContext().getTargetInfo().getNewAlign();
1485}
1486
1487/// Select the correct "usual" deallocation function to use from a selection of
1488/// deallocation functions (either global or class-scope).
1489static UsualDeallocFnInfo resolveDeallocationOverload(
1490 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1491 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1492 UsualDeallocFnInfo Best;
1493
Richard Smithb2f0f052016-10-10 18:54:32 +00001494 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001495 UsualDeallocFnInfo Info(S, I.getPair());
1496 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1497 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001498 continue;
1499
1500 if (!Best) {
1501 Best = Info;
1502 if (BestFns)
1503 BestFns->push_back(Info);
1504 continue;
1505 }
1506
Richard Smithf75dcbe2016-10-11 00:21:10 +00001507 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001508 continue;
1509
1510 // If more than one preferred function is found, all non-preferred
1511 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001512 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001513 BestFns->clear();
1514
1515 Best = Info;
1516 if (BestFns)
1517 BestFns->push_back(Info);
1518 }
1519
1520 return Best;
1521}
1522
1523/// Determine whether a given type is a class for which 'delete[]' would call
1524/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1525/// we need to store the array size (even if the type is
1526/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001527static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1528 QualType allocType) {
1529 const RecordType *record =
1530 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1531 if (!record) return false;
1532
1533 // Try to find an operator delete[] in class scope.
1534
1535 DeclarationName deleteName =
1536 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1537 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1538 S.LookupQualifiedName(ops, record->getDecl());
1539
1540 // We're just doing this for information.
1541 ops.suppressDiagnostics();
1542
1543 // Very likely: there's no operator delete[].
1544 if (ops.empty()) return false;
1545
1546 // If it's ambiguous, it should be illegal to call operator delete[]
1547 // on this thing, so it doesn't matter if we allocate extra space or not.
1548 if (ops.isAmbiguous()) return false;
1549
Richard Smithb2f0f052016-10-10 18:54:32 +00001550 // C++17 [expr.delete]p10:
1551 // If the deallocation functions have class scope, the one without a
1552 // parameter of type std::size_t is selected.
1553 auto Best = resolveDeallocationOverload(
1554 S, ops, /*WantSize*/false,
1555 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1556 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001557}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001558
Sebastian Redld74dd492012-02-12 18:41:05 +00001559/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001560///
Sebastian Redld74dd492012-02-12 18:41:05 +00001561/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001562/// @code new (memory) int[size][4] @endcode
1563/// or
1564/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001565///
1566/// \param StartLoc The first location of the expression.
1567/// \param UseGlobal True if 'new' was prefixed with '::'.
1568/// \param PlacementLParen Opening paren of the placement arguments.
1569/// \param PlacementArgs Placement new arguments.
1570/// \param PlacementRParen Closing paren of the placement arguments.
1571/// \param TypeIdParens If the type is in parens, the source range.
1572/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001573/// \param Initializer The initializing expression or initializer-list, or null
1574/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001575ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001576Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001577 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001578 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001579 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001580 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001581 // If the specified type is an array, unwrap it and save the expression.
1582 if (D.getNumTypeObjects() > 0 &&
1583 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001584 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001585 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001586 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1587 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001588 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001589 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1590 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001591 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001592 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1593 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001594
Sebastian Redl351bb782008-12-02 14:43:59 +00001595 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001596 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001597 }
1598
Douglas Gregor73341c42009-09-11 00:18:58 +00001599 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001600 if (ArraySize) {
1601 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001602 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1603 break;
1604
1605 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1606 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001607 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001608 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001609 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1610 // shall be a converted constant expression (5.19) of type std::size_t
1611 // and shall evaluate to a strictly positive value.
1612 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1613 assert(IntWidth && "Builtin type of size 0?");
1614 llvm::APSInt Value(IntWidth);
1615 Array.NumElts
1616 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1617 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001618 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001619 } else {
1620 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001621 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001622 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001623 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001624 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001625 if (!Array.NumElts)
1626 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001627 }
1628 }
1629 }
1630 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001631
Craig Topperc3ec1492014-05-26 06:22:03 +00001632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001633 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001634 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001635 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001636
Sebastian Redl6047f072012-02-16 12:22:20 +00001637 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001638 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001639 DirectInitRange = List->getSourceRange();
1640
David Blaikie7b97aef2012-11-07 00:12:38 +00001641 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001642 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001643 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001644 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001645 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001646 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001647 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001648 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001649 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001650 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001651}
1652
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001653static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1654 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001655 if (!Init)
1656 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001657 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1658 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001659 if (isa<ImplicitValueInitExpr>(Init))
1660 return true;
1661 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1662 return !CCE->isListInitialization() &&
1663 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001664 else if (Style == CXXNewExpr::ListInit) {
1665 assert(isa<InitListExpr>(Init) &&
1666 "Shouldn't create list CXXConstructExprs for arrays.");
1667 return true;
1668 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001669 return false;
1670}
1671
Akira Hatanakacae83f72017-06-29 18:48:40 +00001672// Emit a diagnostic if an aligned allocation/deallocation function that is not
1673// implemented in the standard library is selected.
1674static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1675 SourceLocation Loc, bool IsDelete,
1676 Sema &S) {
1677 if (!S.getLangOpts().AlignedAllocationUnavailable)
1678 return;
1679
1680 // Return if there is a definition.
1681 if (FD.isDefined())
1682 return;
1683
1684 bool IsAligned = false;
1685 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001686 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1687 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1688 S.getASTContext().getTargetInfo().getPlatformName());
1689
Akira Hatanakacae83f72017-06-29 18:48:40 +00001690 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001691 << IsDelete << FD.getType().getAsString() << OSName
1692 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001693 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1694 }
1695}
1696
John McCalldadc5752010-08-24 06:29:42 +00001697ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001698Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001699 SourceLocation PlacementLParen,
1700 MultiExprArg PlacementArgs,
1701 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001702 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001703 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001704 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001705 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001706 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001707 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001708 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001709 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001710
Sebastian Redl6047f072012-02-16 12:22:20 +00001711 CXXNewExpr::InitializationStyle initStyle;
1712 if (DirectInitRange.isValid()) {
1713 assert(Initializer && "Have parens but no initializer.");
1714 initStyle = CXXNewExpr::CallInit;
1715 } else if (Initializer && isa<InitListExpr>(Initializer))
1716 initStyle = CXXNewExpr::ListInit;
1717 else {
1718 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1719 isa<CXXConstructExpr>(Initializer)) &&
1720 "Initializer expression that cannot have been implicitly created.");
1721 initStyle = CXXNewExpr::NoInit;
1722 }
1723
1724 Expr **Inits = &Initializer;
1725 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001726 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1727 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1728 Inits = List->getExprs();
1729 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001730 }
1731
Richard Smith60437622017-02-09 19:17:44 +00001732 // C++11 [expr.new]p15:
1733 // A new-expression that creates an object of type T initializes that
1734 // object as follows:
1735 InitializationKind Kind
1736 // - If the new-initializer is omitted, the object is default-
1737 // initialized (8.5); if no initialization is performed,
1738 // the object has indeterminate value
1739 = initStyle == CXXNewExpr::NoInit
1740 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1741 // - Otherwise, the new-initializer is interpreted according to the
1742 // initialization rules of 8.5 for direct-initialization.
1743 : initStyle == CXXNewExpr::ListInit
Vedant Kumara14a1f92018-01-17 18:53:51 +00001744 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1745 Initializer->getLocStart(),
1746 Initializer->getLocEnd())
Richard Smith60437622017-02-09 19:17:44 +00001747 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1748 DirectInitRange.getBegin(),
1749 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001750
Richard Smith60437622017-02-09 19:17:44 +00001751 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1752 auto *Deduced = AllocType->getContainedDeducedType();
1753 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1754 if (ArraySize)
1755 return ExprError(Diag(ArraySize->getExprLoc(),
1756 diag::err_deduced_class_template_compound_type)
1757 << /*array*/ 2 << ArraySize->getSourceRange());
1758
1759 InitializedEntity Entity
1760 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1761 AllocType = DeduceTemplateSpecializationFromInitializer(
1762 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1763 if (AllocType.isNull())
1764 return ExprError();
1765 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001766 bool Braced = (initStyle == CXXNewExpr::ListInit);
1767 if (NumInits == 1) {
1768 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1769 Inits = p->getInits();
1770 NumInits = p->getNumInits();
1771 Braced = true;
1772 }
1773 }
1774
Sebastian Redl6047f072012-02-16 12:22:20 +00001775 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001776 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1777 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001778 if (NumInits > 1) {
1779 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001780 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001781 diag::err_auto_new_ctor_multiple_expressions)
1782 << AllocType << TypeRange);
1783 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001784 if (Braced && !getLangOpts().CPlusPlus17)
1785 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1786 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001787 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001788 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001789 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001790 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001791 << AllocType << Deduce->getType()
1792 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001793 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001794 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001795 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001796 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001797
Douglas Gregorcda95f42010-05-16 16:01:03 +00001798 // Per C++0x [expr.new]p5, the type being constructed may be a
1799 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001800 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001801 if (const ConstantArrayType *Array
1802 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001803 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1804 Context.getSizeType(),
1805 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001806 AllocType = Array->getElementType();
1807 }
1808 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001809
Douglas Gregor3999e152010-10-06 16:00:31 +00001810 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1811 return ExprError();
1812
Craig Topperc3ec1492014-05-26 06:22:03 +00001813 if (initStyle == CXXNewExpr::ListInit &&
1814 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001815 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1816 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001817 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001818 }
1819
Simon Pilgrim75c26882016-09-30 14:25:09 +00001820 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001821 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001822 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1823 AllocType->isObjCLifetimeType()) {
1824 AllocType = Context.getLifetimeQualifiedType(AllocType,
1825 AllocType->getObjCARCImplicitLifetime());
1826 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001827
John McCall31168b02011-06-15 23:02:42 +00001828 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001829
John McCall5e77d762013-04-16 07:28:30 +00001830 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1831 ExprResult result = CheckPlaceholderExpr(ArraySize);
1832 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001833 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001834 }
Richard Smith8dd34252012-02-04 07:07:42 +00001835 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1836 // integral or enumeration type with a non-negative value."
1837 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1838 // enumeration type, or a class type for which a single non-explicit
1839 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001840 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001841 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001842 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001843 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001844 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001845 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001846 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1847
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001848 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1849 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001850
Simon Pilgrim75c26882016-09-30 14:25:09 +00001851 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001852 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001853 // Diagnose the compatibility of this conversion.
1854 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1855 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001856 } else {
1857 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1858 protected:
1859 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001860
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001861 public:
1862 SizeConvertDiagnoser(Expr *ArraySize)
1863 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1864 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001865
1866 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1867 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001868 return S.Diag(Loc, diag::err_array_size_not_integral)
1869 << S.getLangOpts().CPlusPlus11 << T;
1870 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001871
1872 SemaDiagnosticBuilder diagnoseIncomplete(
1873 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001874 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1875 << T << ArraySize->getSourceRange();
1876 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001877
1878 SemaDiagnosticBuilder diagnoseExplicitConv(
1879 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001880 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1881 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001882
1883 SemaDiagnosticBuilder noteExplicitConv(
1884 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001885 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1886 << ConvTy->isEnumeralType() << ConvTy;
1887 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001888
1889 SemaDiagnosticBuilder diagnoseAmbiguous(
1890 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001891 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1892 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001893
1894 SemaDiagnosticBuilder noteAmbiguous(
1895 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001896 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1897 << ConvTy->isEnumeralType() << ConvTy;
1898 }
Richard Smithccc11812013-05-21 19:05:48 +00001899
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001900 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1901 QualType T,
1902 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001903 return S.Diag(Loc,
1904 S.getLangOpts().CPlusPlus11
1905 ? diag::warn_cxx98_compat_array_size_conversion
1906 : diag::ext_array_size_conversion)
1907 << T << ConvTy->isEnumeralType() << ConvTy;
1908 }
1909 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001910
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001911 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1912 SizeDiagnoser);
1913 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001914 if (ConvertedSize.isInvalid())
1915 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001916
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001917 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001918 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001919
Douglas Gregor0bf31402010-10-08 23:50:27 +00001920 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001921 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001923 // C++98 [expr.new]p7:
1924 // The expression in a direct-new-declarator shall have integral type
1925 // with a non-negative value.
1926 //
Richard Smith0511d232016-10-05 22:41:02 +00001927 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1928 // per CWG1464. Otherwise, if it's not a constant, we must have an
1929 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001930 if (!ArraySize->isValueDependent()) {
1931 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001932 // We've already performed any required implicit conversion to integer or
1933 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001934 // FIXME: Per CWG1464, we are required to check the value prior to
1935 // converting to size_t. This will never find a negative array size in
1936 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001937 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001938 if (Value.isSigned() && Value.isNegative()) {
1939 return ExprError(Diag(ArraySize->getLocStart(),
1940 diag::err_typecheck_negative_array_size)
1941 << ArraySize->getSourceRange());
1942 }
1943
1944 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001945 unsigned ActiveSizeBits =
1946 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001947 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1948 return ExprError(Diag(ArraySize->getLocStart(),
1949 diag::err_array_too_large)
1950 << Value.toString(10)
1951 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001952 }
Richard Smith0511d232016-10-05 22:41:02 +00001953
1954 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001955 } else if (TypeIdParens.isValid()) {
1956 // Can't have dynamic array size when the type-id is in parentheses.
1957 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1958 << ArraySize->getSourceRange()
1959 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1960 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961
Douglas Gregorf2753b32010-07-13 15:54:32 +00001962 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001963 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
John McCall036f2f62011-05-15 07:14:44 +00001966 // Note that we do *not* convert the argument in any way. It can
1967 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001968 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001969
Craig Topperc3ec1492014-05-26 06:22:03 +00001970 FunctionDecl *OperatorNew = nullptr;
1971 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001972 unsigned Alignment =
1973 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1974 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1975 bool PassAlignment = getLangOpts().AlignedAllocation &&
1976 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001978 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001979 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001980 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001981 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001982 UseGlobal, AllocType, ArraySize, PassAlignment,
1983 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001984 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001985
1986 // If this is an array allocation, compute whether the usual array
1987 // deallocation function for the type has a size_t parameter.
1988 bool UsualArrayDeleteWantsSize = false;
1989 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001990 UsualArrayDeleteWantsSize =
1991 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001992
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001993 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001994 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001996 OperatorNew->getType()->getAs<FunctionProtoType>();
1997 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1998 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999
Richard Smithd6f9e732014-05-13 19:56:21 +00002000 // We've already converted the placement args, just fill in any default
2001 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002002 // argument. Skip the second parameter too if we're passing in the
2003 // alignment; we've already filled it in.
2004 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2005 PassAlignment ? 2 : 1, PlacementArgs,
2006 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002007 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002009 if (!AllPlaceArgs.empty())
2010 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002011
Richard Smithd6f9e732014-05-13 19:56:21 +00002012 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002013 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002014
2015 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016
Richard Smithb2f0f052016-10-10 18:54:32 +00002017 // Warn if the type is over-aligned and is being allocated by (unaligned)
2018 // global operator new.
2019 if (PlacementArgs.empty() && !PassAlignment &&
2020 (OperatorNew->isImplicit() ||
2021 (OperatorNew->getLocStart().isValid() &&
2022 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2023 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002024 Diag(StartLoc, diag::warn_overaligned_type)
2025 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002026 << unsigned(Alignment / Context.getCharWidth())
2027 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002028 }
2029 }
2030
Sebastian Redl6047f072012-02-16 12:22:20 +00002031 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002032 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2033 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002034 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2035 SourceRange InitRange(Inits[0]->getLocStart(),
2036 Inits[NumInits - 1]->getLocEnd());
2037 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2038 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002039 }
2040
Richard Smithdd2ca572012-11-26 08:32:48 +00002041 // If we can perform the initialization, and we've not already done so,
2042 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002043 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002044 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002045 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002046 // The type we initialize is the complete type, including the array bound.
2047 QualType InitType;
2048 if (KnownArraySize)
2049 InitType = Context.getConstantArrayType(
2050 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2051 *KnownArraySize),
2052 ArrayType::Normal, 0);
2053 else if (ArraySize)
2054 InitType =
2055 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2056 else
2057 InitType = AllocType;
2058
Douglas Gregor85dabae2009-12-16 01:38:02 +00002059 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002060 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002061 InitializationSequence InitSeq(*this, Entity, Kind,
2062 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002064 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002065 if (FullInit.isInvalid())
2066 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002067
Sebastian Redl6047f072012-02-16 12:22:20 +00002068 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2069 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002070 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002071 if (CXXBindTemporaryExpr *Binder =
2072 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002073 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002075 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Douglas Gregor6642ca22010-02-26 05:06:18 +00002078 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002079 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002080 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2081 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002082 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002083 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002084 }
2085 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002086 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2087 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002088 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002089 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002090 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002091
John McCall928a2572011-07-13 20:12:57 +00002092 // C++0x [expr.new]p17:
2093 // If the new expression creates an array of objects of class type,
2094 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002095 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2096 if (ArraySize && !BaseAllocType->isDependentType()) {
2097 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2098 if (CXXDestructorDecl *dtor = LookupDestructor(
2099 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2100 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002101 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002102 PDiag(diag::err_access_dtor)
2103 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002104 if (DiagnoseUseOfDecl(dtor, StartLoc))
2105 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002106 }
John McCall928a2572011-07-13 20:12:57 +00002107 }
2108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002110 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002111 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002112 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2113 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2114 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002115}
2116
Sebastian Redl6047f072012-02-16 12:22:20 +00002117/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002118/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002119bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002120 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002121 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2122 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002123 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002124 return Diag(Loc, diag::err_bad_new_type)
2125 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002126 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002127 return Diag(Loc, diag::err_bad_new_type)
2128 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002129 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002130 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002131 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002132 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002133 diag::err_allocation_of_abstract_type))
2134 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002135 else if (AllocType->isVariablyModifiedType())
2136 return Diag(Loc, diag::err_variably_modified_new_type)
2137 << AllocType;
Alexander Richardson6d989432017-10-15 18:48:14 +00002138 else if (AllocType.getAddressSpace() != LangAS::Default)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002139 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002140 << AllocType.getUnqualifiedType()
2141 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002142 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002143 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2144 QualType BaseAllocType = Context.getBaseElementType(AT);
2145 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2146 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002147 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002148 << BaseAllocType;
2149 }
2150 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002151
Sebastian Redlbd150f42008-11-21 19:14:01 +00002152 return false;
2153}
2154
Brian Gesiak87412d92018-02-15 20:09:25 +00002155static bool resolveAllocationOverload(
2156 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2157 bool &PassAlignment, FunctionDecl *&Operator,
2158 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002159 OverloadCandidateSet Candidates(R.getNameLoc(),
2160 OverloadCandidateSet::CSK_Normal);
2161 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2162 Alloc != AllocEnd; ++Alloc) {
2163 // Even member operator new/delete are implicitly treated as
2164 // static, so don't use AddMemberCandidate.
2165 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2166
2167 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2168 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2169 /*ExplicitTemplateArgs=*/nullptr, Args,
2170 Candidates,
2171 /*SuppressUserConversions=*/false);
2172 continue;
2173 }
2174
2175 FunctionDecl *Fn = cast<FunctionDecl>(D);
2176 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2177 /*SuppressUserConversions=*/false);
2178 }
2179
2180 // Do the resolution.
2181 OverloadCandidateSet::iterator Best;
2182 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2183 case OR_Success: {
2184 // Got one!
2185 FunctionDecl *FnDecl = Best->Function;
2186 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2187 Best->FoundDecl) == Sema::AR_inaccessible)
2188 return true;
2189
2190 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002191 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002192 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002193
Richard Smithb2f0f052016-10-10 18:54:32 +00002194 case OR_No_Viable_Function:
2195 // C++17 [expr.new]p13:
2196 // If no matching function is found and the allocated object type has
2197 // new-extended alignment, the alignment argument is removed from the
2198 // argument list, and overload resolution is performed again.
2199 if (PassAlignment) {
2200 PassAlignment = false;
2201 AlignArg = Args[1];
2202 Args.erase(Args.begin() + 1);
2203 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002204 Operator, &Candidates, AlignArg,
2205 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002206 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002207
Richard Smithb2f0f052016-10-10 18:54:32 +00002208 // MSVC will fall back on trying to find a matching global operator new
2209 // if operator new[] cannot be found. Also, MSVC will leak by not
2210 // generating a call to operator delete or operator delete[], but we
2211 // will not replicate that bug.
2212 // FIXME: Find out how this interacts with the std::align_val_t fallback
2213 // once MSVC implements it.
2214 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2215 S.Context.getLangOpts().MSVCCompat) {
2216 R.clear();
2217 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2218 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2219 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2220 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002221 Operator, /*Candidates=*/nullptr,
2222 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002223 }
Richard Smith1cdec012013-09-29 04:40:38 +00002224
Brian Gesiak87412d92018-02-15 20:09:25 +00002225 if (Diagnose) {
2226 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2227 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002228
Brian Gesiak87412d92018-02-15 20:09:25 +00002229 // If we have aligned candidates, only note the align_val_t candidates
2230 // from AlignedCandidates and the non-align_val_t candidates from
2231 // Candidates.
2232 if (AlignedCandidates) {
2233 auto IsAligned = [](OverloadCandidate &C) {
2234 return C.Function->getNumParams() > 1 &&
2235 C.Function->getParamDecl(1)->getType()->isAlignValT();
2236 };
2237 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002238
Brian Gesiak87412d92018-02-15 20:09:25 +00002239 // This was an overaligned allocation, so list the aligned candidates
2240 // first.
2241 Args.insert(Args.begin() + 1, AlignArg);
2242 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2243 R.getNameLoc(), IsAligned);
2244 Args.erase(Args.begin() + 1);
2245 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2246 IsUnaligned);
2247 } else {
2248 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2249 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002250 }
Richard Smith1cdec012013-09-29 04:40:38 +00002251 return true;
2252
Richard Smithb2f0f052016-10-10 18:54:32 +00002253 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002254 if (Diagnose) {
2255 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2256 << R.getLookupName() << Range;
2257 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2258 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002259 return true;
2260
2261 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002262 if (Diagnose) {
2263 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2264 << Best->Function->isDeleted() << R.getLookupName()
2265 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2266 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2267 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002268 return true;
2269 }
2270 }
2271 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002272}
2273
Richard Smithb2f0f052016-10-10 18:54:32 +00002274
Sebastian Redlfaf68082008-12-03 20:26:15 +00002275/// FindAllocationFunctions - Finds the overloads of operator new and delete
2276/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002277bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2278 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002279 bool IsArray, bool &PassAlignment,
2280 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002281 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002282 FunctionDecl *&OperatorDelete,
2283 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002284 // --- Choosing an allocation function ---
2285 // C++ 5.3.4p8 - 14 & 18
2286 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2287 // in the scope of the allocated class.
2288 // 2) If an array size is given, look for operator new[], else look for
2289 // operator new.
2290 // 3) The first argument is always size_t. Append the arguments from the
2291 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002292
Richard Smithb2f0f052016-10-10 18:54:32 +00002293 SmallVector<Expr*, 8> AllocArgs;
2294 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2295
2296 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002297 // FIXME: Should the Sema create the expression and embed it in the syntax
2298 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002299 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002300 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002301 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002302 Context.getSizeType(),
2303 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002304 AllocArgs.push_back(&Size);
2305
2306 QualType AlignValT = Context.VoidTy;
2307 if (PassAlignment) {
2308 DeclareGlobalNewDelete();
2309 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2310 }
2311 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2312 if (PassAlignment)
2313 AllocArgs.push_back(&Align);
2314
2315 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002316
Douglas Gregor6642ca22010-02-26 05:06:18 +00002317 // C++ [expr.new]p8:
2318 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002319 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002320 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002321 // type, the allocation function's name is operator new[] and the
2322 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002323 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002324 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002325
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002326 QualType AllocElemType = Context.getBaseElementType(AllocType);
2327
Richard Smithb2f0f052016-10-10 18:54:32 +00002328 // Find the allocation function.
2329 {
2330 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2331
2332 // C++1z [expr.new]p9:
2333 // If the new-expression begins with a unary :: operator, the allocation
2334 // function's name is looked up in the global scope. Otherwise, if the
2335 // allocated type is a class type T or array thereof, the allocation
2336 // function's name is looked up in the scope of T.
2337 if (AllocElemType->isRecordType() && !UseGlobal)
2338 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2339
2340 // We can see ambiguity here if the allocation function is found in
2341 // multiple base classes.
2342 if (R.isAmbiguous())
2343 return true;
2344
2345 // If this lookup fails to find the name, or if the allocated type is not
2346 // a class type, the allocation function's name is looked up in the
2347 // global scope.
2348 if (R.empty())
2349 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2350
2351 assert(!R.empty() && "implicitly declared allocation functions not found");
2352 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2353
2354 // We do our own custom access checks below.
2355 R.suppressDiagnostics();
2356
2357 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002358 OperatorNew, /*Candidates=*/nullptr,
2359 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002360 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002361 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002362
Richard Smithb2f0f052016-10-10 18:54:32 +00002363 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002364 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002365 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002366 return false;
2367 }
2368
Richard Smithb2f0f052016-10-10 18:54:32 +00002369 // Note, the name of OperatorNew might have been changed from array to
2370 // non-array by resolveAllocationOverload.
2371 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2372 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2373 ? OO_Array_Delete
2374 : OO_Delete);
2375
Douglas Gregor6642ca22010-02-26 05:06:18 +00002376 // C++ [expr.new]p19:
2377 //
2378 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002379 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002380 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002381 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002382 // the scope of T. If this lookup fails to find the name, or if
2383 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002384 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002385 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002386 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002387 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002388 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002389 LookupQualifiedName(FoundDelete, RD);
2390 }
John McCallfb6f5262010-03-18 08:19:33 +00002391 if (FoundDelete.isAmbiguous())
2392 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002393
Richard Smithb2f0f052016-10-10 18:54:32 +00002394 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002395 if (FoundDelete.empty()) {
2396 DeclareGlobalNewDelete();
2397 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2398 }
2399
2400 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002401
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002402 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002403
John McCalld3be2c82010-09-14 21:34:24 +00002404 // Whether we're looking for a placement operator delete is dictated
2405 // by whether we selected a placement operator new, not by whether
2406 // we had explicit placement arguments. This matters for things like
2407 // struct A { void *operator new(size_t, int = 0); ... };
2408 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002409 //
2410 // We don't have any definition for what a "placement allocation function"
2411 // is, but we assume it's any allocation function whose
2412 // parameter-declaration-clause is anything other than (size_t).
2413 //
2414 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2415 // This affects whether an exception from the constructor of an overaligned
2416 // type uses the sized or non-sized form of aligned operator delete.
2417 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2418 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002419
2420 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002421 // C++ [expr.new]p20:
2422 // A declaration of a placement deallocation function matches the
2423 // declaration of a placement allocation function if it has the
2424 // same number of parameters and, after parameter transformations
2425 // (8.3.5), all parameter types except the first are
2426 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002428 // To perform this comparison, we compute the function type that
2429 // the deallocation function should have, and use that type both
2430 // for template argument deduction and for comparison purposes.
2431 QualType ExpectedFunctionType;
2432 {
2433 const FunctionProtoType *Proto
2434 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002435
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002436 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002437 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002438 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2439 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002440
John McCalldb40c7f2010-12-14 08:05:40 +00002441 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002442 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002443 EPI.Variadic = Proto->isVariadic();
2444
Douglas Gregor6642ca22010-02-26 05:06:18 +00002445 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002446 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002447 }
2448
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002450 DEnd = FoundDelete.end();
2451 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002452 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002453 if (FunctionTemplateDecl *FnTmpl =
2454 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002455 // Perform template argument deduction to try to match the
2456 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002457 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002458 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2459 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002460 continue;
2461 } else
2462 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2463
Richard Smithbaa47832016-12-01 02:11:49 +00002464 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2465 ExpectedFunctionType,
2466 /*AdjustExcpetionSpec*/true),
2467 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002468 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002469 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002470
Richard Smithb2f0f052016-10-10 18:54:32 +00002471 if (getLangOpts().CUDA)
2472 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2473 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002474 // C++1y [expr.new]p22:
2475 // For a non-placement allocation function, the normal deallocation
2476 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002477 //
2478 // Per [expr.delete]p10, this lookup prefers a member operator delete
2479 // without a size_t argument, but prefers a non-member operator delete
2480 // with a size_t where possible (which it always is in this case).
2481 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2482 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2483 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2484 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2485 &BestDeallocFns);
2486 if (Selected)
2487 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2488 else {
2489 // If we failed to select an operator, all remaining functions are viable
2490 // but ambiguous.
2491 for (auto Fn : BestDeallocFns)
2492 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002493 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002494 }
2495
2496 // C++ [expr.new]p20:
2497 // [...] If the lookup finds a single matching deallocation
2498 // function, that function will be called; otherwise, no
2499 // deallocation function will be called.
2500 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002501 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002502
Richard Smithb2f0f052016-10-10 18:54:32 +00002503 // C++1z [expr.new]p23:
2504 // If the lookup finds a usual deallocation function (3.7.4.2)
2505 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002506 // as a placement deallocation function, would have been
2507 // selected as a match for the allocation function, the program
2508 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002509 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002510 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002511 UsualDeallocFnInfo Info(*this,
2512 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002513 // Core issue, per mail to core reflector, 2016-10-09:
2514 // If this is a member operator delete, and there is a corresponding
2515 // non-sized member operator delete, this isn't /really/ a sized
2516 // deallocation function, it just happens to have a size_t parameter.
2517 bool IsSizedDelete = Info.HasSizeT;
2518 if (IsSizedDelete && !FoundGlobalDelete) {
2519 auto NonSizedDelete =
2520 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2521 /*WantAlign*/Info.HasAlignValT);
2522 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2523 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2524 IsSizedDelete = false;
2525 }
2526
2527 if (IsSizedDelete) {
2528 SourceRange R = PlaceArgs.empty()
2529 ? SourceRange()
2530 : SourceRange(PlaceArgs.front()->getLocStart(),
2531 PlaceArgs.back()->getLocEnd());
2532 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2533 if (!OperatorDelete->isImplicit())
2534 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2535 << DeleteName;
2536 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002537 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002538
2539 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2540 Matches[0].first);
2541 } else if (!Matches.empty()) {
2542 // We found multiple suitable operators. Per [expr.new]p20, that means we
2543 // call no 'operator delete' function, but we should at least warn the user.
2544 // FIXME: Suppress this warning if the construction cannot throw.
2545 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2546 << DeleteName << AllocElemType;
2547
2548 for (auto &Match : Matches)
2549 Diag(Match.second->getLocation(),
2550 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002551 }
2552
Sebastian Redlfaf68082008-12-03 20:26:15 +00002553 return false;
2554}
2555
2556/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2557/// delete. These are:
2558/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002559/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002560/// void* operator new(std::size_t) throw(std::bad_alloc);
2561/// void* operator new[](std::size_t) throw(std::bad_alloc);
2562/// void operator delete(void *) throw();
2563/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002564/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002565/// void* operator new(std::size_t);
2566/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002567/// void operator delete(void *) noexcept;
2568/// void operator delete[](void *) noexcept;
2569/// // C++1y:
2570/// void* operator new(std::size_t);
2571/// void* operator new[](std::size_t);
2572/// void operator delete(void *) noexcept;
2573/// void operator delete[](void *) noexcept;
2574/// void operator delete(void *, std::size_t) noexcept;
2575/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002576/// @endcode
2577/// Note that the placement and nothrow forms of new are *not* implicitly
2578/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002579void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002580 if (GlobalNewDeleteDeclared)
2581 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582
Douglas Gregor87f54062009-09-15 22:30:29 +00002583 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002584 // [...] The following allocation and deallocation functions (18.4) are
2585 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002586 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587 //
Sebastian Redl37588092011-03-14 18:08:30 +00002588 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002589 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590 // void* operator new[](std::size_t) throw(std::bad_alloc);
2591 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002592 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002593 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002594 // void* operator new(std::size_t);
2595 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002596 // void operator delete(void*) noexcept;
2597 // void operator delete[](void*) noexcept;
2598 // C++1y:
2599 // void* operator new(std::size_t);
2600 // void* operator new[](std::size_t);
2601 // void operator delete(void*) noexcept;
2602 // void operator delete[](void*) noexcept;
2603 // void operator delete(void*, std::size_t) noexcept;
2604 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002605 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002607 // new, operator new[], operator delete, operator delete[].
2608 //
2609 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2610 // "std" or "bad_alloc" as necessary to form the exception specification.
2611 // However, we do not make these implicit declarations visible to name
2612 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002613 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002614 // The "std::bad_alloc" class has not yet been declared, so build it
2615 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2617 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002618 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002620 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002621 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002622 }
Richard Smith59139022016-09-30 22:41:36 +00002623 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002624 // The "std::align_val_t" enum class has not yet been declared, so build it
2625 // implicitly.
2626 auto *AlignValT = EnumDecl::Create(
2627 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2628 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2629 AlignValT->setIntegerType(Context.getSizeType());
2630 AlignValT->setPromotionType(Context.getSizeType());
2631 AlignValT->setImplicit(true);
2632 StdAlignValT = AlignValT;
2633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634
Sebastian Redlfaf68082008-12-03 20:26:15 +00002635 GlobalNewDeleteDeclared = true;
2636
2637 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2638 QualType SizeT = Context.getSizeType();
2639
Richard Smith96269c52016-09-29 22:49:46 +00002640 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2641 QualType Return, QualType Param) {
2642 llvm::SmallVector<QualType, 3> Params;
2643 Params.push_back(Param);
2644
2645 // Create up to four variants of the function (sized/aligned).
2646 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2647 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002648 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002649
2650 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2651 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2652 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002653 if (Sized)
2654 Params.push_back(SizeT);
2655
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002656 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002657 if (Aligned)
2658 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2659
2660 DeclareGlobalAllocationFunction(
2661 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2662
2663 if (Aligned)
2664 Params.pop_back();
2665 }
2666 }
2667 };
2668
2669 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2670 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2671 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2672 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002673}
2674
2675/// DeclareGlobalAllocationFunction - Declares a single implicit global
2676/// allocation function if it doesn't already exist.
2677void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002678 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002679 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002680 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2681
2682 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002683 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2684 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2685 Alloc != AllocEnd; ++Alloc) {
2686 // Only look at non-template functions, as it is the predefined,
2687 // non-templated allocation function we are trying to declare here.
2688 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002689 if (Func->getNumParams() == Params.size()) {
2690 llvm::SmallVector<QualType, 3> FuncParams;
2691 for (auto *P : Func->parameters())
2692 FuncParams.push_back(
2693 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2694 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002695 // Make the function visible to name lookup, even if we found it in
2696 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002697 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002698 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002699 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002700 }
Chandler Carruth93538422010-02-03 11:02:14 +00002701 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002702 }
2703 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002704
Richard Smithc015bc22014-02-07 22:39:53 +00002705 FunctionProtoType::ExtProtoInfo EPI;
2706
Richard Smithf8b417c2014-02-08 00:42:45 +00002707 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002709 = (Name.getCXXOverloadedOperator() == OO_New ||
2710 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002711 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002712 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002713 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002714 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002715 EPI.ExceptionSpec.Type = EST_Dynamic;
2716 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002717 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002718 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002719 EPI.ExceptionSpec =
2720 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722
Artem Belevich07db5cf2016-10-21 20:34:05 +00002723 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2724 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2725 FunctionDecl *Alloc = FunctionDecl::Create(
2726 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2727 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2728 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002729 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002730 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002731
Artem Belevich07db5cf2016-10-21 20:34:05 +00002732 // Implicit sized deallocation functions always have default visibility.
2733 Alloc->addAttr(
2734 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002735
Artem Belevich07db5cf2016-10-21 20:34:05 +00002736 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2737 for (QualType T : Params) {
2738 ParamDecls.push_back(ParmVarDecl::Create(
2739 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2740 /*TInfo=*/nullptr, SC_None, nullptr));
2741 ParamDecls.back()->setImplicit();
2742 }
2743 Alloc->setParams(ParamDecls);
2744 if (ExtraAttr)
2745 Alloc->addAttr(ExtraAttr);
2746 Context.getTranslationUnitDecl()->addDecl(Alloc);
2747 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2748 };
2749
2750 if (!LangOpts.CUDA)
2751 CreateAllocationFunctionDecl(nullptr);
2752 else {
2753 // Host and device get their own declaration so each can be
2754 // defined or re-declared independently.
2755 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2756 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002757 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002758}
2759
Richard Smith1cdec012013-09-29 04:40:38 +00002760FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2761 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002762 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002763 DeclarationName Name) {
2764 DeclareGlobalNewDelete();
2765
2766 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2767 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2768
Richard Smithb2f0f052016-10-10 18:54:32 +00002769 // FIXME: It's possible for this to result in ambiguity, through a
2770 // user-declared variadic operator delete or the enable_if attribute. We
2771 // should probably not consider those cases to be usual deallocation
2772 // functions. But for now we just make an arbitrary choice in that case.
2773 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2774 Overaligned);
2775 assert(Result.FD && "operator delete missing from global scope?");
2776 return Result.FD;
2777}
Richard Smith1cdec012013-09-29 04:40:38 +00002778
Richard Smithb2f0f052016-10-10 18:54:32 +00002779FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2780 CXXRecordDecl *RD) {
2781 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002782
Richard Smithb2f0f052016-10-10 18:54:32 +00002783 FunctionDecl *OperatorDelete = nullptr;
2784 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2785 return nullptr;
2786 if (OperatorDelete)
2787 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002788
Richard Smithb2f0f052016-10-10 18:54:32 +00002789 // If there's no class-specific operator delete, look up the global
2790 // non-array delete.
2791 return FindUsualDeallocationFunction(
2792 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2793 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002794}
2795
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002796bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2797 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002798 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002799 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002800 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002801 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802
John McCall27b18f82009-11-17 02:14:36 +00002803 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002804 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002805
Chandler Carruthb6f99172010-06-28 00:30:51 +00002806 Found.suppressDiagnostics();
2807
Richard Smithb2f0f052016-10-10 18:54:32 +00002808 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002809
Richard Smithb2f0f052016-10-10 18:54:32 +00002810 // C++17 [expr.delete]p10:
2811 // If the deallocation functions have class scope, the one without a
2812 // parameter of type std::size_t is selected.
2813 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2814 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2815 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002816
Richard Smithb2f0f052016-10-10 18:54:32 +00002817 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002818 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002819 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002820
Richard Smithb2f0f052016-10-10 18:54:32 +00002821 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002822 if (Operator->isDeleted()) {
2823 if (Diagnose) {
2824 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002825 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002826 }
2827 return true;
2828 }
2829
Richard Smith921bd202012-02-26 09:11:52 +00002830 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002831 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002832 return true;
2833
John McCall66a87592010-08-04 00:31:26 +00002834 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002835 }
John McCall66a87592010-08-04 00:31:26 +00002836
Richard Smithb2f0f052016-10-10 18:54:32 +00002837 // We found multiple suitable operators; complain about the ambiguity.
2838 // FIXME: The standard doesn't say to do this; it appears that the intent
2839 // is that this should never happen.
2840 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002841 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002842 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2843 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002844 for (auto &Match : Matches)
2845 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002846 }
John McCall66a87592010-08-04 00:31:26 +00002847 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002848 }
2849
2850 // We did find operator delete/operator delete[] declarations, but
2851 // none of them were suitable.
2852 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002853 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002854 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2855 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856
Richard Smithb2f0f052016-10-10 18:54:32 +00002857 for (NamedDecl *D : Found)
2858 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002859 diag::note_member_declared_here) << Name;
2860 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002861 return true;
2862 }
2863
Craig Topperc3ec1492014-05-26 06:22:03 +00002864 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002865 return false;
2866}
2867
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002868namespace {
2869/// \brief Checks whether delete-expression, and new-expression used for
2870/// initializing deletee have the same array form.
2871class MismatchingNewDeleteDetector {
2872public:
2873 enum MismatchResult {
2874 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2875 NoMismatch,
2876 /// Indicates that variable is initialized with mismatching form of \a new.
2877 VarInitMismatches,
2878 /// Indicates that member is initialized with mismatching form of \a new.
2879 MemberInitMismatches,
2880 /// Indicates that 1 or more constructors' definitions could not been
2881 /// analyzed, and they will be checked again at the end of translation unit.
2882 AnalyzeLater
2883 };
2884
2885 /// \param EndOfTU True, if this is the final analysis at the end of
2886 /// translation unit. False, if this is the initial analysis at the point
2887 /// delete-expression was encountered.
2888 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002889 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002890 HasUndefinedConstructors(false) {}
2891
2892 /// \brief Checks whether pointee of a delete-expression is initialized with
2893 /// matching form of new-expression.
2894 ///
2895 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2896 /// point where delete-expression is encountered, then a warning will be
2897 /// issued immediately. If return value is \c AnalyzeLater at the point where
2898 /// delete-expression is seen, then member will be analyzed at the end of
2899 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2900 /// couldn't be analyzed. If at least one constructor initializes the member
2901 /// with matching type of new, the return value is \c NoMismatch.
2902 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2903 /// \brief Analyzes a class member.
2904 /// \param Field Class member to analyze.
2905 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2906 /// for deleting the \p Field.
2907 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002908 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002909 /// List of mismatching new-expressions used for initialization of the pointee
2910 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2911 /// Indicates whether delete-expression was in array form.
2912 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002913
2914private:
2915 const bool EndOfTU;
2916 /// \brief Indicates that there is at least one constructor without body.
2917 bool HasUndefinedConstructors;
2918 /// \brief Returns \c CXXNewExpr from given initialization expression.
2919 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002920 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002921 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2922 /// \brief Returns whether member is initialized with mismatching form of
2923 /// \c new either by the member initializer or in-class initialization.
2924 ///
2925 /// If bodies of all constructors are not visible at the end of translation
2926 /// unit or at least one constructor initializes member with the matching
2927 /// form of \c new, mismatch cannot be proven, and this function will return
2928 /// \c NoMismatch.
2929 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2930 /// \brief Returns whether variable is initialized with mismatching form of
2931 /// \c new.
2932 ///
2933 /// If variable is initialized with matching form of \c new or variable is not
2934 /// initialized with a \c new expression, this function will return true.
2935 /// If variable is initialized with mismatching form of \c new, returns false.
2936 /// \param D Variable to analyze.
2937 bool hasMatchingVarInit(const DeclRefExpr *D);
2938 /// \brief Checks whether the constructor initializes pointee with mismatching
2939 /// form of \c new.
2940 ///
2941 /// Returns true, if member is initialized with matching form of \c new in
2942 /// member initializer list. Returns false, if member is initialized with the
2943 /// matching form of \c new in this constructor's initializer or given
2944 /// constructor isn't defined at the point where delete-expression is seen, or
2945 /// member isn't initialized by the constructor.
2946 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2947 /// \brief Checks whether member is initialized with matching form of
2948 /// \c new in member initializer list.
2949 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2950 /// Checks whether member is initialized with mismatching form of \c new by
2951 /// in-class initializer.
2952 MismatchResult analyzeInClassInitializer();
2953};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002954}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002955
2956MismatchingNewDeleteDetector::MismatchResult
2957MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2958 NewExprs.clear();
2959 assert(DE && "Expected delete-expression");
2960 IsArrayForm = DE->isArrayForm();
2961 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2962 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2963 return analyzeMemberExpr(ME);
2964 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2965 if (!hasMatchingVarInit(D))
2966 return VarInitMismatches;
2967 }
2968 return NoMismatch;
2969}
2970
2971const CXXNewExpr *
2972MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2973 assert(E != nullptr && "Expected a valid initializer expression");
2974 E = E->IgnoreParenImpCasts();
2975 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2976 if (ILE->getNumInits() == 1)
2977 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2978 }
2979
2980 return dyn_cast_or_null<const CXXNewExpr>(E);
2981}
2982
2983bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2984 const CXXCtorInitializer *CI) {
2985 const CXXNewExpr *NE = nullptr;
2986 if (Field == CI->getMember() &&
2987 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2988 if (NE->isArray() == IsArrayForm)
2989 return true;
2990 else
2991 NewExprs.push_back(NE);
2992 }
2993 return false;
2994}
2995
2996bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2997 const CXXConstructorDecl *CD) {
2998 if (CD->isImplicit())
2999 return false;
3000 const FunctionDecl *Definition = CD;
3001 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3002 HasUndefinedConstructors = true;
3003 return EndOfTU;
3004 }
3005 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3006 if (hasMatchingNewInCtorInit(CI))
3007 return true;
3008 }
3009 return false;
3010}
3011
3012MismatchingNewDeleteDetector::MismatchResult
3013MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3014 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003015 const Expr *InitExpr = Field->getInClassInitializer();
3016 if (!InitExpr)
3017 return EndOfTU ? NoMismatch : AnalyzeLater;
3018 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003019 if (NE->isArray() != IsArrayForm) {
3020 NewExprs.push_back(NE);
3021 return MemberInitMismatches;
3022 }
3023 }
3024 return NoMismatch;
3025}
3026
3027MismatchingNewDeleteDetector::MismatchResult
3028MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3029 bool DeleteWasArrayForm) {
3030 assert(Field != nullptr && "Analysis requires a valid class member.");
3031 this->Field = Field;
3032 IsArrayForm = DeleteWasArrayForm;
3033 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3034 for (const auto *CD : RD->ctors()) {
3035 if (hasMatchingNewInCtor(CD))
3036 return NoMismatch;
3037 }
3038 if (HasUndefinedConstructors)
3039 return EndOfTU ? NoMismatch : AnalyzeLater;
3040 if (!NewExprs.empty())
3041 return MemberInitMismatches;
3042 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3043 : NoMismatch;
3044}
3045
3046MismatchingNewDeleteDetector::MismatchResult
3047MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3048 assert(ME != nullptr && "Expected a member expression");
3049 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3050 return analyzeField(F, IsArrayForm);
3051 return NoMismatch;
3052}
3053
3054bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3055 const CXXNewExpr *NE = nullptr;
3056 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3057 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3058 NE->isArray() != IsArrayForm) {
3059 NewExprs.push_back(NE);
3060 }
3061 }
3062 return NewExprs.empty();
3063}
3064
3065static void
3066DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3067 const MismatchingNewDeleteDetector &Detector) {
3068 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3069 FixItHint H;
3070 if (!Detector.IsArrayForm)
3071 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3072 else {
3073 SourceLocation RSquare = Lexer::findLocationAfterToken(
3074 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3075 SemaRef.getLangOpts(), true);
3076 if (RSquare.isValid())
3077 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3078 }
3079 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3080 << Detector.IsArrayForm << H;
3081
3082 for (const auto *NE : Detector.NewExprs)
3083 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3084 << Detector.IsArrayForm;
3085}
3086
3087void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3088 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3089 return;
3090 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3091 switch (Detector.analyzeDeleteExpr(DE)) {
3092 case MismatchingNewDeleteDetector::VarInitMismatches:
3093 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3094 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3095 break;
3096 }
3097 case MismatchingNewDeleteDetector::AnalyzeLater: {
3098 DeleteExprs[Detector.Field].push_back(
3099 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3100 break;
3101 }
3102 case MismatchingNewDeleteDetector::NoMismatch:
3103 break;
3104 }
3105}
3106
3107void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3108 bool DeleteWasArrayForm) {
3109 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3110 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3111 case MismatchingNewDeleteDetector::VarInitMismatches:
3112 llvm_unreachable("This analysis should have been done for class members.");
3113 case MismatchingNewDeleteDetector::AnalyzeLater:
3114 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3115 "translation unit.");
3116 case MismatchingNewDeleteDetector::MemberInitMismatches:
3117 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3118 break;
3119 case MismatchingNewDeleteDetector::NoMismatch:
3120 break;
3121 }
3122}
3123
Sebastian Redlbd150f42008-11-21 19:14:01 +00003124/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3125/// @code ::delete ptr; @endcode
3126/// or
3127/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003128ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003129Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003130 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003131 // C++ [expr.delete]p1:
3132 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003133 // non-explicit conversion function to a pointer type. The result has type
3134 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003135 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003136 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3137
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003138 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003139 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003140 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003141 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003142
John Wiegley01296292011-04-08 18:41:53 +00003143 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003144 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003145 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003146 if (Ex.isInvalid())
3147 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003148
John Wiegley01296292011-04-08 18:41:53 +00003149 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003150
Richard Smithccc11812013-05-21 19:05:48 +00003151 class DeleteConverter : public ContextualImplicitConverter {
3152 public:
3153 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Craig Toppere14c0f82014-03-12 04:55:44 +00003155 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003156 // FIXME: If we have an operator T* and an operator void*, we must pick
3157 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003158 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003159 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003160 return true;
3161 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003162 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003163
Richard Smithccc11812013-05-21 19:05:48 +00003164 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003165 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003166 return S.Diag(Loc, diag::err_delete_operand) << T;
3167 }
3168
3169 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003170 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003171 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3172 }
3173
3174 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003175 QualType T,
3176 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003177 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3178 }
3179
3180 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003181 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003182 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3183 << ConvTy;
3184 }
3185
3186 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003187 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003188 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3189 }
3190
3191 SemaDiagnosticBuilder noteAmbiguous(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 diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003198 QualType T,
3199 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003200 llvm_unreachable("conversion functions are permitted");
3201 }
3202 } Converter;
3203
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003204 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003205 if (Ex.isInvalid())
3206 return ExprError();
3207 Type = Ex.get()->getType();
3208 if (!Converter.match(Type))
3209 // FIXME: PerformContextualImplicitConversion should return ExprError
3210 // itself in this case.
3211 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003212
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003213 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003214 QualType PointeeElem = Context.getBaseElementType(Pointee);
3215
Alexander Richardson6d989432017-10-15 18:48:14 +00003216 if (Pointee.getAddressSpace() != LangAS::Default)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003217 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003218 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003219 << Pointee.getUnqualifiedType()
3220 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003221
Craig Topperc3ec1492014-05-26 06:22:03 +00003222 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003223 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003225 // effectively bans deletion of "void*". However, most compilers support
3226 // this, so we treat it as a warning unless we're in a SFINAE context.
3227 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003228 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003229 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003230 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003231 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003232 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003233 // FIXME: This can result in errors if the definition was imported from a
3234 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003235 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003236 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003237 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3238 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3239 }
3240 }
3241
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003242 if (Pointee->isArrayType() && !ArrayForm) {
3243 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003244 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003245 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003246 ArrayForm = true;
3247 }
3248
Anders Carlssona471db02009-08-16 20:29:29 +00003249 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3250 ArrayForm ? OO_Array_Delete : OO_Delete);
3251
Eli Friedmanae4280f2011-07-26 22:25:31 +00003252 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003254 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3255 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003256 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257
John McCall284c48f2011-01-27 09:37:56 +00003258 // If we're allocating an array of records, check whether the
3259 // usual operator delete[] has a size_t parameter.
3260 if (ArrayForm) {
3261 // If the user specifically asked to use the global allocator,
3262 // we'll need to do the lookup into the class.
3263 if (UseGlobal)
3264 UsualArrayDeleteWantsSize =
3265 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3266
3267 // Otherwise, the usual operator delete[] should be the
3268 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003269 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003270 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003271 UsualDeallocFnInfo(*this,
3272 DeclAccessPair::make(OperatorDelete, AS_public))
3273 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003274 }
3275
Richard Smitheec915d62012-02-18 04:13:32 +00003276 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003277 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003278 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003279 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003280 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3281 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003282 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003283
Nico Weber5a9259c2016-01-15 21:45:31 +00003284 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3285 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3286 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3287 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289
Richard Smithb2f0f052016-10-10 18:54:32 +00003290 if (!OperatorDelete) {
3291 bool IsComplete = isCompleteType(StartLoc, Pointee);
3292 bool CanProvideSize =
3293 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3294 Pointee.isDestructedType());
3295 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3296
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003297 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003298 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3299 Overaligned, DeleteName);
3300 }
Mike Stump11289f42009-09-09 15:08:12 +00003301
Eli Friedmanfa0df832012-02-02 03:46:19 +00003302 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003303
Richard Smith5b349582017-10-13 01:55:36 +00003304 // Check access and ambiguity of destructor if we're going to call it.
3305 // Note that this is required even for a virtual delete.
3306 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003307 if (PointeeRD) {
3308 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003309 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3310 PDiag(diag::err_access_dtor) << PointeeElem);
3311 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003312 }
3313 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003314
3315 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3316 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003317
3318 // Convert the operand to the type of the first parameter of operator
3319 // delete. This is only necessary if we selected a destroying operator
3320 // delete that we are going to call (non-virtually); converting to void*
3321 // is trivial and left to AST consumers to handle.
3322 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3323 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003324 Qualifiers Qs = Pointee.getQualifiers();
3325 if (Qs.hasCVRQualifiers()) {
3326 // Qualifiers are irrelevant to this conversion; we're only looking
3327 // for access and ambiguity.
3328 Qs.removeCVRQualifiers();
3329 QualType Unqual = Context.getPointerType(
3330 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3331 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3332 }
Richard Smith5b349582017-10-13 01:55:36 +00003333 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3334 if (Ex.isInvalid())
3335 return ExprError();
3336 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003337 }
3338
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003339 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003340 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3341 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003342 AnalyzeDeleteExprMismatch(Result);
3343 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003344}
3345
Nico Weber5a9259c2016-01-15 21:45:31 +00003346void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3347 bool IsDelete, bool CallCanBeVirtual,
3348 bool WarnOnNonAbstractTypes,
3349 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003350 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003351 return;
3352
3353 // C++ [expr.delete]p3:
3354 // In the first alternative (delete object), if the static type of the
3355 // object to be deleted is different from its dynamic type, the static
3356 // type shall be a base class of the dynamic type of the object to be
3357 // deleted and the static type shall have a virtual destructor or the
3358 // behavior is undefined.
3359 //
3360 const CXXRecordDecl *PointeeRD = dtor->getParent();
3361 // Note: a final class cannot be derived from, no issue there
3362 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3363 return;
3364
Nico Weberbf2260c2017-08-31 06:17:08 +00003365 // If the superclass is in a system header, there's nothing that can be done.
3366 // The `delete` (where we emit the warning) can be in a system header,
3367 // what matters for this warning is where the deleted type is defined.
3368 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3369 return;
3370
Nico Weber5a9259c2016-01-15 21:45:31 +00003371 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3372 if (PointeeRD->isAbstract()) {
3373 // If the class is abstract, we warn by default, because we're
3374 // sure the code has undefined behavior.
3375 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3376 << ClassType;
3377 } else if (WarnOnNonAbstractTypes) {
3378 // Otherwise, if this is not an array delete, it's a bit suspect,
3379 // but not necessarily wrong.
3380 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3381 << ClassType;
3382 }
3383 if (!IsDelete) {
3384 std::string TypeStr;
3385 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3386 Diag(DtorLoc, diag::note_delete_non_virtual)
3387 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3388 }
3389}
3390
Richard Smith03a4aa32016-06-23 19:02:52 +00003391Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3392 SourceLocation StmtLoc,
3393 ConditionKind CK) {
3394 ExprResult E =
3395 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3396 if (E.isInvalid())
3397 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003398 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3399 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003400}
3401
Douglas Gregor633caca2009-11-23 23:44:04 +00003402/// \brief Check the use of the given variable as a C++ condition in an if,
3403/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003404ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003405 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003406 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003407 if (ConditionVar->isInvalidDecl())
3408 return ExprError();
3409
Douglas Gregor633caca2009-11-23 23:44:04 +00003410 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregor633caca2009-11-23 23:44:04 +00003412 // C++ [stmt.select]p2:
3413 // The declarator shall not specify a function or an array.
3414 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003416 diag::err_invalid_use_of_function_type)
3417 << ConditionVar->getSourceRange());
3418 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003420 diag::err_invalid_use_of_array_type)
3421 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003422
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003423 ExprResult Condition = DeclRefExpr::Create(
3424 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3425 /*enclosing*/ false, ConditionVar->getLocation(),
3426 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003427
Eli Friedmanfa0df832012-02-02 03:46:19 +00003428 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003429
Richard Smith03a4aa32016-06-23 19:02:52 +00003430 switch (CK) {
3431 case ConditionKind::Boolean:
3432 return CheckBooleanCondition(StmtLoc, Condition.get());
3433
Richard Smithb130fe72016-06-23 19:16:49 +00003434 case ConditionKind::ConstexprIf:
3435 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3436
Richard Smith03a4aa32016-06-23 19:02:52 +00003437 case ConditionKind::Switch:
3438 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003439 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440
Richard Smith03a4aa32016-06-23 19:02:52 +00003441 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003442}
3443
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003444/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003445ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003446 // C++ 6.4p4:
3447 // The value of a condition that is an initialized declaration in a statement
3448 // other than a switch statement is the value of the declared variable
3449 // implicitly converted to type bool. If that conversion is ill-formed, the
3450 // program is ill-formed.
3451 // The value of a condition that is an expression is the value of the
3452 // expression, implicitly converted to bool.
3453 //
Richard Smithb130fe72016-06-23 19:16:49 +00003454 // FIXME: Return this value to the caller so they don't need to recompute it.
3455 llvm::APSInt Value(/*BitWidth*/1);
3456 return (IsConstexpr && !CondExpr->isValueDependent())
3457 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3458 CCEK_ConstexprIf)
3459 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003460}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003461
3462/// Helper function to determine whether this is the (deprecated) C++
3463/// conversion from a string literal to a pointer to non-const char or
3464/// non-const wchar_t (for narrow and wide string literals,
3465/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003466bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003467Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3468 // Look inside the implicit cast, if it exists.
3469 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3470 From = Cast->getSubExpr();
3471
3472 // A string literal (2.13.4) that is not a wide string literal can
3473 // be converted to an rvalue of type "pointer to char"; a wide
3474 // string literal can be converted to an rvalue of type "pointer
3475 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003476 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003477 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003478 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003479 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003480 // This conversion is considered only when there is an
3481 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003482 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3483 switch (StrLit->getKind()) {
3484 case StringLiteral::UTF8:
3485 case StringLiteral::UTF16:
3486 case StringLiteral::UTF32:
3487 // We don't allow UTF literals to be implicitly converted
3488 break;
3489 case StringLiteral::Ascii:
3490 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3491 ToPointeeType->getKind() == BuiltinType::Char_S);
3492 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003493 return Context.typesAreCompatible(Context.getWideCharType(),
3494 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003495 }
3496 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003497 }
3498
3499 return false;
3500}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003501
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003503 SourceLocation CastLoc,
3504 QualType Ty,
3505 CastKind Kind,
3506 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003507 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003508 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003509 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003510 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003511 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003512 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003513 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003514 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515
Richard Smith72d74052013-07-20 19:41:36 +00003516 if (S.RequireNonAbstractType(CastLoc, Ty,
3517 diag::err_allocation_of_abstract_type))
3518 return ExprError();
3519
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003520 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003521 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
Richard Smith5179eb72016-06-28 19:03:57 +00003523 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3524 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003525 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003526 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003527
Richard Smithf8adcdc2014-07-17 05:12:35 +00003528 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003529 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003530 ConstructorArgs, HadMultipleCandidates,
3531 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3532 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003533 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003534 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003536 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538
John McCalle3027922010-08-25 11:45:40 +00003539 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003540 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
Richard Smithd3f2d322015-02-24 21:16:19 +00003542 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003543 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003544 return ExprError();
3545
Douglas Gregora4253922010-04-16 22:17:36 +00003546 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003547 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3548 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003549 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003550 if (Result.isInvalid())
3551 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003552 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003553 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3554 CK_UserDefinedConversion, Result.get(),
3555 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556
Douglas Gregor668443e2011-01-20 00:18:04 +00003557 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003558 }
3559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560}
Douglas Gregora4253922010-04-16 22:17:36 +00003561
Douglas Gregor5fb53972009-01-14 15:45:31 +00003562/// PerformImplicitConversion - Perform an implicit conversion of the
3563/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003564/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003565/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003566/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003567ExprResult
3568Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003569 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003570 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003571 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003572 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003573 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003574 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3575 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003576 if (Res.isInvalid())
3577 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003578 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003579 break;
John Wiegley01296292011-04-08 18:41:53 +00003580 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003581
Anders Carlsson110b07b2009-09-15 06:28:28 +00003582 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003584 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003585 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003586 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003587 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003588 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003589 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590
Anders Carlsson110b07b2009-09-15 06:28:28 +00003591 // If the user-defined conversion is specified by a conversion function,
3592 // the initial standard conversion sequence converts the source type to
3593 // the implicit object parameter of the conversion function.
3594 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003595 } else {
3596 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003597 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003598 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003599 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003601 // initial standard conversion sequence converts the source type to
3602 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003603 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605 }
Richard Smith72d74052013-07-20 19:41:36 +00003606 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003607 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003608 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003609 PerformImplicitConversion(From, BeforeToType,
3610 ICS.UserDefined.Before, AA_Converting,
3611 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003612 if (Res.isInvalid())
3613 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003614 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616
3617 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003618 = BuildCXXCastArgument(*this,
3619 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003620 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003621 CastKind, cast<CXXMethodDecl>(FD),
3622 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003623 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003624 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003625
3626 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003627 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003628
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003629 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003630
Richard Smith507840d2011-11-29 22:48:16 +00003631 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3632 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003633 }
John McCall0d1da222010-01-12 00:44:57 +00003634
3635 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003636 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003637 PDiag(diag::err_typecheck_ambiguous_condition)
3638 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003639 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregor39c16d42008-10-24 04:54:22 +00003641 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003642 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003643
3644 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003645 bool Diagnosed =
3646 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3647 From->getType(), From, Action);
3648 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003649 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003650 }
3651
3652 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003653 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003654}
3655
Richard Smith507840d2011-11-29 22:48:16 +00003656/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003657/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003658/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003659/// expression. Flavor is the context in which we're performing this
3660/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003661ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003662Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003663 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003664 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003665 CheckedConversionKind CCK) {
3666 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003667
Mike Stump87c57ac2009-05-16 07:39:55 +00003668 // Overall FIXME: we are recomputing too many types here and doing far too
3669 // much extra work. What this means is that we need to keep track of more
3670 // information that is computed when we try the implicit conversion initially,
3671 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003672 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003673
Douglas Gregor2fe98832008-11-03 19:09:14 +00003674 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003675 // FIXME: When can ToType be a reference type?
3676 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003677 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003678 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003679 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003680 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003681 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003682 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003683 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003684 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3685 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003686 ConstructorArgs, /*HadMultipleCandidates*/ false,
3687 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3688 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003689 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003690 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003691 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3692 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003693 From, /*HadMultipleCandidates*/ false,
3694 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3695 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003696 }
3697
Douglas Gregor980fb162010-04-29 18:24:40 +00003698 // Resolve overloaded function references.
3699 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3700 DeclAccessPair Found;
3701 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3702 true, Found);
3703 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003704 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003705
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003706 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003707 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708
Douglas Gregor980fb162010-04-29 18:24:40 +00003709 From = FixOverloadedFunctionReference(From, Found, Fn);
3710 FromType = From->getType();
3711 }
3712
Richard Smitha23ab512013-05-23 00:30:41 +00003713 // If we're converting to an atomic type, first convert to the corresponding
3714 // non-atomic type.
3715 QualType ToAtomicType;
3716 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3717 ToAtomicType = ToType;
3718 ToType = ToAtomic->getValueType();
3719 }
3720
George Burgess IV8d141e02015-12-14 22:00:49 +00003721 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003722 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003723 switch (SCS.First) {
3724 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003725 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3726 FromType = FromAtomic->getValueType().getUnqualifiedType();
3727 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3728 From, /*BasePath=*/nullptr, VK_RValue);
3729 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003730 break;
3731
Eli Friedman946b7b52012-01-24 22:51:26 +00003732 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003733 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003734 ExprResult FromRes = DefaultLvalueConversion(From);
3735 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003736 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003737 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003738 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003739 }
John McCall34376a62010-12-04 03:47:34 +00003740
Douglas Gregor39c16d42008-10-24 04:54:22 +00003741 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003742 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003743 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003744 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003745 break;
3746
3747 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003748 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003749 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003750 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003751 break;
3752
3753 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003754 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003755 }
3756
Richard Smith507840d2011-11-29 22:48:16 +00003757 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003758 switch (SCS.Second) {
3759 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003760 // C++ [except.spec]p5:
3761 // [For] assignment to and initialization of pointers to functions,
3762 // pointers to member functions, and references to functions: the
3763 // target entity shall allow at least the exceptions allowed by the
3764 // source value in the assignment or initialization.
3765 switch (Action) {
3766 case AA_Assigning:
3767 case AA_Initializing:
3768 // Note, function argument passing and returning are initialization.
3769 case AA_Passing:
3770 case AA_Returning:
3771 case AA_Sending:
3772 case AA_Passing_CFAudited:
3773 if (CheckExceptionSpecCompatibility(From, ToType))
3774 return ExprError();
3775 break;
3776
3777 case AA_Casting:
3778 case AA_Converting:
3779 // Casts and implicit conversions are not initialization, so are not
3780 // checked for exception specification mismatches.
3781 break;
3782 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003783 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003784 break;
3785
3786 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003787 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003788 if (ToType->isBooleanType()) {
3789 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3790 SCS.Second == ICK_Integral_Promotion &&
3791 "only enums with fixed underlying type can promote to bool");
3792 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003793 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003794 } else {
3795 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003796 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003797 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003798 break;
3799
3800 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003801 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003802 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003803 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003804 break;
3805
3806 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003807 case ICK_Complex_Conversion: {
3808 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3809 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3810 CastKind CK;
3811 if (FromEl->isRealFloatingType()) {
3812 if (ToEl->isRealFloatingType())
3813 CK = CK_FloatingComplexCast;
3814 else
3815 CK = CK_FloatingComplexToIntegralComplex;
3816 } else if (ToEl->isRealFloatingType()) {
3817 CK = CK_IntegralComplexToFloatingComplex;
3818 } else {
3819 CK = CK_IntegralComplexCast;
3820 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003821 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003822 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003823 break;
John McCall8cb679e2010-11-15 09:13:47 +00003824 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003825
Douglas Gregor39c16d42008-10-24 04:54:22 +00003826 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003827 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003828 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003829 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003830 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003831 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003832 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003833 break;
3834
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003835 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003836 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003837 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003838 break;
3839
John McCall31168b02011-06-15 23:02:42 +00003840 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003841 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003842 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003843 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003844 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003845 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003846 diag::ext_typecheck_convert_incompatible_pointer)
3847 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003848 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003849 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003850 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003851 diag::ext_typecheck_convert_incompatible_pointer)
3852 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003853 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003854
Douglas Gregor33823722011-06-11 01:09:30 +00003855 if (From->getType()->isObjCObjectPointerType() &&
3856 ToType->isObjCObjectPointerType())
3857 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00003858 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3859 !CheckObjCARCUnavailableWeakConversion(ToType,
3860 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003861 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003862 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003863 diag::err_arc_weak_unavailable_assign);
3864 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003865 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003866 diag::err_arc_convesion_of_weak_unavailable)
3867 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003868 << From->getSourceRange();
3869 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003870
Richard Smith354abec2017-12-08 23:29:59 +00003871 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00003872 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003873 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003874 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003875
3876 // Make sure we extend blocks if necessary.
3877 // FIXME: doing this here is really ugly.
3878 if (Kind == CK_BlockPointerToObjCPointerCast) {
3879 ExprResult E = From;
3880 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003881 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003882 }
Brian Kelley11352a82017-03-29 18:09:02 +00003883 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3884 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003885 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003886 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003887 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003890 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00003891 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00003892 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003893 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003894 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003895 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003896 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003897
3898 // We may not have been able to figure out what this member pointer resolved
3899 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003900 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003901 (void)isCompleteType(From->getExprLoc(), From->getType());
3902 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003903 }
David Majnemerd96b9972014-08-08 00:10:39 +00003904
Richard Smith507840d2011-11-29 22:48:16 +00003905 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003906 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003907 break;
3908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003910 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003911 // Perform half-to-boolean conversion via float.
3912 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003913 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003914 FromType = Context.FloatTy;
3915 }
3916
Richard Smith507840d2011-11-29 22:48:16 +00003917 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003918 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003919 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003920 break;
3921
Douglas Gregor88d292c2010-05-13 16:44:06 +00003922 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003923 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003925 ToType.getNonReferenceType(),
3926 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003928 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003929 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003930 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003931
Richard Smith507840d2011-11-29 22:48:16 +00003932 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3933 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003934 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003935 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003936 }
3937
Douglas Gregor46188682010-05-18 22:42:18 +00003938 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003939 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003940 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003941 break;
3942
George Burgess IVdf1ed002016-01-13 01:52:39 +00003943 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003944 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003945 Expr *Elem = prepareVectorSplat(ToType, From).get();
3946 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3947 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003948 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950
Douglas Gregor46188682010-05-18 22:42:18 +00003951 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003952 // Case 1. x -> _Complex y
3953 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3954 QualType ElType = ToComplex->getElementType();
3955 bool isFloatingComplex = ElType->isRealFloatingType();
3956
3957 // x -> y
3958 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3959 // do nothing
3960 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003961 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003962 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003963 } else {
3964 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003965 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003966 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003967 }
3968 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003969 From = ImpCastExprToType(From, ToType,
3970 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003971 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003972
3973 // Case 2. _Complex x -> y
3974 } else {
3975 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3976 assert(FromComplex);
3977
3978 QualType ElType = FromComplex->getElementType();
3979 bool isFloatingComplex = ElType->isRealFloatingType();
3980
3981 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003982 From = ImpCastExprToType(From, ElType,
3983 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003984 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003985 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003986
3987 // x -> y
3988 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3989 // do nothing
3990 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003991 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003992 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003993 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003994 } else {
3995 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003996 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003997 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003998 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003999 }
4000 }
Douglas Gregor46188682010-05-18 22:42:18 +00004001 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004002
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004003 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004004 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004005 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004006 break;
4007 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004008
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004009 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004010 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004011 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004012 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4013 if (FromRes.isInvalid())
4014 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004015 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004016 assert ((ConvTy == Sema::Compatible) &&
4017 "Improper transparent union conversion");
4018 (void)ConvTy;
4019 break;
4020 }
4021
Guy Benyei259f9f42013-02-07 16:05:33 +00004022 case ICK_Zero_Event_Conversion:
4023 From = ImpCastExprToType(From, ToType,
4024 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004025 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004026 break;
4027
Egor Churaev89831422016-12-23 14:55:49 +00004028 case ICK_Zero_Queue_Conversion:
4029 From = ImpCastExprToType(From, ToType,
4030 CK_ZeroToOCLQueue,
4031 From->getValueKind()).get();
4032 break;
4033
Douglas Gregor46188682010-05-18 22:42:18 +00004034 case ICK_Lvalue_To_Rvalue:
4035 case ICK_Array_To_Pointer:
4036 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004037 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004038 case ICK_Qualification:
4039 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004040 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004041 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004042 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004043 }
4044
4045 switch (SCS.Third) {
4046 case ICK_Identity:
4047 // Nothing to do.
4048 break;
4049
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004050 case ICK_Function_Conversion:
4051 // If both sides are functions (or pointers/references to them), there could
4052 // be incompatible exception declarations.
4053 if (CheckExceptionSpecCompatibility(From, ToType))
4054 return ExprError();
4055
4056 From = ImpCastExprToType(From, ToType, CK_NoOp,
4057 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4058 break;
4059
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004060 case ICK_Qualification: {
4061 // The qualification keeps the category of the inner expression, unless the
4062 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004063 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004064 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004065 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004066 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004067
Douglas Gregore981bb02011-03-14 16:13:32 +00004068 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004069 !getLangOpts().WritableStrings) {
4070 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4071 ? diag::ext_deprecated_string_literal_conversion
4072 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004073 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004074 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004075
Douglas Gregor39c16d42008-10-24 04:54:22 +00004076 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004077 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004078
Douglas Gregor39c16d42008-10-24 04:54:22 +00004079 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004080 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004081 }
4082
Douglas Gregor298f43d2012-04-12 20:42:30 +00004083 // If this conversion sequence involved a scalar -> atomic conversion, perform
4084 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004085 if (!ToAtomicType.isNull()) {
4086 assert(Context.hasSameType(
4087 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4088 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004089 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004090 }
4091
George Burgess IV8d141e02015-12-14 22:00:49 +00004092 // If this conversion sequence succeeded and involved implicitly converting a
4093 // _Nullable type to a _Nonnull one, complain.
4094 if (CCK == CCK_ImplicitConversion)
4095 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4096 From->getLocStart());
4097
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004098 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004099}
4100
Chandler Carruth8e172c62011-05-01 06:51:22 +00004101/// \brief Check the completeness of a type in a unary type trait.
4102///
4103/// If the particular type trait requires a complete type, tries to complete
4104/// it. If completing the type fails, a diagnostic is emitted and false
4105/// returned. If completing the type succeeds or no completion was required,
4106/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004107static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004108 SourceLocation Loc,
4109 QualType ArgTy) {
4110 // C++0x [meta.unary.prop]p3:
4111 // For all of the class templates X declared in this Clause, instantiating
4112 // that template with a template argument that is a class template
4113 // specialization may result in the implicit instantiation of the template
4114 // argument if and only if the semantics of X require that the argument
4115 // must be a complete type.
4116 // We apply this rule to all the type trait expressions used to implement
4117 // these class templates. We also try to follow any GCC documented behavior
4118 // in these expressions to ensure portability of standard libraries.
4119 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004120 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004121 // is_complete_type somewhat obviously cannot require a complete type.
4122 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004123 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004124
4125 // These traits are modeled on the type predicates in C++0x
4126 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4127 // requiring a complete type, as whether or not they return true cannot be
4128 // impacted by the completeness of the type.
4129 case UTT_IsVoid:
4130 case UTT_IsIntegral:
4131 case UTT_IsFloatingPoint:
4132 case UTT_IsArray:
4133 case UTT_IsPointer:
4134 case UTT_IsLvalueReference:
4135 case UTT_IsRvalueReference:
4136 case UTT_IsMemberFunctionPointer:
4137 case UTT_IsMemberObjectPointer:
4138 case UTT_IsEnum:
4139 case UTT_IsUnion:
4140 case UTT_IsClass:
4141 case UTT_IsFunction:
4142 case UTT_IsReference:
4143 case UTT_IsArithmetic:
4144 case UTT_IsFundamental:
4145 case UTT_IsObject:
4146 case UTT_IsScalar:
4147 case UTT_IsCompound:
4148 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004149 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004150
4151 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4152 // which requires some of its traits to have the complete type. However,
4153 // the completeness of the type cannot impact these traits' semantics, and
4154 // so they don't require it. This matches the comments on these traits in
4155 // Table 49.
4156 case UTT_IsConst:
4157 case UTT_IsVolatile:
4158 case UTT_IsSigned:
4159 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004160
4161 // This type trait always returns false, checking the type is moot.
4162 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004163 return true;
4164
David Majnemer213bea32015-11-16 06:58:51 +00004165 // C++14 [meta.unary.prop]:
4166 // If T is a non-union class type, T shall be a complete type.
4167 case UTT_IsEmpty:
4168 case UTT_IsPolymorphic:
4169 case UTT_IsAbstract:
4170 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4171 if (!RD->isUnion())
4172 return !S.RequireCompleteType(
4173 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4174 return true;
4175
4176 // C++14 [meta.unary.prop]:
4177 // If T is a class type, T shall be a complete type.
4178 case UTT_IsFinal:
4179 case UTT_IsSealed:
4180 if (ArgTy->getAsCXXRecordDecl())
4181 return !S.RequireCompleteType(
4182 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4183 return true;
4184
Richard Smithf03e9082017-06-01 00:28:16 +00004185 // C++1z [meta.unary.prop]:
4186 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004187 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004188 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004189 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004190 case UTT_IsStandardLayout:
4191 case UTT_IsPOD:
4192 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004193 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4194 // or an array of unknown bound. But GCC actually imposes the same constraints
4195 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004196 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004197 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004198 case UTT_HasNothrowConstructor:
4199 case UTT_HasNothrowCopy:
4200 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004201 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004202 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004203 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004204 case UTT_HasTrivialCopy:
4205 case UTT_HasTrivialDestructor:
4206 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004207 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4208 LLVM_FALLTHROUGH;
4209
4210 // C++1z [meta.unary.prop]:
4211 // T shall be a complete type, cv void, or an array of unknown bound.
4212 case UTT_IsDestructible:
4213 case UTT_IsNothrowDestructible:
4214 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004215 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004216 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004217 return true;
4218
4219 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004220 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004221 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004222}
4223
Joao Matosc9523d42013-03-27 01:34:16 +00004224static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4225 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004226 bool (CXXRecordDecl::*HasTrivial)() const,
4227 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004228 bool (CXXMethodDecl::*IsDesiredOp)() const)
4229{
4230 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4231 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4232 return true;
4233
4234 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4235 DeclarationNameInfo NameInfo(Name, KeyLoc);
4236 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4237 if (Self.LookupQualifiedName(Res, RD)) {
4238 bool FoundOperator = false;
4239 Res.suppressDiagnostics();
4240 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4241 Op != OpEnd; ++Op) {
4242 if (isa<FunctionTemplateDecl>(*Op))
4243 continue;
4244
4245 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4246 if((Operator->*IsDesiredOp)()) {
4247 FoundOperator = true;
4248 const FunctionProtoType *CPT =
4249 Operator->getType()->getAs<FunctionProtoType>();
4250 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004251 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004252 return false;
4253 }
4254 }
4255 return FoundOperator;
4256 }
4257 return false;
4258}
4259
Alp Toker95e7ff22014-01-01 05:57:51 +00004260static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004261 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004262 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004263
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004264 ASTContext &C = Self.Context;
4265 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004266 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004267 // Type trait expressions corresponding to the primary type category
4268 // predicates in C++0x [meta.unary.cat].
4269 case UTT_IsVoid:
4270 return T->isVoidType();
4271 case UTT_IsIntegral:
4272 return T->isIntegralType(C);
4273 case UTT_IsFloatingPoint:
4274 return T->isFloatingType();
4275 case UTT_IsArray:
4276 return T->isArrayType();
4277 case UTT_IsPointer:
4278 return T->isPointerType();
4279 case UTT_IsLvalueReference:
4280 return T->isLValueReferenceType();
4281 case UTT_IsRvalueReference:
4282 return T->isRValueReferenceType();
4283 case UTT_IsMemberFunctionPointer:
4284 return T->isMemberFunctionPointerType();
4285 case UTT_IsMemberObjectPointer:
4286 return T->isMemberDataPointerType();
4287 case UTT_IsEnum:
4288 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004289 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004290 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004291 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004292 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004293 case UTT_IsFunction:
4294 return T->isFunctionType();
4295
4296 // Type trait expressions which correspond to the convenient composition
4297 // predicates in C++0x [meta.unary.comp].
4298 case UTT_IsReference:
4299 return T->isReferenceType();
4300 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004301 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004302 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004303 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004304 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004305 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004306 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004307 // Note: semantic analysis depends on Objective-C lifetime types to be
4308 // considered scalar types. However, such types do not actually behave
4309 // like scalar types at run time (since they may require retain/release
4310 // operations), so we report them as non-scalar.
4311 if (T->isObjCLifetimeType()) {
4312 switch (T.getObjCLifetime()) {
4313 case Qualifiers::OCL_None:
4314 case Qualifiers::OCL_ExplicitNone:
4315 return true;
4316
4317 case Qualifiers::OCL_Strong:
4318 case Qualifiers::OCL_Weak:
4319 case Qualifiers::OCL_Autoreleasing:
4320 return false;
4321 }
4322 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004323
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004324 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004325 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004326 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004327 case UTT_IsMemberPointer:
4328 return T->isMemberPointerType();
4329
4330 // Type trait expressions which correspond to the type property predicates
4331 // in C++0x [meta.unary.prop].
4332 case UTT_IsConst:
4333 return T.isConstQualified();
4334 case UTT_IsVolatile:
4335 return T.isVolatileQualified();
4336 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004337 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004338 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004339 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004340 case UTT_IsStandardLayout:
4341 return T->isStandardLayoutType();
4342 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004343 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004344 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004345 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004346 case UTT_IsEmpty:
4347 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4348 return !RD->isUnion() && RD->isEmpty();
4349 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004350 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004351 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004352 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004353 return false;
4354 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004355 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004356 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004357 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004358 case UTT_IsAggregate:
4359 // Report vector extensions and complex types as aggregates because they
4360 // support aggregate initialization. GCC mirrors this behavior for vectors
4361 // but not _Complex.
4362 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4363 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004364 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4365 // even then only when it is used with the 'interface struct ...' syntax
4366 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004367 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004368 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004369 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004370 case UTT_IsSealed:
4371 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004372 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004373 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004374 case UTT_IsSigned:
4375 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004376 case UTT_IsUnsigned:
4377 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004378
4379 // Type trait expressions which query classes regarding their construction,
4380 // destruction, and copying. Rather than being based directly on the
4381 // related type predicates in the standard, they are specified by both
4382 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4383 // specifications.
4384 //
4385 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4386 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004387 //
4388 // Note that these builtins do not behave as documented in g++: if a class
4389 // has both a trivial and a non-trivial special member of a particular kind,
4390 // they return false! For now, we emulate this behavior.
4391 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4392 // does not correctly compute triviality in the presence of multiple special
4393 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004394 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004395 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4396 // If __is_pod (type) is true then the trait is true, else if type is
4397 // a cv class or union type (or array thereof) with a trivial default
4398 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004399 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004400 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004401 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4402 return RD->hasTrivialDefaultConstructor() &&
4403 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004404 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004405 case UTT_HasTrivialMoveConstructor:
4406 // This trait is implemented by MSVC 2012 and needed to parse the
4407 // standard library headers. Specifically this is used as the logic
4408 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004409 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004410 return true;
4411 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4412 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4413 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004414 case UTT_HasTrivialCopy:
4415 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4416 // If __is_pod (type) is true or type is a reference type then
4417 // the trait is true, else if type is a cv class or union type
4418 // with a trivial copy constructor ([class.copy]) then the trait
4419 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004420 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004421 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004422 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4423 return RD->hasTrivialCopyConstructor() &&
4424 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004425 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004426 case UTT_HasTrivialMoveAssign:
4427 // This trait is implemented by MSVC 2012 and needed to parse the
4428 // standard library headers. Specifically it is used as the logic
4429 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004430 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004431 return true;
4432 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4433 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4434 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004435 case UTT_HasTrivialAssign:
4436 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4437 // If type is const qualified or is a reference type then the
4438 // trait is false. Otherwise if __is_pod (type) is true then the
4439 // trait is true, else if type is a cv class or union type with
4440 // a trivial copy assignment ([class.copy]) then the trait is
4441 // true, else it is false.
4442 // Note: the const and reference restrictions are interesting,
4443 // given that const and reference members don't prevent a class
4444 // from having a trivial copy assignment operator (but do cause
4445 // errors if the copy assignment operator is actually used, q.v.
4446 // [class.copy]p12).
4447
Richard Smith92f241f2012-12-08 02:53:02 +00004448 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004449 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004450 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004451 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004452 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4453 return RD->hasTrivialCopyAssignment() &&
4454 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004455 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004456 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004457 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004458 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004459 // C++14 [meta.unary.prop]:
4460 // For reference types, is_destructible<T>::value is true.
4461 if (T->isReferenceType())
4462 return true;
4463
4464 // Objective-C++ ARC: autorelease types don't require destruction.
4465 if (T->isObjCLifetimeType() &&
4466 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4467 return true;
4468
4469 // C++14 [meta.unary.prop]:
4470 // For incomplete types and function types, is_destructible<T>::value is
4471 // false.
4472 if (T->isIncompleteType() || T->isFunctionType())
4473 return false;
4474
Richard Smithf03e9082017-06-01 00:28:16 +00004475 // A type that requires destruction (via a non-trivial destructor or ARC
4476 // lifetime semantics) is not trivially-destructible.
4477 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4478 return false;
4479
David Majnemerac73de92015-08-11 03:03:28 +00004480 // C++14 [meta.unary.prop]:
4481 // For object types and given U equal to remove_all_extents_t<T>, if the
4482 // expression std::declval<U&>().~U() is well-formed when treated as an
4483 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4484 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4485 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4486 if (!Destructor)
4487 return false;
4488 // C++14 [dcl.fct.def.delete]p2:
4489 // A program that refers to a deleted function implicitly or
4490 // explicitly, other than to declare it, is ill-formed.
4491 if (Destructor->isDeleted())
4492 return false;
4493 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4494 return false;
4495 if (UTT == UTT_IsNothrowDestructible) {
4496 const FunctionProtoType *CPT =
4497 Destructor->getType()->getAs<FunctionProtoType>();
4498 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4499 if (!CPT || !CPT->isNothrow(C))
4500 return false;
4501 }
4502 }
4503 return true;
4504
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004505 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004506 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004507 // If __is_pod (type) is true or type is a reference type
4508 // then the trait is true, else if type is a cv class or union
4509 // type (or array thereof) with a trivial destructor
4510 // ([class.dtor]) then the trait is true, else it is
4511 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004512 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004513 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004514
John McCall31168b02011-06-15 23:02:42 +00004515 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004516 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004517 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4518 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004519
Richard Smith92f241f2012-12-08 02:53:02 +00004520 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4521 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004522 return false;
4523 // TODO: Propagate nothrowness for implicitly declared special members.
4524 case UTT_HasNothrowAssign:
4525 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4526 // If type is const qualified or is a reference type then the
4527 // trait is false. Otherwise if __has_trivial_assign (type)
4528 // is true then the trait is true, else if type is a cv class
4529 // or union type with copy assignment operators that are known
4530 // not to throw an exception then the trait is true, else it is
4531 // false.
4532 if (C.getBaseElementType(T).isConstQualified())
4533 return false;
4534 if (T->isReferenceType())
4535 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004536 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004537 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004538
Joao Matosc9523d42013-03-27 01:34:16 +00004539 if (const RecordType *RT = T->getAs<RecordType>())
4540 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4541 &CXXRecordDecl::hasTrivialCopyAssignment,
4542 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4543 &CXXMethodDecl::isCopyAssignmentOperator);
4544 return false;
4545 case UTT_HasNothrowMoveAssign:
4546 // This trait is implemented by MSVC 2012 and needed to parse the
4547 // standard library headers. Specifically this is used as the logic
4548 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004549 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004550 return true;
4551
4552 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4553 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4554 &CXXRecordDecl::hasTrivialMoveAssignment,
4555 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4556 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004557 return false;
4558 case UTT_HasNothrowCopy:
4559 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4560 // If __has_trivial_copy (type) is true then the trait is true, else
4561 // if type is a cv class or union type with copy constructors that are
4562 // known not to throw an exception then the trait is true, else it is
4563 // false.
John McCall31168b02011-06-15 23:02:42 +00004564 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004565 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004566 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4567 if (RD->hasTrivialCopyConstructor() &&
4568 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004569 return true;
4570
4571 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004572 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004573 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004574 // A template constructor is never a copy constructor.
4575 // FIXME: However, it may actually be selected at the actual overload
4576 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004577 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004578 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004579 // UsingDecl itself is not a constructor
4580 if (isa<UsingDecl>(ND))
4581 continue;
4582 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004583 if (Constructor->isCopyConstructor(FoundTQs)) {
4584 FoundConstructor = true;
4585 const FunctionProtoType *CPT
4586 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004587 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4588 if (!CPT)
4589 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004590 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004591 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004592 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004593 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004594 }
4595 }
4596
Richard Smith938f40b2011-06-11 17:19:42 +00004597 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004598 }
4599 return false;
4600 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004601 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004602 // If __has_trivial_constructor (type) is true then the trait is
4603 // true, else if type is a cv class or union type (or array
4604 // thereof) with a default constructor that is known not to
4605 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004606 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004607 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004608 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4609 if (RD->hasTrivialDefaultConstructor() &&
4610 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004611 return true;
4612
Alp Tokerb4bca412014-01-20 00:23:47 +00004613 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004614 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004615 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004616 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004617 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004618 // UsingDecl itself is not a constructor
4619 if (isa<UsingDecl>(ND))
4620 continue;
4621 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004622 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004623 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004624 const FunctionProtoType *CPT
4625 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004626 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4627 if (!CPT)
4628 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004629 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004630 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004631 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004632 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004633 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004634 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004635 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004636 }
4637 return false;
4638 case UTT_HasVirtualDestructor:
4639 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4640 // If type is a class type with a virtual destructor ([class.dtor])
4641 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004642 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004643 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004644 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004645 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004646
4647 // These type trait expressions are modeled on the specifications for the
4648 // Embarcadero C++0x type trait functions:
4649 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4650 case UTT_IsCompleteType:
4651 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4652 // Returns True if and only if T is a complete type at the point of the
4653 // function call.
4654 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004655 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004656 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004657 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004658}
Sebastian Redl5822f082009-02-07 20:10:22 +00004659
Alp Tokercbb90342013-12-13 20:49:58 +00004660static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4661 QualType RhsT, SourceLocation KeyLoc);
4662
Douglas Gregor29c42f22012-02-24 07:38:34 +00004663static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4664 ArrayRef<TypeSourceInfo *> Args,
4665 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004666 if (Kind <= UTT_Last)
4667 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4668
Eric Fiselier1af6c112018-01-12 00:09:37 +00004669 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4670 // traits to avoid duplication.
4671 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004672 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4673 Args[1]->getType(), RParenLoc);
4674
Douglas Gregor29c42f22012-02-24 07:38:34 +00004675 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004676 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004677 case clang::TT_IsConstructible:
4678 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004679 case clang::TT_IsTriviallyConstructible: {
4680 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004681 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004682 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004683 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004684 // definition for is_constructible, as defined below, is known to call
4685 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004686 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004687 // The predicate condition for a template specialization
4688 // is_constructible<T, Args...> shall be satisfied if and only if the
4689 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004690 // variable t:
4691 //
4692 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004693 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004694
4695 // Precondition: T and all types in the parameter pack Args shall be
4696 // complete types, (possibly cv-qualified) void, or arrays of
4697 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004698 for (const auto *TSI : Args) {
4699 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004700 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004701 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004702
Simon Pilgrim75c26882016-09-30 14:25:09 +00004703 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004704 diag::err_incomplete_type_used_in_type_trait_expr))
4705 return false;
4706 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004707
David Majnemer9658ecc2015-11-13 05:32:43 +00004708 // Make sure the first argument is not incomplete nor a function type.
4709 QualType T = Args[0]->getType();
4710 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004711 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004712
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004713 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004714 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004715 if (RD && RD->isAbstract())
4716 return false;
4717
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004718 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4719 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004720 ArgExprs.reserve(Args.size() - 1);
4721 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004722 QualType ArgTy = Args[I]->getType();
4723 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4724 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004725 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004726 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4727 ArgTy.getNonLValueExprType(S.Context),
4728 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004729 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004730 for (Expr &E : OpaqueArgExprs)
4731 ArgExprs.push_back(&E);
4732
Simon Pilgrim75c26882016-09-30 14:25:09 +00004733 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004734 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004735 EnterExpressionEvaluationContext Unevaluated(
4736 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004737 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4738 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4739 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4740 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4741 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004742 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004743 if (Init.Failed())
4744 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004745
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004746 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004747 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4748 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004749
Alp Toker73287bf2014-01-20 00:24:09 +00004750 if (Kind == clang::TT_IsConstructible)
4751 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004752
Eric Fiselier1af6c112018-01-12 00:09:37 +00004753 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4754 if (!T->isReferenceType())
4755 return false;
4756
4757 return !Init.isDirectReferenceBinding();
4758 }
4759
Alp Toker73287bf2014-01-20 00:24:09 +00004760 if (Kind == clang::TT_IsNothrowConstructible)
4761 return S.canThrow(Result.get()) == CT_Cannot;
4762
4763 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004764 // Under Objective-C ARC and Weak, if the destination has non-trivial
4765 // Objective-C lifetime, this is a non-trivial construction.
4766 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004767 return false;
4768
4769 // The initialization succeeded; now make sure there are no non-trivial
4770 // calls.
4771 return !Result.get()->hasNonTrivialCall(S.Context);
4772 }
4773
4774 llvm_unreachable("unhandled type trait");
4775 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004776 }
Alp Tokercbb90342013-12-13 20:49:58 +00004777 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004778 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004779
Douglas Gregor29c42f22012-02-24 07:38:34 +00004780 return false;
4781}
4782
Simon Pilgrim75c26882016-09-30 14:25:09 +00004783ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4784 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004785 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004786 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004787
Alp Toker95e7ff22014-01-01 05:57:51 +00004788 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4789 *this, Kind, KWLoc, Args[0]->getType()))
4790 return ExprError();
4791
Douglas Gregor29c42f22012-02-24 07:38:34 +00004792 bool Dependent = false;
4793 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4794 if (Args[I]->getType()->isDependentType()) {
4795 Dependent = true;
4796 break;
4797 }
4798 }
Alp Tokercbb90342013-12-13 20:49:58 +00004799
4800 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004801 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004802 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4803
4804 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4805 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004806}
4807
Alp Toker88f64e62013-12-13 21:19:30 +00004808ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4809 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004810 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004811 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004812 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004813
Douglas Gregor29c42f22012-02-24 07:38:34 +00004814 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4815 TypeSourceInfo *TInfo;
4816 QualType T = GetTypeFromParser(Args[I], &TInfo);
4817 if (!TInfo)
4818 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004819
4820 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004821 }
Alp Tokercbb90342013-12-13 20:49:58 +00004822
Douglas Gregor29c42f22012-02-24 07:38:34 +00004823 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4824}
4825
Alp Tokercbb90342013-12-13 20:49:58 +00004826static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4827 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004828 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4829 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004830
4831 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004832 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004833 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004834 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004835 // Base and Derived are not unions and name the same class type without
4836 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004837
John McCall388ef532011-01-28 22:02:36 +00004838 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004839 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004840 if (!rhsRecord || !lhsRecord) {
4841 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4842 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4843 if (!LHSObjTy || !RHSObjTy)
4844 return false;
4845
4846 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4847 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4848 if (!BaseInterface || !DerivedInterface)
4849 return false;
4850
4851 if (Self.RequireCompleteType(
4852 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4853 return false;
4854
4855 return BaseInterface->isSuperClassOf(DerivedInterface);
4856 }
John McCall388ef532011-01-28 22:02:36 +00004857
4858 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4859 == (lhsRecord == rhsRecord));
4860
4861 if (lhsRecord == rhsRecord)
4862 return !lhsRecord->getDecl()->isUnion();
4863
4864 // C++0x [meta.rel]p2:
4865 // If Base and Derived are class types and are different types
4866 // (ignoring possible cv-qualifiers) then Derived shall be a
4867 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004868 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004869 diag::err_incomplete_type_used_in_type_trait_expr))
4870 return false;
4871
4872 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4873 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4874 }
John Wiegley65497cc2011-04-27 23:09:49 +00004875 case BTT_IsSame:
4876 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00004877 case BTT_TypeCompatible: {
4878 // GCC ignores cv-qualifiers on arrays for this builtin.
4879 Qualifiers LhsQuals, RhsQuals;
4880 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
4881 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
4882 return Self.Context.typesAreCompatible(Lhs, Rhs);
4883 }
John Wiegley65497cc2011-04-27 23:09:49 +00004884 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004885 case BTT_IsConvertibleTo: {
4886 // C++0x [meta.rel]p4:
4887 // Given the following function prototype:
4888 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004889 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004890 // typename add_rvalue_reference<T>::type create();
4891 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004892 // the predicate condition for a template specialization
4893 // is_convertible<From, To> shall be satisfied if and only if
4894 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004895 // well-formed, including any implicit conversions to the return
4896 // type of the function:
4897 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004898 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004899 // return create<From>();
4900 // }
4901 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004902 // Access checking is performed as if in a context unrelated to To and
4903 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004904 // of the return-statement (including conversions to the return type)
4905 // is considered.
4906 //
4907 // We model the initialization as a copy-initialization of a temporary
4908 // of the appropriate type, which for this expression is identical to the
4909 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004910
4911 // Functions aren't allowed to return function or array types.
4912 if (RhsT->isFunctionType() || RhsT->isArrayType())
4913 return false;
4914
4915 // A return statement in a void function must have void type.
4916 if (RhsT->isVoidType())
4917 return LhsT->isVoidType();
4918
4919 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004920 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004921 return false;
4922
4923 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004924 if (LhsT->isObjectType() || LhsT->isFunctionType())
4925 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004926
4927 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004928 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004929 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004930 Expr::getValueKindForType(LhsT));
4931 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004932 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004933 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004934
4935 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004936 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004937 EnterExpressionEvaluationContext Unevaluated(
4938 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004939 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4940 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004941 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004942 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004943 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004944
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004945 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004946 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4947 }
Alp Toker73287bf2014-01-20 00:24:09 +00004948
David Majnemerb3d96882016-05-23 17:21:55 +00004949 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004950 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004951 case BTT_IsTriviallyAssignable: {
4952 // C++11 [meta.unary.prop]p3:
4953 // is_trivially_assignable is defined as:
4954 // is_assignable<T, U>::value is true and the assignment, as defined by
4955 // is_assignable, is known to call no operation that is not trivial
4956 //
4957 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004958 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004959 // treated as an unevaluated operand (Clause 5).
4960 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004961 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004962 // void, or arrays of unknown bound.
4963 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004964 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004965 diag::err_incomplete_type_used_in_type_trait_expr))
4966 return false;
4967 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004968 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004969 diag::err_incomplete_type_used_in_type_trait_expr))
4970 return false;
4971
4972 // cv void is never assignable.
4973 if (LhsT->isVoidType() || RhsT->isVoidType())
4974 return false;
4975
Simon Pilgrim75c26882016-09-30 14:25:09 +00004976 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004977 // declval<U>().
4978 if (LhsT->isObjectType() || LhsT->isFunctionType())
4979 LhsT = Self.Context.getRValueReferenceType(LhsT);
4980 if (RhsT->isObjectType() || RhsT->isFunctionType())
4981 RhsT = Self.Context.getRValueReferenceType(RhsT);
4982 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4983 Expr::getValueKindForType(LhsT));
4984 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4985 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004986
4987 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004988 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004989 EnterExpressionEvaluationContext Unevaluated(
4990 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004991 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00004992 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004993 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4994 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004995 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4996 return false;
4997
David Majnemerb3d96882016-05-23 17:21:55 +00004998 if (BTT == BTT_IsAssignable)
4999 return true;
5000
Alp Toker73287bf2014-01-20 00:24:09 +00005001 if (BTT == BTT_IsNothrowAssignable)
5002 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005003
Alp Toker73287bf2014-01-20 00:24:09 +00005004 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005005 // Under Objective-C ARC and Weak, if the destination has non-trivial
5006 // Objective-C lifetime, this is a non-trivial assignment.
5007 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005008 return false;
5009
5010 return !Result.get()->hasNonTrivialCall(Self.Context);
5011 }
5012
5013 llvm_unreachable("unhandled type trait");
5014 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005015 }
Alp Tokercbb90342013-12-13 20:49:58 +00005016 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005017 }
5018 llvm_unreachable("Unknown type trait or not implemented");
5019}
5020
John Wiegley6242b6a2011-04-28 00:16:57 +00005021ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5022 SourceLocation KWLoc,
5023 ParsedType Ty,
5024 Expr* DimExpr,
5025 SourceLocation RParen) {
5026 TypeSourceInfo *TSInfo;
5027 QualType T = GetTypeFromParser(Ty, &TSInfo);
5028 if (!TSInfo)
5029 TSInfo = Context.getTrivialTypeSourceInfo(T);
5030
5031 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5032}
5033
5034static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5035 QualType T, Expr *DimExpr,
5036 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005037 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005038
5039 switch(ATT) {
5040 case ATT_ArrayRank:
5041 if (T->isArrayType()) {
5042 unsigned Dim = 0;
5043 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5044 ++Dim;
5045 T = AT->getElementType();
5046 }
5047 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005048 }
John Wiegleyd3522222011-04-28 02:06:46 +00005049 return 0;
5050
John Wiegley6242b6a2011-04-28 00:16:57 +00005051 case ATT_ArrayExtent: {
5052 llvm::APSInt Value;
5053 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005054 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005055 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005056 false).isInvalid())
5057 return 0;
5058 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005059 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5060 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005061 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005062 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005063 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005064
5065 if (T->isArrayType()) {
5066 unsigned D = 0;
5067 bool Matched = false;
5068 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5069 if (Dim == D) {
5070 Matched = true;
5071 break;
5072 }
5073 ++D;
5074 T = AT->getElementType();
5075 }
5076
John Wiegleyd3522222011-04-28 02:06:46 +00005077 if (Matched && T->isArrayType()) {
5078 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5079 return CAT->getSize().getLimitedValue();
5080 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005081 }
John Wiegleyd3522222011-04-28 02:06:46 +00005082 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005083 }
5084 }
5085 llvm_unreachable("Unknown type trait or not implemented");
5086}
5087
5088ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5089 SourceLocation KWLoc,
5090 TypeSourceInfo *TSInfo,
5091 Expr* DimExpr,
5092 SourceLocation RParen) {
5093 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005094
Chandler Carruthc5276e52011-05-01 08:48:21 +00005095 // FIXME: This should likely be tracked as an APInt to remove any host
5096 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005097 uint64_t Value = 0;
5098 if (!T->isDependentType())
5099 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5100
Chandler Carruthc5276e52011-05-01 08:48:21 +00005101 // While the specification for these traits from the Embarcadero C++
5102 // compiler's documentation says the return type is 'unsigned int', Clang
5103 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5104 // compiler, there is no difference. On several other platforms this is an
5105 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005106 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5107 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005108}
5109
John Wiegleyf9f65842011-04-25 06:54:41 +00005110ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005111 SourceLocation KWLoc,
5112 Expr *Queried,
5113 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005114 // If error parsing the expression, ignore.
5115 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005116 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005117
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005118 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005119
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005120 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005121}
5122
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005123static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5124 switch (ET) {
5125 case ET_IsLValueExpr: return E->isLValue();
5126 case ET_IsRValueExpr: return E->isRValue();
5127 }
5128 llvm_unreachable("Expression trait not covered by switch");
5129}
5130
John Wiegleyf9f65842011-04-25 06:54:41 +00005131ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005132 SourceLocation KWLoc,
5133 Expr *Queried,
5134 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005135 if (Queried->isTypeDependent()) {
5136 // Delay type-checking for type-dependent expressions.
5137 } else if (Queried->getType()->isPlaceholderType()) {
5138 ExprResult PE = CheckPlaceholderExpr(Queried);
5139 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005140 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005141 }
5142
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005143 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005144
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005145 return new (Context)
5146 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005147}
5148
Richard Trieu82402a02011-09-15 21:56:47 +00005149QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005150 ExprValueKind &VK,
5151 SourceLocation Loc,
5152 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005153 assert(!LHS.get()->getType()->isPlaceholderType() &&
5154 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005155 "placeholders should have been weeded out by now");
5156
Richard Smith4baaa5a2016-12-03 01:14:32 +00005157 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5158 // temporary materialization conversion otherwise.
5159 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005160 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005161 else if (LHS.get()->isRValue())
5162 LHS = TemporaryMaterializationConversion(LHS.get());
5163 if (LHS.isInvalid())
5164 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005165
5166 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005167 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005168 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005169
Sebastian Redl5822f082009-02-07 20:10:22 +00005170 const char *OpSpelling = isIndirect ? "->*" : ".*";
5171 // C++ 5.5p2
5172 // The binary operator .* [p3: ->*] binds its second operand, which shall
5173 // be of type "pointer to member of T" (where T is a completely-defined
5174 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005175 QualType RHSType = RHS.get()->getType();
5176 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005177 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005178 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005179 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005180 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005181 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005182
Sebastian Redl5822f082009-02-07 20:10:22 +00005183 QualType Class(MemPtr->getClass(), 0);
5184
Douglas Gregord07ba342010-10-13 20:41:14 +00005185 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5186 // member pointer points must be completely-defined. However, there is no
5187 // reason for this semantic distinction, and the rule is not enforced by
5188 // other compilers. Therefore, we do not check this property, as it is
5189 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005190
Sebastian Redl5822f082009-02-07 20:10:22 +00005191 // C++ 5.5p2
5192 // [...] to its first operand, which shall be of class T or of a class of
5193 // which T is an unambiguous and accessible base class. [p3: a pointer to
5194 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005195 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005196 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005197 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5198 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005199 else {
5200 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005201 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005202 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005203 return QualType();
5204 }
5205 }
5206
Richard Trieu82402a02011-09-15 21:56:47 +00005207 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005208 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005209 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5210 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005211 return QualType();
5212 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005213
Richard Smith0f59cb32015-12-18 21:45:41 +00005214 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005215 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005216 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005217 return QualType();
5218 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005219
5220 CXXCastPath BasePath;
5221 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5222 SourceRange(LHS.get()->getLocStart(),
5223 RHS.get()->getLocEnd()),
5224 &BasePath))
5225 return QualType();
5226
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005227 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005228 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5229 if (isIndirect)
5230 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005231 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005232 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005233 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005234 }
5235
Richard Trieu82402a02011-09-15 21:56:47 +00005236 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005237 // Diagnose use of pointer-to-member type which when used as
5238 // the functional cast in a pointer-to-member expression.
5239 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5240 return QualType();
5241 }
John McCall7decc9e2010-11-18 06:31:45 +00005242
Sebastian Redl5822f082009-02-07 20:10:22 +00005243 // C++ 5.5p2
5244 // The result is an object or a function of the type specified by the
5245 // second operand.
5246 // The cv qualifiers are the union of those in the pointer and the left side,
5247 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005248 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005249 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005250
Douglas Gregor1d042092011-01-26 16:40:18 +00005251 // C++0x [expr.mptr.oper]p6:
5252 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253 // ill-formed if the second operand is a pointer to member function with
5254 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5255 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005256 // is a pointer to member function with ref-qualifier &&.
5257 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5258 switch (Proto->getRefQualifier()) {
5259 case RQ_None:
5260 // Do nothing
5261 break;
5262
5263 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005264 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5265 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5266 if (Proto->isConst())
5267 Diag(Loc, getLangOpts().CPlusPlus2a
5268 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5269 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5270 else
5271 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5272 << RHSType << 1 << LHS.get()->getSourceRange();
5273 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005274 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005275
Douglas Gregor1d042092011-01-26 16:40:18 +00005276 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005277 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005278 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005279 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005280 break;
5281 }
5282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283
John McCall7decc9e2010-11-18 06:31:45 +00005284 // C++ [expr.mptr.oper]p6:
5285 // The result of a .* expression whose second operand is a pointer
5286 // to a data member is of the same value category as its
5287 // first operand. The result of a .* expression whose second
5288 // operand is a pointer to a member function is a prvalue. The
5289 // result of an ->* expression is an lvalue if its second operand
5290 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005291 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005292 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005293 return Context.BoundMemberTy;
5294 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005295 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005296 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005297 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005298 }
John McCall7decc9e2010-11-18 06:31:45 +00005299
Sebastian Redl5822f082009-02-07 20:10:22 +00005300 return Result;
5301}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005302
Richard Smith2414bca2016-04-25 19:30:37 +00005303/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005304///
5305/// This is part of the parameter validation for the ? operator. If either
5306/// value operand is a class type, the two operands are attempted to be
5307/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005308/// It returns true if the program is ill-formed and has already been diagnosed
5309/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005310static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5311 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005312 bool &HaveConversion,
5313 QualType &ToType) {
5314 HaveConversion = false;
5315 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316
5317 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005318 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005319 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005320 // The process for determining whether an operand expression E1 of type T1
5321 // can be converted to match an operand expression E2 of type T2 is defined
5322 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005323 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5324 // implicitly converted to type "lvalue reference to T2", subject to the
5325 // constraint that in the conversion the reference must bind directly to
5326 // an lvalue.
5327 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5328 // implicitly conveted to the type "rvalue reference to R2", subject to
5329 // the constraint that the reference must bind directly.
5330 if (To->isLValue() || To->isXValue()) {
5331 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5332 : Self.Context.getRValueReferenceType(ToType);
5333
Douglas Gregor838fcc32010-03-26 20:14:36 +00005334 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005335
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005336 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005337 if (InitSeq.isDirectReferenceBinding()) {
5338 ToType = T;
5339 HaveConversion = true;
5340 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005342
Douglas Gregor838fcc32010-03-26 20:14:36 +00005343 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005344 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005345 }
John McCall65eb8792010-02-25 01:37:24 +00005346
Sebastian Redl1a99f442009-04-16 17:51:27 +00005347 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5348 // -- if E1 and E2 have class type, and the underlying class types are
5349 // the same or one is a base class of the other:
5350 QualType FTy = From->getType();
5351 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005352 const RecordType *FRec = FTy->getAs<RecordType>();
5353 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005355 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5356 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5357 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005358 // E1 can be converted to match E2 if the class of T2 is the
5359 // same type as, or a base class of, the class of T1, and
5360 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005361 if (FRec == TRec || FDerivedFromT) {
5362 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005363 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005364 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005365 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005366 HaveConversion = true;
5367 return false;
5368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369
Douglas Gregor838fcc32010-03-26 20:14:36 +00005370 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005371 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374
Douglas Gregor838fcc32010-03-26 20:14:36 +00005375 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005377
Douglas Gregor838fcc32010-03-26 20:14:36 +00005378 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5379 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005381 // an rvalue).
5382 //
5383 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5384 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005385 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005386
Douglas Gregor838fcc32010-03-26 20:14:36 +00005387 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005388 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005389 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005390 ToType = TTy;
5391 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005392 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005393
Sebastian Redl1a99f442009-04-16 17:51:27 +00005394 return false;
5395}
5396
5397/// \brief Try to find a common type for two according to C++0x 5.16p5.
5398///
5399/// This is part of the parameter validation for the ? operator. If either
5400/// value operand is a class type, overload resolution is used to find a
5401/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005402static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005403 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005404 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005405 OverloadCandidateSet CandidateSet(QuestionLoc,
5406 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005407 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005408 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005409
5410 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005411 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005412 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005413 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005414 ExprResult LHSRes = Self.PerformImplicitConversion(
5415 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5416 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005417 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005418 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005419 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005420
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005421 ExprResult RHSRes = Self.PerformImplicitConversion(
5422 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5423 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005424 if (RHSRes.isInvalid())
5425 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005426 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005427 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005428 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005429 return false;
John Wiegley01296292011-04-08 18:41:53 +00005430 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005432 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005433
5434 // Emit a better diagnostic if one of the expressions is a null pointer
5435 // constant and the other is a pointer type. In this case, the user most
5436 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005437 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005438 return true;
5439
5440 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005441 << LHS.get()->getType() << RHS.get()->getType()
5442 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005443 return true;
5444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005445 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005446 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005447 << LHS.get()->getType() << RHS.get()->getType()
5448 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005449 // FIXME: Print the possible common types by printing the return types of
5450 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005451 break;
5452
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005453 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005454 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005455 }
5456 return true;
5457}
5458
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005459/// \brief Perform an "extended" implicit conversion as returned by
5460/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005461static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005462 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005463 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005464 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005465 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005466 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005467 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005468 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005469 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470
John Wiegley01296292011-04-08 18:41:53 +00005471 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005472 return false;
5473}
5474
Sebastian Redl1a99f442009-04-16 17:51:27 +00005475/// \brief Check the operands of ?: under C++ semantics.
5476///
5477/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5478/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005479QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5480 ExprResult &RHS, ExprValueKind &VK,
5481 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005482 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005483 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5484 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005485
Richard Smith45edb702012-08-07 22:06:48 +00005486 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005487 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005488 //
5489 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5490 // a is that of a integer vector with the same number of elements and
5491 // size as the vectors of b and c. If one of either b or c is a scalar
5492 // it is implicitly converted to match the type of the vector.
5493 // Otherwise the expression is ill-formed. If both b and c are scalars,
5494 // then b and c are checked and converted to the type of a if possible.
5495 // Unlike the OpenCL ?: operator, the expression is evaluated as
5496 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005497 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005498 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005499 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005500 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005501 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005502 }
5503
John McCall7decc9e2010-11-18 06:31:45 +00005504 // Assume r-value.
5505 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005506 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005507
Sebastian Redl1a99f442009-04-16 17:51:27 +00005508 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005509 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005510 return Context.DependentTy;
5511
Richard Smith45edb702012-08-07 22:06:48 +00005512 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005514 QualType LTy = LHS.get()->getType();
5515 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005516 bool LVoid = LTy->isVoidType();
5517 bool RVoid = RTy->isVoidType();
5518 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005519 // ... one of the following shall hold:
5520 // -- The second or the third operand (but not both) is a (possibly
5521 // parenthesized) throw-expression; the result is of the type
5522 // and value category of the other.
5523 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5524 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5525 if (LThrow != RThrow) {
5526 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5527 VK = NonThrow->getValueKind();
5528 // DR (no number yet): the result is a bit-field if the
5529 // non-throw-expression operand is a bit-field.
5530 OK = NonThrow->getObjectKind();
5531 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005532 }
5533
Sebastian Redl1a99f442009-04-16 17:51:27 +00005534 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005535 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005536 if (LVoid && RVoid)
5537 return Context.VoidTy;
5538
5539 // Neither holds, error.
5540 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5541 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005542 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005543 return QualType();
5544 }
5545
5546 // Neither is void.
5547
Richard Smithf2b084f2012-08-08 06:13:49 +00005548 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005549 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005550 // either has (cv) class type [...] an attempt is made to convert each of
5551 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005553 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005554 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005555 QualType L2RType, R2LType;
5556 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005557 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005558 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005559 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005560 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005561
Sebastian Redl1a99f442009-04-16 17:51:27 +00005562 // If both can be converted, [...] the program is ill-formed.
5563 if (HaveL2R && HaveR2L) {
5564 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005565 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005566 return QualType();
5567 }
5568
5569 // If exactly one conversion is possible, that conversion is applied to
5570 // the chosen operand and the converted operands are used in place of the
5571 // original operands for the remainder of this section.
5572 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005573 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005574 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005575 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005576 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005577 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005578 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005579 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005580 }
5581 }
5582
Richard Smithf2b084f2012-08-08 06:13:49 +00005583 // C++11 [expr.cond]p3
5584 // if both are glvalues of the same value category and the same type except
5585 // for cv-qualification, an attempt is made to convert each of those
5586 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005587 // FIXME:
5588 // Resolving a defect in P0012R1: we extend this to cover all cases where
5589 // one of the operands is reference-compatible with the other, in order
5590 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005591 ExprValueKind LVK = LHS.get()->getValueKind();
5592 ExprValueKind RVK = RHS.get()->getValueKind();
5593 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005594 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005595 // DerivedToBase was already handled by the class-specific case above.
5596 // FIXME: Should we allow ObjC conversions here?
5597 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5598 if (CompareReferenceRelationship(
5599 QuestionLoc, LTy, RTy, DerivedToBase,
5600 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005601 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5602 // [...] subject to the constraint that the reference must bind
5603 // directly [...]
5604 !RHS.get()->refersToBitField() &&
5605 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005606 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005607 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005608 } else if (CompareReferenceRelationship(
5609 QuestionLoc, RTy, LTy, DerivedToBase,
5610 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005611 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5612 !LHS.get()->refersToBitField() &&
5613 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005614 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5615 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005616 }
5617 }
5618
5619 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005620 // If the second and third operands are glvalues of the same value
5621 // category and have the same type, the result is of that type and
5622 // value category and it is a bit-field if the second or the third
5623 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005624 // We only extend this to bitfields, not to the crazy other kinds of
5625 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005626 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005627 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005628 LHS.get()->isOrdinaryOrBitFieldObject() &&
5629 RHS.get()->isOrdinaryOrBitFieldObject()) {
5630 VK = LHS.get()->getValueKind();
5631 if (LHS.get()->getObjectKind() == OK_BitField ||
5632 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005633 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005634
5635 // If we have function pointer types, unify them anyway to unify their
5636 // exception specifications, if any.
5637 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5638 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005639 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005640 /*ConvertArgs*/false);
5641 LTy = Context.getQualifiedType(LTy, Qs);
5642
5643 assert(!LTy.isNull() && "failed to find composite pointer type for "
5644 "canonically equivalent function ptr types");
5645 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5646 }
5647
John McCall7decc9e2010-11-18 06:31:45 +00005648 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005649 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005650
Richard Smithf2b084f2012-08-08 06:13:49 +00005651 // C++11 [expr.cond]p5
5652 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005653 // do not have the same type, and either has (cv) class type, ...
5654 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5655 // ... overload resolution is used to determine the conversions (if any)
5656 // to be applied to the operands. If the overload resolution fails, the
5657 // program is ill-formed.
5658 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5659 return QualType();
5660 }
5661
Richard Smithf2b084f2012-08-08 06:13:49 +00005662 // C++11 [expr.cond]p6
5663 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005664 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005665 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5666 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005667 if (LHS.isInvalid() || RHS.isInvalid())
5668 return QualType();
5669 LTy = LHS.get()->getType();
5670 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005671
5672 // After those conversions, one of the following shall hold:
5673 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005674 // is of that type. If the operands have class type, the result
5675 // is a prvalue temporary of the result type, which is
5676 // copy-initialized from either the second operand or the third
5677 // operand depending on the value of the first operand.
5678 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5679 if (LTy->isRecordType()) {
5680 // The operands have class type. Make a temporary copy.
5681 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5684 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005685 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005686 if (LHSCopy.isInvalid())
5687 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688
5689 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5690 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005691 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005692 if (RHSCopy.isInvalid())
5693 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005694
John Wiegley01296292011-04-08 18:41:53 +00005695 LHS = LHSCopy;
5696 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005697 }
5698
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005699 // If we have function pointer types, unify them anyway to unify their
5700 // exception specifications, if any.
5701 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5702 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5703 assert(!LTy.isNull() && "failed to find composite pointer type for "
5704 "canonically equivalent function ptr types");
5705 }
5706
Sebastian Redl1a99f442009-04-16 17:51:27 +00005707 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005708 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005709
Douglas Gregor46188682010-05-18 22:42:18 +00005710 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005712 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5713 /*AllowBothBool*/true,
5714 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005715
Sebastian Redl1a99f442009-04-16 17:51:27 +00005716 // -- The second and third operands have arithmetic or enumeration type;
5717 // the usual arithmetic conversions are performed to bring them to a
5718 // common type, and the result is of that type.
5719 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005720 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005721 if (LHS.isInvalid() || RHS.isInvalid())
5722 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005723 if (ResTy.isNull()) {
5724 Diag(QuestionLoc,
5725 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5727 return QualType();
5728 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005729
5730 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5731 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5732
5733 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005734 }
5735
5736 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005737 // type and the other is a null pointer constant, or both are null
5738 // pointer constants, at least one of which is non-integral; pointer
5739 // conversions and qualification conversions are performed to bring them
5740 // to their composite pointer type. The result is of the composite
5741 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005742 // -- The second and third operands have pointer to member type, or one has
5743 // pointer to member type and the other is a null pointer constant;
5744 // pointer to member conversions and qualification conversions are
5745 // performed to bring them to a common type, whose cv-qualification
5746 // shall match the cv-qualification of either the second or the third
5747 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005748 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5749 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005750 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Douglas Gregor697a3912010-04-01 22:47:07 +00005752 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005753 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5754 if (!Composite.isNull())
5755 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005756
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005757 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005758 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005759 return QualType();
5760
Sebastian Redl1a99f442009-04-16 17:51:27 +00005761 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005762 << LHS.get()->getType() << RHS.get()->getType()
5763 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005764 return QualType();
5765}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005766
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005767static FunctionProtoType::ExceptionSpecInfo
5768mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5769 FunctionProtoType::ExceptionSpecInfo ESI2,
5770 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5771 ExceptionSpecificationType EST1 = ESI1.Type;
5772 ExceptionSpecificationType EST2 = ESI2.Type;
5773
5774 // If either of them can throw anything, that is the result.
5775 if (EST1 == EST_None) return ESI1;
5776 if (EST2 == EST_None) return ESI2;
5777 if (EST1 == EST_MSAny) return ESI1;
5778 if (EST2 == EST_MSAny) return ESI2;
5779
5780 // If either of them is non-throwing, the result is the other.
5781 if (EST1 == EST_DynamicNone) return ESI2;
5782 if (EST2 == EST_DynamicNone) return ESI1;
5783 if (EST1 == EST_BasicNoexcept) return ESI2;
5784 if (EST2 == EST_BasicNoexcept) return ESI1;
5785
5786 // If either of them is a non-value-dependent computed noexcept, that
5787 // determines the result.
5788 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5789 !ESI2.NoexceptExpr->isValueDependent())
5790 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5791 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5792 !ESI1.NoexceptExpr->isValueDependent())
5793 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5794 // If we're left with value-dependent computed noexcept expressions, we're
5795 // stuck. Before C++17, we can just drop the exception specification entirely,
5796 // since it's not actually part of the canonical type. And this should never
5797 // happen in C++17, because it would mean we were computing the composite
5798 // pointer type of dependent types, which should never happen.
5799 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005800 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005801 "computing composite pointer type of dependent types");
5802 return FunctionProtoType::ExceptionSpecInfo();
5803 }
5804
5805 // Switch over the possibilities so that people adding new values know to
5806 // update this function.
5807 switch (EST1) {
5808 case EST_None:
5809 case EST_DynamicNone:
5810 case EST_MSAny:
5811 case EST_BasicNoexcept:
5812 case EST_ComputedNoexcept:
5813 llvm_unreachable("handled above");
5814
5815 case EST_Dynamic: {
5816 // This is the fun case: both exception specifications are dynamic. Form
5817 // the union of the two lists.
5818 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5819 llvm::SmallPtrSet<QualType, 8> Found;
5820 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5821 for (QualType E : Exceptions)
5822 if (Found.insert(S.Context.getCanonicalType(E)).second)
5823 ExceptionTypeStorage.push_back(E);
5824
5825 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5826 Result.Exceptions = ExceptionTypeStorage;
5827 return Result;
5828 }
5829
5830 case EST_Unevaluated:
5831 case EST_Uninstantiated:
5832 case EST_Unparsed:
5833 llvm_unreachable("shouldn't see unresolved exception specifications here");
5834 }
5835
5836 llvm_unreachable("invalid ExceptionSpecificationType");
5837}
5838
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005839/// \brief Find a merged pointer type and convert the two expressions to it.
5840///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005841/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005842/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005843/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005844/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005845///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005846/// \param Loc The location of the operator requiring these two expressions to
5847/// be converted to the composite pointer type.
5848///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005849/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005850QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005851 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005852 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005853 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005854
5855 // C++1z [expr]p14:
5856 // The composite pointer type of two operands p1 and p2 having types T1
5857 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005858 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005859
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005860 // where at least one is a pointer or pointer to member type or
5861 // std::nullptr_t is:
5862 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5863 T1->isNullPtrType();
5864 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5865 T2->isNullPtrType();
5866 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005867 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005868
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005869 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5870 // This can't actually happen, following the standard, but we also use this
5871 // to implement the end of [expr.conv], which hits this case.
5872 //
5873 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5874 if (T1IsPointerLike &&
5875 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005876 if (ConvertArgs)
5877 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5878 ? CK_NullToMemberPointer
5879 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005880 return T1;
5881 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005882 if (T2IsPointerLike &&
5883 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005884 if (ConvertArgs)
5885 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5886 ? CK_NullToMemberPointer
5887 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005888 return T2;
5889 }
Mike Stump11289f42009-09-09 15:08:12 +00005890
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005891 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005892 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005893 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005894 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5895 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005896
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005897 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5898 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5899 // the union of cv1 and cv2;
5900 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5901 // "pointer to function", where the function types are otherwise the same,
5902 // "pointer to function";
5903 // FIXME: This rule is defective: it should also permit removing noexcept
5904 // from a pointer to member function. As a Clang extension, we also
5905 // permit removing 'noreturn', so we generalize this rule to;
5906 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5907 // "pointer to member function" and the pointee types can be unified
5908 // by a function pointer conversion, that conversion is applied
5909 // before checking the following rules.
5910 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5911 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5912 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5913 // respectively;
5914 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5915 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5916 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5917 // T1 or the cv-combined type of T1 and T2, respectively;
5918 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5919 // T2;
5920 //
5921 // If looked at in the right way, these bullets all do the same thing.
5922 // What we do here is, we build the two possible cv-combined types, and try
5923 // the conversions in both directions. If only one works, or if the two
5924 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005925 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005926 //
5927 // Note that this will fail to find a composite pointer type for "pointer
5928 // to void" and "pointer to function". We can't actually perform the final
5929 // conversion in this case, even though a composite pointer type formally
5930 // exists.
5931 SmallVector<unsigned, 4> QualifierUnion;
5932 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005933 QualType Composite1 = T1;
5934 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005936 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005937 const PointerType *Ptr1, *Ptr2;
5938 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5939 (Ptr2 = Composite2->getAs<PointerType>())) {
5940 Composite1 = Ptr1->getPointeeType();
5941 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005942
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005943 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005944 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005945 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005946 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005947
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005948 QualifierUnion.push_back(
5949 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005950 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005951 continue;
5952 }
Mike Stump11289f42009-09-09 15:08:12 +00005953
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005954 const MemberPointerType *MemPtr1, *MemPtr2;
5955 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5956 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5957 Composite1 = MemPtr1->getPointeeType();
5958 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005959
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005960 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005962 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005963 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005964
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005965 QualifierUnion.push_back(
5966 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5967 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5968 MemPtr2->getClass()));
5969 continue;
5970 }
Mike Stump11289f42009-09-09 15:08:12 +00005971
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005972 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005973
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005974 // Cannot unwrap any more types.
5975 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005976 }
Mike Stump11289f42009-09-09 15:08:12 +00005977
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005978 // Apply the function pointer conversion to unify the types. We've already
5979 // unwrapped down to the function types, and we want to merge rather than
5980 // just convert, so do this ourselves rather than calling
5981 // IsFunctionConversion.
5982 //
5983 // FIXME: In order to match the standard wording as closely as possible, we
5984 // currently only do this under a single level of pointers. Ideally, we would
5985 // allow this in general, and set NeedConstBefore to the relevant depth on
5986 // the side(s) where we changed anything.
5987 if (QualifierUnion.size() == 1) {
5988 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5989 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5990 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5991 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5992
5993 // The result is noreturn if both operands are.
5994 bool Noreturn =
5995 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5996 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5997 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5998
5999 // The result is nothrow if both operands are.
6000 SmallVector<QualType, 8> ExceptionTypeStorage;
6001 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6002 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6003 ExceptionTypeStorage);
6004
6005 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6006 FPT1->getParamTypes(), EPI1);
6007 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6008 FPT2->getParamTypes(), EPI2);
6009 }
6010 }
6011 }
6012
Richard Smith5e9746f2016-10-21 22:00:42 +00006013 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006014 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006015 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006016 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006017 for (unsigned I = 0; I != NeedConstBefore; ++I)
6018 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006019 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006022 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006023 auto MOC = MemberOfClass.rbegin();
6024 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6025 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6026 auto Classes = *MOC++;
6027 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006028 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006029 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006030 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006031 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006032 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006033 } else {
6034 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006035 Composite1 =
6036 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6037 Composite2 =
6038 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006039 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006040 }
6041
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006042 struct Conversion {
6043 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006044 Expr *&E1, *&E2;
6045 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006046 InitializedEntity Entity;
6047 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006048 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006049 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006050
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006051 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6052 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006053 : S(S), E1(E1), E2(E2), Composite(Composite),
6054 Entity(InitializedEntity::InitializeTemporary(Composite)),
6055 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6056 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6057 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006058
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006059 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006060 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6061 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006062 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006063 E1 = E1Result.getAs<Expr>();
6064
6065 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6066 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006067 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006068 E2 = E2Result.getAs<Expr>();
6069
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006070 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006071 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006072 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006073
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006074 // Try to convert to each composite pointer type.
6075 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006076 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6077 if (ConvertArgs && C1.perform())
6078 return QualType();
6079 return C1.Composite;
6080 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006081 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006082
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006083 if (C1.Viable == C2.Viable) {
6084 // Either Composite1 and Composite2 are viable and are different, or
6085 // neither is viable.
6086 // FIXME: How both be viable and different?
6087 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006088 }
6089
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006090 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006091 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6092 return QualType();
6093
6094 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006095}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006096
John McCalldadc5752010-08-24 06:29:42 +00006097ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006098 if (!E)
6099 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
John McCall31168b02011-06-15 23:02:42 +00006101 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6102
6103 // If the result is a glvalue, we shouldn't bind it.
6104 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006105 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006106
John McCall31168b02011-06-15 23:02:42 +00006107 // In ARC, calls that return a retainable type can return retained,
6108 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006109 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006110 E->getType()->isObjCRetainableType()) {
6111
6112 bool ReturnsRetained;
6113
6114 // For actual calls, we compute this by examining the type of the
6115 // called value.
6116 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6117 Expr *Callee = Call->getCallee()->IgnoreParens();
6118 QualType T = Callee->getType();
6119
6120 if (T == Context.BoundMemberTy) {
6121 // Handle pointer-to-members.
6122 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6123 T = BinOp->getRHS()->getType();
6124 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6125 T = Mem->getMemberDecl()->getType();
6126 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006127
John McCall31168b02011-06-15 23:02:42 +00006128 if (const PointerType *Ptr = T->getAs<PointerType>())
6129 T = Ptr->getPointeeType();
6130 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6131 T = Ptr->getPointeeType();
6132 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6133 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006134
John McCall31168b02011-06-15 23:02:42 +00006135 const FunctionType *FTy = T->getAs<FunctionType>();
6136 assert(FTy && "call to value not of function type?");
6137 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6138
6139 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6140 // type always produce a +1 object.
6141 } else if (isa<StmtExpr>(E)) {
6142 ReturnsRetained = true;
6143
Ted Kremeneke65b0862012-03-06 20:05:56 +00006144 // We hit this case with the lambda conversion-to-block optimization;
6145 // we don't want any extra casts here.
6146 } else if (isa<CastExpr>(E) &&
6147 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006148 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006149
John McCall31168b02011-06-15 23:02:42 +00006150 // For message sends and property references, we try to find an
6151 // actual method. FIXME: we should infer retention by selector in
6152 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006153 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006154 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006155 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6156 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006157 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6158 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006159 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006160 // Don't do reclaims if we're using the zero-element array
6161 // constant.
6162 if (ArrayLit->getNumElements() == 0 &&
6163 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6164 return E;
6165
Ted Kremeneke65b0862012-03-06 20:05:56 +00006166 D = ArrayLit->getArrayWithObjectsMethod();
6167 } else if (ObjCDictionaryLiteral *DictLit
6168 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006169 // Don't do reclaims if we're using the zero-element dictionary
6170 // constant.
6171 if (DictLit->getNumElements() == 0 &&
6172 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6173 return E;
6174
Ted Kremeneke65b0862012-03-06 20:05:56 +00006175 D = DictLit->getDictWithObjectsMethod();
6176 }
John McCall31168b02011-06-15 23:02:42 +00006177
6178 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006179
6180 // Don't do reclaims on performSelector calls; despite their
6181 // return type, the invoked method doesn't necessarily actually
6182 // return an object.
6183 if (!ReturnsRetained &&
6184 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006185 return E;
John McCall31168b02011-06-15 23:02:42 +00006186 }
6187
John McCall16de4d22011-11-14 19:53:16 +00006188 // Don't reclaim an object of Class type.
6189 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006190 return E;
John McCall16de4d22011-11-14 19:53:16 +00006191
Tim Shen4a05bb82016-06-21 20:29:17 +00006192 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006193
John McCall2d637d22011-09-10 06:18:15 +00006194 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6195 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006196 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6197 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006198 }
6199
David Blaikiebbafb8a2012-03-11 07:00:24 +00006200 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006201 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006202
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006203 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6204 // a fast path for the common case that the type is directly a RecordType.
6205 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006206 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006207 while (!RT) {
6208 switch (T->getTypeClass()) {
6209 case Type::Record:
6210 RT = cast<RecordType>(T);
6211 break;
6212 case Type::ConstantArray:
6213 case Type::IncompleteArray:
6214 case Type::VariableArray:
6215 case Type::DependentSizedArray:
6216 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6217 break;
6218 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006219 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006220 }
6221 }
Mike Stump11289f42009-09-09 15:08:12 +00006222
Richard Smithfd555f62012-02-22 02:04:18 +00006223 // That should be enough to guarantee that this type is complete, if we're
6224 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006225 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006226 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006227 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006228
6229 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006230 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006231
John McCall31168b02011-06-15 23:02:42 +00006232 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006233 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006234 CheckDestructorAccess(E->getExprLoc(), Destructor,
6235 PDiag(diag::err_access_dtor_temp)
6236 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006237 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6238 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006239
Richard Smithfd555f62012-02-22 02:04:18 +00006240 // If destructor is trivial, we can avoid the extra copy.
6241 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006242 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006243
John McCall28fc7092011-11-10 05:35:25 +00006244 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006245 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006246 }
Richard Smitheec915d62012-02-18 04:13:32 +00006247
6248 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006249 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6250
6251 if (IsDecltype)
6252 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6253
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006254 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006255}
6256
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257ExprResult
John McCall5d413782010-12-06 08:20:24 +00006258Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006259 if (SubExpr.isInvalid())
6260 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006262 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006263}
6264
John McCall28fc7092011-11-10 05:35:25 +00006265Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006266 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006267
Eli Friedman3bda6b12012-02-02 23:15:15 +00006268 CleanupVarDeclMarking();
6269
John McCall28fc7092011-11-10 05:35:25 +00006270 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6271 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006272 assert(Cleanup.exprNeedsCleanups() ||
6273 ExprCleanupObjects.size() == FirstCleanup);
6274 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006275 return SubExpr;
6276
Craig Topper5fc8fc22014-08-27 06:28:36 +00006277 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6278 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006279
Tim Shen4a05bb82016-06-21 20:29:17 +00006280 auto *E = ExprWithCleanups::Create(
6281 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006282 DiscardCleanupsInEvaluationContext();
6283
6284 return E;
6285}
6286
John McCall5d413782010-12-06 08:20:24 +00006287Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006288 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006289
Eli Friedman3bda6b12012-02-02 23:15:15 +00006290 CleanupVarDeclMarking();
6291
Tim Shen4a05bb82016-06-21 20:29:17 +00006292 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006293 return SubStmt;
6294
6295 // FIXME: In order to attach the temporaries, wrap the statement into
6296 // a StmtExpr; currently this is only used for asm statements.
6297 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6298 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006299 CompoundStmt *CompStmt = CompoundStmt::Create(
6300 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006301 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6302 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006303 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006304}
6305
Richard Smithfd555f62012-02-22 02:04:18 +00006306/// Process the expression contained within a decltype. For such expressions,
6307/// certain semantic checks on temporaries are delayed until this point, and
6308/// are omitted for the 'topmost' call in the decltype expression. If the
6309/// topmost call bound a temporary, strip that temporary off the expression.
6310ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006311 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006312
6313 // C++11 [expr.call]p11:
6314 // If a function call is a prvalue of object type,
6315 // -- if the function call is either
6316 // -- the operand of a decltype-specifier, or
6317 // -- the right operand of a comma operator that is the operand of a
6318 // decltype-specifier,
6319 // a temporary object is not introduced for the prvalue.
6320
6321 // Recursively rebuild ParenExprs and comma expressions to strip out the
6322 // outermost CXXBindTemporaryExpr, if any.
6323 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6324 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6325 if (SubExpr.isInvalid())
6326 return ExprError();
6327 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006328 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006329 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006330 }
6331 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6332 if (BO->getOpcode() == BO_Comma) {
6333 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6334 if (RHS.isInvalid())
6335 return ExprError();
6336 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006337 return E;
6338 return new (Context) BinaryOperator(
6339 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006340 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006341 }
6342 }
6343
6344 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006345 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6346 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006347 if (TopCall)
6348 E = TopCall;
6349 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006350 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006351
6352 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006353 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006354
Richard Smithf86b0ae2012-07-28 19:54:11 +00006355 // In MS mode, don't perform any extra checking of call return types within a
6356 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006357 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006358 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006359
Richard Smithfd555f62012-02-22 02:04:18 +00006360 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006361 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6362 I != N; ++I) {
6363 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006364 if (Call == TopCall)
6365 continue;
6366
David Majnemerced8bdf2015-02-25 17:36:15 +00006367 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006368 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006369 Call, Call->getDirectCallee()))
6370 return ExprError();
6371 }
6372
6373 // Now all relevant types are complete, check the destructors are accessible
6374 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006375 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6376 I != N; ++I) {
6377 CXXBindTemporaryExpr *Bind =
6378 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006379 if (Bind == TopBind)
6380 continue;
6381
6382 CXXTemporary *Temp = Bind->getTemporary();
6383
6384 CXXRecordDecl *RD =
6385 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6386 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6387 Temp->setDestructor(Destructor);
6388
Richard Smith7d847b12012-05-11 22:20:10 +00006389 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6390 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006391 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006392 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006393 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6394 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006395
6396 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006397 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006398 }
6399
6400 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006401 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006402}
6403
Richard Smith79c927b2013-11-06 19:31:51 +00006404/// Note a set of 'operator->' functions that were used for a member access.
6405static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006406 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006407 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6408 // FIXME: Make this configurable?
6409 unsigned Limit = 9;
6410 if (OperatorArrows.size() > Limit) {
6411 // Produce Limit-1 normal notes and one 'skipping' note.
6412 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6413 SkipCount = OperatorArrows.size() - (Limit - 1);
6414 }
6415
6416 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6417 if (I == SkipStart) {
6418 S.Diag(OperatorArrows[I]->getLocation(),
6419 diag::note_operator_arrows_suppressed)
6420 << SkipCount;
6421 I += SkipCount;
6422 } else {
6423 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6424 << OperatorArrows[I]->getCallResultType();
6425 ++I;
6426 }
6427 }
6428}
6429
Nico Weber964d3322015-02-16 22:35:45 +00006430ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6431 SourceLocation OpLoc,
6432 tok::TokenKind OpKind,
6433 ParsedType &ObjectType,
6434 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006435 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006436 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006437 if (Result.isInvalid()) return ExprError();
6438 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006439
John McCall526ab472011-10-25 17:37:35 +00006440 Result = CheckPlaceholderExpr(Base);
6441 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006442 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006443
John McCallb268a282010-08-23 23:25:46 +00006444 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006445 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006446 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006447 // If we have a pointer to a dependent type and are using the -> operator,
6448 // the object type is the type that the pointer points to. We might still
6449 // have enough information about that type to do something useful.
6450 if (OpKind == tok::arrow)
6451 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6452 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453
John McCallba7bf592010-08-24 05:47:05 +00006454 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006455 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006456 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006457 }
Mike Stump11289f42009-09-09 15:08:12 +00006458
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006459 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006460 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006461 // returned, with the original second operand.
6462 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006463 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006464 bool NoArrowOperatorFound = false;
6465 bool FirstIteration = true;
6466 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006467 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006468 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006469 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006470 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006472 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006473 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6474 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006475 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006476 noteOperatorArrows(*this, OperatorArrows);
6477 Diag(OpLoc, diag::note_operator_arrow_depth)
6478 << getLangOpts().ArrowDepth;
6479 return ExprError();
6480 }
6481
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006482 Result = BuildOverloadedArrowExpr(
6483 S, Base, OpLoc,
6484 // When in a template specialization and on the first loop iteration,
6485 // potentially give the default diagnostic (with the fixit in a
6486 // separate note) instead of having the error reported back to here
6487 // and giving a diagnostic with a fixit attached to the error itself.
6488 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006489 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006490 : &NoArrowOperatorFound);
6491 if (Result.isInvalid()) {
6492 if (NoArrowOperatorFound) {
6493 if (FirstIteration) {
6494 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006495 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006496 << FixItHint::CreateReplacement(OpLoc, ".");
6497 OpKind = tok::period;
6498 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006499 }
6500 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6501 << BaseType << Base->getSourceRange();
6502 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006503 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006504 Diag(CD->getLocStart(),
6505 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006506 }
6507 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006508 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006509 }
John McCallb268a282010-08-23 23:25:46 +00006510 Base = Result.get();
6511 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006512 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006513 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006514 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006515 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006516 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6517 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006518 return ExprError();
6519 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006520 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006521 }
Mike Stump11289f42009-09-09 15:08:12 +00006522
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006523 if (OpKind == tok::arrow &&
6524 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006525 BaseType = BaseType->getPointeeType();
6526 }
Mike Stump11289f42009-09-09 15:08:12 +00006527
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006528 // Objective-C properties allow "." access on Objective-C pointer types,
6529 // so adjust the base type to the object type itself.
6530 if (BaseType->isObjCObjectPointerType())
6531 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006532
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006533 // C++ [basic.lookup.classref]p2:
6534 // [...] If the type of the object expression is of pointer to scalar
6535 // type, the unqualified-id is looked up in the context of the complete
6536 // postfix-expression.
6537 //
6538 // This also indicates that we could be parsing a pseudo-destructor-name.
6539 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006540 // expressions or normal member (ivar or property) access expressions, and
6541 // it's legal for the type to be incomplete if this is a pseudo-destructor
6542 // call. We'll do more incomplete-type checks later in the lookup process,
6543 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006544 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006545 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006546 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006547 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006548 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006549 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006550 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006551 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006552 }
Mike Stump11289f42009-09-09 15:08:12 +00006553
Douglas Gregor3024f072012-04-16 07:05:22 +00006554 // The object type must be complete (or dependent), or
6555 // C++11 [expr.prim.general]p3:
6556 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006557 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006558 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006559 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006560 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006561 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006562 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006563
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006564 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006565 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006566 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006567 // type C (or of pointer to a class type C), the unqualified-id is looked
6568 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006569 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006570 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006571}
6572
Simon Pilgrim75c26882016-09-30 14:25:09 +00006573static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006574 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006575 if (Base->hasPlaceholderType()) {
6576 ExprResult result = S.CheckPlaceholderExpr(Base);
6577 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006578 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006579 }
6580 ObjectType = Base->getType();
6581
David Blaikie1d578782011-12-16 16:03:09 +00006582 // C++ [expr.pseudo]p2:
6583 // The left-hand side of the dot operator shall be of scalar type. The
6584 // left-hand side of the arrow operator shall be of pointer to scalar type.
6585 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006586 // Note that this is rather different from the normal handling for the
6587 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006588 if (OpKind == tok::arrow) {
6589 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6590 ObjectType = Ptr->getPointeeType();
6591 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006592 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006593 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6594 << ObjectType << true
6595 << FixItHint::CreateReplacement(OpLoc, ".");
6596 if (S.isSFINAEContext())
6597 return true;
6598
6599 OpKind = tok::period;
6600 }
6601 }
6602
6603 return false;
6604}
6605
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006606/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6607/// pointer objects.
6608static bool
6609canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6610 QualType DestructedType) {
6611 // If this is a record type, check if its destructor is callable.
6612 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6613 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6614 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6615 return false;
6616 }
6617
6618 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6619 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6620 DestructedType->isVectorType();
6621}
6622
John McCalldadc5752010-08-24 06:29:42 +00006623ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006624 SourceLocation OpLoc,
6625 tok::TokenKind OpKind,
6626 const CXXScopeSpec &SS,
6627 TypeSourceInfo *ScopeTypeInfo,
6628 SourceLocation CCLoc,
6629 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006630 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006631 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632
Eli Friedman0ce4de42012-01-25 04:35:06 +00006633 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006634 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6635 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregorc5c57342012-09-10 14:57:06 +00006637 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6638 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006639 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006640 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006641 else {
Nico Weber58829272012-01-23 05:50:57 +00006642 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6643 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006644 return ExprError();
6645 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006646 }
6647
6648 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006649 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006650 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006651 if (DestructedTypeInfo) {
6652 QualType DestructedType = DestructedTypeInfo->getType();
6653 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006654 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006655 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6656 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006657 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6658 // Foo *foo;
6659 // foo.~Foo();
6660 if (OpKind == tok::period && ObjectType->isPointerType() &&
6661 Context.hasSameUnqualifiedType(DestructedType,
6662 ObjectType->getPointeeType())) {
6663 auto Diagnostic =
6664 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6665 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006666
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006667 // Issue a fixit only when the destructor is valid.
6668 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6669 *this, DestructedType))
6670 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6671
6672 // Recover by setting the object type to the destructed type and the
6673 // operator to '->'.
6674 ObjectType = DestructedType;
6675 OpKind = tok::arrow;
6676 } else {
6677 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6678 << ObjectType << DestructedType << Base->getSourceRange()
6679 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6680
6681 // Recover by setting the destructed type to the object type.
6682 DestructedType = ObjectType;
6683 DestructedTypeInfo =
6684 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6685 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6686 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006687 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006688 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006689
John McCall31168b02011-06-15 23:02:42 +00006690 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6691 // Okay: just pretend that the user provided the correctly-qualified
6692 // type.
6693 } else {
6694 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6695 << ObjectType << DestructedType << Base->getSourceRange()
6696 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6697 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006698
John McCall31168b02011-06-15 23:02:42 +00006699 // Recover by setting the destructed type to the object type.
6700 DestructedType = ObjectType;
6701 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6702 DestructedTypeStart);
6703 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6704 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006705 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006708 // C++ [expr.pseudo]p2:
6709 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6710 // form
6711 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006713 //
6714 // shall designate the same scalar type.
6715 if (ScopeTypeInfo) {
6716 QualType ScopeType = ScopeTypeInfo->getType();
6717 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006718 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006719
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006720 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006721 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006722 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006723 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006725 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006726 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006727 }
6728 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006729
John McCallb268a282010-08-23 23:25:46 +00006730 Expr *Result
6731 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6732 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006733 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006734 ScopeTypeInfo,
6735 CCLoc,
6736 TildeLoc,
6737 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738
David Majnemerced8bdf2015-02-25 17:36:15 +00006739 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006740}
6741
John McCalldadc5752010-08-24 06:29:42 +00006742ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006743 SourceLocation OpLoc,
6744 tok::TokenKind OpKind,
6745 CXXScopeSpec &SS,
6746 UnqualifiedId &FirstTypeName,
6747 SourceLocation CCLoc,
6748 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006749 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006750 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6751 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006752 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006753 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6754 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006755 "Invalid second type name in pseudo-destructor");
6756
Eli Friedman0ce4de42012-01-25 04:35:06 +00006757 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006758 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6759 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006760
6761 // Compute the object type that we should use for name lookup purposes. Only
6762 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006763 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006764 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006765 if (ObjectType->isRecordType())
6766 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006767 else if (ObjectType->isDependentType())
6768 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
6771 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006772 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006773 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006774 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006775 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006776 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006777 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006778 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006779 S, &SS, true, false, ObjectTypePtrForLookup,
6780 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006781 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006782 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6783 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006784 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006785 // couldn't find anything useful in scope. Just store the identifier and
6786 // it's location, and we'll perform (qualified) name lookup again at
6787 // template instantiation time.
6788 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6789 SecondTypeName.StartLocation);
6790 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006792 diag::err_pseudo_dtor_destructor_non_type)
6793 << SecondTypeName.Identifier << ObjectType;
6794 if (isSFINAEContext())
6795 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006796
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006797 // Recover by assuming we had the right type all along.
6798 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006799 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006800 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006801 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006802 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006803 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006804 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006805 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006806 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006807 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006808 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006809 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006810 TemplateId->TemplateNameLoc,
6811 TemplateId->LAngleLoc,
6812 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006813 TemplateId->RAngleLoc,
6814 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006815 if (T.isInvalid() || !T.get()) {
6816 // Recover by assuming we had the right type all along.
6817 DestructedType = ObjectType;
6818 } else
6819 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006821
6822 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006823 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006824 if (!DestructedType.isNull()) {
6825 if (!DestructedTypeInfo)
6826 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006827 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006828 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006831 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006832 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006833 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006834 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006835 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006836 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006837 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006838 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006839 S, &SS, true, false, ObjectTypePtrForLookup,
6840 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006841 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006843 diag::err_pseudo_dtor_destructor_non_type)
6844 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006845
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006846 if (isSFINAEContext())
6847 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006849 // Just drop this type. It's unnecessary anyway.
6850 ScopeType = QualType();
6851 } else
6852 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006853 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006854 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006855 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006856 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006857 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006858 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006859 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006860 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006861 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006862 TemplateId->TemplateNameLoc,
6863 TemplateId->LAngleLoc,
6864 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006865 TemplateId->RAngleLoc,
6866 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006867 if (T.isInvalid() || !T.get()) {
6868 // Recover by dropping this type.
6869 ScopeType = QualType();
6870 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006871 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006872 }
6873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006874
Douglas Gregor90ad9222010-02-24 23:02:30 +00006875 if (!ScopeType.isNull() && !ScopeTypeInfo)
6876 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6877 FirstTypeName.StartLocation);
6878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879
John McCallb268a282010-08-23 23:25:46 +00006880 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006881 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006882 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006883}
6884
David Blaikie1d578782011-12-16 16:03:09 +00006885ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6886 SourceLocation OpLoc,
6887 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006888 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006889 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006890 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006891 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6892 return ExprError();
6893
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006894 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6895 false);
David Blaikie1d578782011-12-16 16:03:09 +00006896
6897 TypeLocBuilder TLB;
6898 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6899 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6900 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6901 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6902
6903 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006904 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006905 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006906}
6907
John Wiegley01296292011-04-08 18:41:53 +00006908ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006909 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006910 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006911 if (Method->getParent()->isLambda() &&
6912 Method->getConversionType()->isBlockPointerType()) {
6913 // This is a lambda coversion to block pointer; check if the argument
6914 // is a LambdaExpr.
6915 Expr *SubE = E;
6916 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6917 if (CE && CE->getCastKind() == CK_NoOp)
6918 SubE = CE->getSubExpr();
6919 SubE = SubE->IgnoreParens();
6920 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6921 SubE = BE->getSubExpr();
6922 if (isa<LambdaExpr>(SubE)) {
6923 // For the conversion to block pointer on a lambda expression, we
6924 // construct a special BlockLiteral instead; this doesn't really make
6925 // a difference in ARC, but outside of ARC the resulting block literal
6926 // follows the normal lifetime rules for block literals instead of being
6927 // autoreleased.
6928 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00006929 PushExpressionEvaluationContext(
6930 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006931 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6932 E->getExprLoc(),
6933 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006934 PopExpressionEvaluationContext();
6935
Eli Friedman98b01ed2012-03-01 04:01:32 +00006936 if (Exp.isInvalid())
6937 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6938 return Exp;
6939 }
6940 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006941
Craig Topperc3ec1492014-05-26 06:22:03 +00006942 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006943 FoundDecl, Method);
6944 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006945 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006946
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006947 MemberExpr *ME = new (Context) MemberExpr(
6948 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6949 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006950 if (HadMultipleCandidates)
6951 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006952 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006953
Alp Toker314cc812014-01-25 16:55:45 +00006954 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006955 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6956 ResultType = ResultType.getNonLValueExprType(Context);
6957
Douglas Gregor27381f32009-11-23 12:27:39 +00006958 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006959 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006960 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006961
6962 if (CheckFunctionCall(Method, CE,
6963 Method->getType()->castAs<FunctionProtoType>()))
6964 return ExprError();
6965
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006966 return CE;
6967}
6968
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006969ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6970 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006971 // If the operand is an unresolved lookup expression, the expression is ill-
6972 // formed per [over.over]p1, because overloaded function names cannot be used
6973 // without arguments except in explicit contexts.
6974 ExprResult R = CheckPlaceholderExpr(Operand);
6975 if (R.isInvalid())
6976 return R;
6977
6978 // The operand may have been modified when checking the placeholder type.
6979 Operand = R.get();
6980
Richard Smith51ec0cf2017-02-21 01:17:38 +00006981 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006982 // The expression operand for noexcept is in an unevaluated expression
6983 // context, so side effects could result in unintended consequences.
6984 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6985 }
6986
Richard Smithf623c962012-04-17 00:58:00 +00006987 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006988 return new (Context)
6989 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006990}
6991
6992ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6993 Expr *Operand, SourceLocation RParen) {
6994 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006995}
6996
Eli Friedmanf798f652012-05-24 22:04:19 +00006997static bool IsSpecialDiscardedValue(Expr *E) {
6998 // In C++11, discarded-value expressions of a certain form are special,
6999 // according to [expr]p10:
7000 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7001 // expression is an lvalue of volatile-qualified type and it has
7002 // one of the following forms:
7003 E = E->IgnoreParens();
7004
Eli Friedmanc49c2262012-05-24 22:36:31 +00007005 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007006 if (isa<DeclRefExpr>(E))
7007 return true;
7008
Eli Friedmanc49c2262012-05-24 22:36:31 +00007009 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007010 if (isa<ArraySubscriptExpr>(E))
7011 return true;
7012
Eli Friedmanc49c2262012-05-24 22:36:31 +00007013 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007014 if (isa<MemberExpr>(E))
7015 return true;
7016
Eli Friedmanc49c2262012-05-24 22:36:31 +00007017 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007018 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7019 if (UO->getOpcode() == UO_Deref)
7020 return true;
7021
7022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007023 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007024 if (BO->isPtrMemOp())
7025 return true;
7026
Eli Friedmanc49c2262012-05-24 22:36:31 +00007027 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007028 if (BO->getOpcode() == BO_Comma)
7029 return IsSpecialDiscardedValue(BO->getRHS());
7030 }
7031
Eli Friedmanc49c2262012-05-24 22:36:31 +00007032 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007033 // operands are one of the above, or
7034 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7035 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7036 IsSpecialDiscardedValue(CO->getFalseExpr());
7037 // The related edge case of "*x ?: *x".
7038 if (BinaryConditionalOperator *BCO =
7039 dyn_cast<BinaryConditionalOperator>(E)) {
7040 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7041 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7042 IsSpecialDiscardedValue(BCO->getFalseExpr());
7043 }
7044
7045 // Objective-C++ extensions to the rule.
7046 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7047 return true;
7048
7049 return false;
7050}
7051
John McCall34376a62010-12-04 03:47:34 +00007052/// Perform the conversions required for an expression used in a
7053/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007054ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007055 if (E->hasPlaceholderType()) {
7056 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007057 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007058 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007059 }
7060
John McCallfee942d2010-12-02 02:07:15 +00007061 // C99 6.3.2.1:
7062 // [Except in specific positions,] an lvalue that does not have
7063 // array type is converted to the value stored in the
7064 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007065 if (E->isRValue()) {
7066 // In C, function designators (i.e. expressions of function type)
7067 // are r-values, but we still want to do function-to-pointer decay
7068 // on them. This is both technically correct and convenient for
7069 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007070 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007071 return DefaultFunctionArrayConversion(E);
7072
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007073 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007074 }
John McCallfee942d2010-12-02 02:07:15 +00007075
Eli Friedmanf798f652012-05-24 22:04:19 +00007076 if (getLangOpts().CPlusPlus) {
7077 // The C++11 standard defines the notion of a discarded-value expression;
7078 // normally, we don't need to do anything to handle it, but if it is a
7079 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7080 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007081 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007082 E->getType().isVolatileQualified() &&
7083 IsSpecialDiscardedValue(E)) {
7084 ExprResult Res = DefaultLvalueConversion(E);
7085 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007086 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007087 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007088 }
Richard Smith122f88d2016-12-06 23:52:28 +00007089
7090 // C++1z:
7091 // If the expression is a prvalue after this optional conversion, the
7092 // temporary materialization conversion is applied.
7093 //
7094 // We skip this step: IR generation is able to synthesize the storage for
7095 // itself in the aggregate case, and adding the extra node to the AST is
7096 // just clutter.
7097 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7098 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007099 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007100 }
John McCall34376a62010-12-04 03:47:34 +00007101
7102 // GCC seems to also exclude expressions of incomplete enum type.
7103 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7104 if (!T->getDecl()->isComplete()) {
7105 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007106 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007107 return E;
John McCall34376a62010-12-04 03:47:34 +00007108 }
7109 }
7110
John Wiegley01296292011-04-08 18:41:53 +00007111 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7112 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007113 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007114 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007115
John McCallca61b652010-12-04 12:29:11 +00007116 if (!E->getType()->isVoidType())
7117 RequireCompleteType(E->getExprLoc(), E->getType(),
7118 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007119 return E;
John McCall34376a62010-12-04 03:47:34 +00007120}
7121
Faisal Valia17d19f2013-11-07 05:17:06 +00007122// If we can unambiguously determine whether Var can never be used
7123// in a constant expression, return true.
7124// - if the variable and its initializer are non-dependent, then
7125// we can unambiguously check if the variable is a constant expression.
7126// - if the initializer is not value dependent - we can determine whether
7127// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007128// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007129// never be a constant expression.
7130// - FXIME: if the initializer is dependent, we can still do some analysis and
7131// identify certain cases unambiguously as non-const by using a Visitor:
7132// - such as those that involve odr-use of a ParmVarDecl, involve a new
7133// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007134static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007135 ASTContext &Context) {
7136 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007137 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007138
7139 // If there is no initializer - this can not be a constant expression.
7140 if (!Var->getAnyInitializer(DefVD)) return true;
7141 assert(DefVD);
7142 if (DefVD->isWeak()) return false;
7143 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007144
Faisal Valia17d19f2013-11-07 05:17:06 +00007145 Expr *Init = cast<Expr>(Eval->Value);
7146
7147 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007148 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7149 // of value-dependent expressions, and use it here to determine whether the
7150 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007151 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007152 }
7153
Simon Pilgrim75c26882016-09-30 14:25:09 +00007154 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007155}
7156
Simon Pilgrim75c26882016-09-30 14:25:09 +00007157/// \brief Check if the current lambda has any potential captures
7158/// that must be captured by any of its enclosing lambdas that are ready to
7159/// capture. If there is a lambda that can capture a nested
7160/// potential-capture, go ahead and do so. Also, check to see if any
7161/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007162/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007163
Faisal Valiab3d6462013-12-07 20:22:44 +00007164static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7165 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7166
Simon Pilgrim75c26882016-09-30 14:25:09 +00007167 assert(!S.isUnevaluatedContext());
7168 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007169#ifndef NDEBUG
7170 DeclContext *DC = S.CurContext;
7171 while (DC && isa<CapturedDecl>(DC))
7172 DC = DC->getParent();
7173 assert(
7174 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007175 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007176#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007177
7178 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7179
Faisal Valiab3d6462013-12-07 20:22:44 +00007180 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007181 // lambda (within a generic outer lambda), must be captured by an
7182 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007183 const unsigned NumPotentialCaptures =
7184 CurrentLSI->getNumPotentialVariableCaptures();
7185 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007186 Expr *VarExpr = nullptr;
7187 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007188 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007189 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007190 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007191 // need to check enclosing lambda's for speculative captures.
7192 // For e.g.:
7193 // Even though 'x' is not odr-used, it should be captured.
7194 // int test() {
7195 // const int x = 10;
7196 // auto L = [=](auto a) {
7197 // (void) +x + a;
7198 // };
7199 // }
7200 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007201 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007202 continue;
7203
7204 // If we have a capture-capable lambda for the variable, go ahead and
7205 // capture the variable in that lambda (and all its enclosing lambdas).
7206 if (const Optional<unsigned> Index =
7207 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007208 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007209 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7210 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7211 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007212 }
7213 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007214 VariableCanNeverBeAConstantExpression(Var, S.Context);
7215 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7216 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007217 // can not be used in a constant expression - which means
7218 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007219 // capture violation early, if the variable is un-captureable.
7220 // This is purely for diagnosing errors early. Otherwise, this
7221 // error would get diagnosed when the lambda becomes capture ready.
7222 QualType CaptureType, DeclRefType;
7223 SourceLocation ExprLoc = VarExpr->getExprLoc();
7224 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007225 /*EllipsisLoc*/ SourceLocation(),
7226 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007227 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007228 // We will never be able to capture this variable, and we need
7229 // to be able to in any and all instantiations, so diagnose it.
7230 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007231 /*EllipsisLoc*/ SourceLocation(),
7232 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007233 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007234 }
7235 }
7236 }
7237
Faisal Valiab3d6462013-12-07 20:22:44 +00007238 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007239 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007240 // If we have a capture-capable lambda for 'this', go ahead and capture
7241 // 'this' in that lambda (and all its enclosing lambdas).
7242 if (const Optional<unsigned> Index =
7243 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007244 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007245 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7246 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7247 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7248 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007249 }
7250 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007251
7252 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007253 CurrentLSI->clearPotentialCaptures();
7254}
7255
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007256static ExprResult attemptRecovery(Sema &SemaRef,
7257 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007258 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007259 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7260 Consumer.getLookupResult().getLookupKind());
7261 const CXXScopeSpec *SS = Consumer.getSS();
7262 CXXScopeSpec NewSS;
7263
7264 // Use an approprate CXXScopeSpec for building the expr.
7265 if (auto *NNS = TC.getCorrectionSpecifier())
7266 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7267 else if (SS && !TC.WillReplaceSpecifier())
7268 NewSS = *SS;
7269
Richard Smithde6d6c42015-12-29 19:43:10 +00007270 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007271 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007272 R.addDecl(ND);
7273 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007274 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007275 CXXRecordDecl *Record = nullptr;
7276 if (auto *NNS = TC.getCorrectionSpecifier())
7277 Record = NNS->getAsType()->getAsCXXRecordDecl();
7278 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007279 Record =
7280 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7281 if (Record)
7282 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007283
7284 // Detect and handle the case where the decl might be an implicit
7285 // member.
7286 bool MightBeImplicitMember;
7287 if (!Consumer.isAddressOfOperand())
7288 MightBeImplicitMember = true;
7289 else if (!NewSS.isEmpty())
7290 MightBeImplicitMember = false;
7291 else if (R.isOverloadedResult())
7292 MightBeImplicitMember = false;
7293 else if (R.isUnresolvableResult())
7294 MightBeImplicitMember = true;
7295 else
7296 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7297 isa<IndirectFieldDecl>(ND) ||
7298 isa<MSPropertyDecl>(ND);
7299
7300 if (MightBeImplicitMember)
7301 return SemaRef.BuildPossibleImplicitMemberExpr(
7302 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007303 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007304 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7305 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7306 Ivar->getIdentifier());
7307 }
7308 }
7309
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007310 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7311 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007312}
7313
Kaelyn Takata6c759512014-10-27 18:07:37 +00007314namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007315class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7316 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7317
7318public:
7319 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7320 : TypoExprs(TypoExprs) {}
7321 bool VisitTypoExpr(TypoExpr *TE) {
7322 TypoExprs.insert(TE);
7323 return true;
7324 }
7325};
7326
Kaelyn Takata6c759512014-10-27 18:07:37 +00007327class TransformTypos : public TreeTransform<TransformTypos> {
7328 typedef TreeTransform<TransformTypos> BaseTransform;
7329
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007330 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7331 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007332 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007333 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007334 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007335 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007336
7337 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7338 /// If the TypoExprs were successfully corrected, then the diagnostics should
7339 /// suggest the corrections. Otherwise the diagnostics will not suggest
7340 /// anything (having been passed an empty TypoCorrection).
7341 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007342 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007343 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007344 if (State.DiagHandler) {
7345 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7346 ExprResult Replacement = TransformCache[TE];
7347
7348 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7349 // TypoCorrection, replacing the existing decls. This ensures the right
7350 // NamedDecl is used in diagnostics e.g. in the case where overload
7351 // resolution was used to select one from several possible decls that
7352 // had been stored in the TypoCorrection.
7353 if (auto *ND = getDeclFromExpr(
7354 Replacement.isInvalid() ? nullptr : Replacement.get()))
7355 TC.setCorrectionDecl(ND);
7356
7357 State.DiagHandler(TC);
7358 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007359 SemaRef.clearDelayedTypo(TE);
7360 }
7361 }
7362
7363 /// \brief If corrections for the first TypoExpr have been exhausted for a
7364 /// given combination of the other TypoExprs, retry those corrections against
7365 /// the next combination of substitutions for the other TypoExprs by advancing
7366 /// to the next potential correction of the second TypoExpr. For the second
7367 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7368 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7369 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7370 /// TransformCache). Returns true if there is still any untried combinations
7371 /// of corrections.
7372 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7373 for (auto TE : TypoExprs) {
7374 auto &State = SemaRef.getTypoExprState(TE);
7375 TransformCache.erase(TE);
7376 if (!State.Consumer->finished())
7377 return true;
7378 State.Consumer->resetCorrectionStream();
7379 }
7380 return false;
7381 }
7382
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007383 NamedDecl *getDeclFromExpr(Expr *E) {
7384 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7385 E = OverloadResolution[OE];
7386
7387 if (!E)
7388 return nullptr;
7389 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007390 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007391 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007392 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007393 // FIXME: Add any other expr types that could be be seen by the delayed typo
7394 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007395 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007396 return nullptr;
7397 }
7398
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007399 ExprResult TryTransform(Expr *E) {
7400 Sema::SFINAETrap Trap(SemaRef);
7401 ExprResult Res = TransformExpr(E);
7402 if (Trap.hasErrorOccurred() || Res.isInvalid())
7403 return ExprError();
7404
7405 return ExprFilter(Res.get());
7406 }
7407
Kaelyn Takata6c759512014-10-27 18:07:37 +00007408public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007409 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7410 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007411
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007412 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7413 MultiExprArg Args,
7414 SourceLocation RParenLoc,
7415 Expr *ExecConfig = nullptr) {
7416 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7417 RParenLoc, ExecConfig);
7418 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007419 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007420 Expr *ResultCall = Result.get();
7421 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7422 ResultCall = BE->getSubExpr();
7423 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7424 OverloadResolution[OE] = CE->getCallee();
7425 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007426 }
7427 return Result;
7428 }
7429
Kaelyn Takata6c759512014-10-27 18:07:37 +00007430 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7431
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007432 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7433
Kaelyn Takata6c759512014-10-27 18:07:37 +00007434 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007435 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007436 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007437 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007438
Kaelyn Takata6c759512014-10-27 18:07:37 +00007439 // Exit if either the transform was valid or if there were no TypoExprs
7440 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007441 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007442 !CheckAndAdvanceTypoExprCorrectionStreams())
7443 break;
7444 }
7445
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007446 // Ensure none of the TypoExprs have multiple typo correction candidates
7447 // with the same edit length that pass all the checks and filters.
7448 // TODO: Properly handle various permutations of possible corrections when
7449 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007450 // Also, disable typo correction while attempting the transform when
7451 // handling potentially ambiguous typo corrections as any new TypoExprs will
7452 // have been introduced by the application of one of the correction
7453 // candidates and add little to no value if corrected.
7454 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007455 while (!AmbiguousTypoExprs.empty()) {
7456 auto TE = AmbiguousTypoExprs.back();
7457 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007458 auto &State = SemaRef.getTypoExprState(TE);
7459 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007460 TransformCache.erase(TE);
7461 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007462 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007463 TransformCache.erase(TE);
7464 Res = ExprError();
7465 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007466 }
7467 AmbiguousTypoExprs.remove(TE);
7468 State.Consumer->restoreSavedPosition();
7469 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007470 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007471 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007472
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007473 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007474 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007475 FindTypoExprs(TypoExprs).TraverseStmt(E);
7476
Kaelyn Takata6c759512014-10-27 18:07:37 +00007477 EmitAllDiagnostics();
7478
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007479 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007480 }
7481
7482 ExprResult TransformTypoExpr(TypoExpr *E) {
7483 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7484 // cached transformation result if there is one and the TypoExpr isn't the
7485 // first one that was encountered.
7486 auto &CacheEntry = TransformCache[E];
7487 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7488 return CacheEntry;
7489 }
7490
7491 auto &State = SemaRef.getTypoExprState(E);
7492 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7493
7494 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7495 // typo correction and return it.
7496 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007497 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007498 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007499 // FIXME: If we would typo-correct to an invalid declaration, it's
7500 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007501 ExprResult NE = State.RecoveryHandler ?
7502 State.RecoveryHandler(SemaRef, E, TC) :
7503 attemptRecovery(SemaRef, *State.Consumer, TC);
7504 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007505 // Check whether there may be a second viable correction with the same
7506 // edit distance; if so, remember this TypoExpr may have an ambiguous
7507 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007508 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007509 if ((Next = State.Consumer->peekNextCorrection()) &&
7510 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7511 AmbiguousTypoExprs.insert(E);
7512 } else {
7513 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007514 }
7515 assert(!NE.isUnset() &&
7516 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007517 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007518 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007519 }
7520 return CacheEntry = ExprError();
7521 }
7522};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007523}
Faisal Valia17d19f2013-11-07 05:17:06 +00007524
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007525ExprResult
7526Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7527 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007528 // If the current evaluation context indicates there are uncorrected typos
7529 // and the current expression isn't guaranteed to not have typos, try to
7530 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007531 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007532 (E->isTypeDependent() || E->isValueDependent() ||
7533 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007534 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7535 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7536 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007537 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007538 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007539 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007540 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007541 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007542 ExprEvalContexts.back().NumTypos -= TyposResolved;
7543 return Result;
7544 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007545 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007546 }
7547 return E;
7548}
7549
Richard Smith945f8d32013-01-14 22:39:08 +00007550ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007551 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007552 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007553 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007554 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007555
7556 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007557 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007558
7559 // If we are an init-expression in a lambdas init-capture, we should not
7560 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007561 // containing full-expression is done).
7562 // template<class ... Ts> void test(Ts ... t) {
7563 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7564 // return a;
7565 // }() ...);
7566 // }
7567 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7568 // when we parse the lambda introducer, and teach capturing (but not
7569 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7570 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7571 // lambda where we've entered the introducer but not the body, or represent a
7572 // lambda where we've entered the body, depending on where the
7573 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007574 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007575 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007576 return ExprError();
7577
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007578 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007579 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007580 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007581 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007582 if (FullExpr.isInvalid())
7583 return ExprError();
7584 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007585
Richard Smith945f8d32013-01-14 22:39:08 +00007586 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007587 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007588 if (FullExpr.isInvalid())
7589 return ExprError();
7590
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007591 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007592 if (FullExpr.isInvalid())
7593 return ExprError();
7594 }
John Wiegley01296292011-04-08 18:41:53 +00007595
Kaelyn Takata49d84322014-11-11 23:26:56 +00007596 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7597 if (FullExpr.isInvalid())
7598 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007599
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007600 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007601
Simon Pilgrim75c26882016-09-30 14:25:09 +00007602 // At the end of this full expression (which could be a deeply nested
7603 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007604 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007605 // Consider the following code:
7606 // void f(int, int);
7607 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007608 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007609 // const int x = 10, y = 20;
7610 // auto L = [=](auto a) {
7611 // auto M = [=](auto b) {
7612 // f(x, b); <-- requires x to be captured by L and M
7613 // f(y, a); <-- requires y to be captured by L, but not all Ms
7614 // };
7615 // };
7616 // }
7617
Simon Pilgrim75c26882016-09-30 14:25:09 +00007618 // FIXME: Also consider what happens for something like this that involves
7619 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007620 // void f() {
7621 // const int n = 0;
7622 // auto L = [&](auto a) {
7623 // +n + ({ 0; a; });
7624 // };
7625 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007626 //
7627 // Here, we see +n, and then the full-expression 0; ends, so we don't
7628 // capture n (and instead remove it from our list of potential captures),
7629 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007630 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007631
Alexey Bataev31939e32016-11-11 12:36:20 +00007632 LambdaScopeInfo *const CurrentLSI =
7633 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007634 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007635 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007636 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007637 // By ensuring we are in the context of a lambda's call operator
7638 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007639 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007640 // PR, a proper fix would entail :
7641 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007642 // - Add to Sema an integer holding the smallest (outermost) scope
7643 // index that we are *lexically* within, and save/restore/set to
7644 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007645 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007646 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007647 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007648 DeclContext *DC = CurContext;
7649 while (DC && isa<CapturedDecl>(DC))
7650 DC = DC->getParent();
7651 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007652 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007653 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007654 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7655 *this);
John McCall5d413782010-12-06 08:20:24 +00007656 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007657}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007658
7659StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7660 if (!FullStmt) return StmtError();
7661
John McCall5d413782010-12-06 08:20:24 +00007662 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007663}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007664
Simon Pilgrim75c26882016-09-30 14:25:09 +00007665Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007666Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7667 CXXScopeSpec &SS,
7668 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007669 DeclarationName TargetName = TargetNameInfo.getName();
7670 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007671 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007672
Douglas Gregor43edb322011-10-24 22:31:10 +00007673 // If the name itself is dependent, then the result is dependent.
7674 if (TargetName.isDependentName())
7675 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007676
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007677 // Do the redeclaration lookup in the current scope.
7678 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7679 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007680 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007681 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007682
Douglas Gregor43edb322011-10-24 22:31:10 +00007683 switch (R.getResultKind()) {
7684 case LookupResult::Found:
7685 case LookupResult::FoundOverloaded:
7686 case LookupResult::FoundUnresolvedValue:
7687 case LookupResult::Ambiguous:
7688 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007689
Douglas Gregor43edb322011-10-24 22:31:10 +00007690 case LookupResult::NotFound:
7691 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007692
Douglas Gregor43edb322011-10-24 22:31:10 +00007693 case LookupResult::NotFoundInCurrentInstantiation:
7694 return IER_Dependent;
7695 }
David Blaikie8a40f702012-01-17 06:56:22 +00007696
7697 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007698}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007699
Simon Pilgrim75c26882016-09-30 14:25:09 +00007700Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007701Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7702 bool IsIfExists, CXXScopeSpec &SS,
7703 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007704 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007705
Richard Smith151c4562016-12-20 21:35:28 +00007706 // Check for an unexpanded parameter pack.
7707 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7708 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7709 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007710 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007711
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007712 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7713}