blob: 1185dacc227ba66c4b6d53581957b2904d04ed5d [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"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000295
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
Richard Smithef2cd8f2017-02-08 20:39:08 +0000326ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
327 ParsedType ObjectType) {
328 if (DS.getTypeSpecType() == DeclSpec::TST_error)
329 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000330
Richard Smithef2cd8f2017-02-08 20:39:08 +0000331 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
332 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
333 return nullptr;
334 }
335
336 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
337 "unexpected type in getDestructorType");
338 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
339
340 // If we know the type of the object, check that the correct destructor
341 // type was named now; we can give better diagnostics this way.
342 QualType SearchType = GetTypeFromParser(ObjectType);
343 if (!SearchType.isNull() && !SearchType->isDependentType() &&
344 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000345 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
346 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000347 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000348 }
349
350 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000351}
352
Richard Smithd091dc12013-12-05 00:58:33 +0000353bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
354 const UnqualifiedId &Name) {
355 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
356
357 if (!SS.isValid())
358 return false;
359
360 switch (SS.getScopeRep()->getKind()) {
361 case NestedNameSpecifier::Identifier:
362 case NestedNameSpecifier::TypeSpec:
363 case NestedNameSpecifier::TypeSpecWithTemplate:
364 // Per C++11 [over.literal]p2, literal operators can only be declared at
365 // namespace scope. Therefore, this unqualified-id cannot name anything.
366 // Reject it early, because we have no AST representation for this in the
367 // case where the scope is dependent.
368 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
369 << SS.getScopeRep();
370 return true;
371
372 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000373 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000374 case NestedNameSpecifier::Namespace:
375 case NestedNameSpecifier::NamespaceAlias:
376 return false;
377 }
378
379 llvm_unreachable("unknown nested name specifier kind");
380}
381
Douglas Gregor9da64192010-04-26 22:37:10 +0000382/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000383ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000384 SourceLocation TypeidLoc,
385 TypeSourceInfo *Operand,
386 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000387 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000389 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000391 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000392 Qualifiers Quals;
393 QualType T
394 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
395 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000396 if (T->getAs<RecordType>() &&
397 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
398 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
David Majnemer6f3150a2014-11-21 21:09:12 +0000400 if (T->isVariablyModifiedType())
401 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
402
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000403 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
404 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000405}
406
407/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000408ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000409 SourceLocation TypeidLoc,
410 Expr *E,
411 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000412 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000413 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000414 if (E->getType()->isPlaceholderType()) {
415 ExprResult result = CheckPlaceholderExpr(E);
416 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000417 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000418 }
419
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 QualType T = E->getType();
421 if (const RecordType *RecordT = T->getAs<RecordType>()) {
422 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
423 // C++ [expr.typeid]p3:
424 // [...] If the type of the expression is a class type, the class
425 // shall be completely-defined.
426 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
427 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor9da64192010-04-26 22:37:10 +0000429 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000430 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000431 // polymorphic class type [...] [the] expression is an unevaluated
432 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000433 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000434 // The subexpression is potentially evaluated; switch the context
435 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000436 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000437 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000438 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000439
440 // We require a vtable to query the type at run time.
441 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000442 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000443 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor9da64192010-04-26 22:37:10 +0000446 // C++ [expr.typeid]p4:
447 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448 // cv-qualified type, the result of the typeid expression refers to a
449 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000451 Qualifiers Quals;
452 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
453 if (!Context.hasSameType(T, UnqualT)) {
454 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000455 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000456 }
457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458
David Majnemer6f3150a2014-11-21 21:09:12 +0000459 if (E->getType()->isVariablyModifiedType())
460 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
461 << E->getType());
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000462 else if (ActiveTemplateInstantiations.empty() &&
463 E->HasSideEffects(Context, WasEvaluated)) {
464 // The expression operand for typeid is in an unevaluated expression
465 // context, so side effects could result in unintended consequences.
466 Diag(E->getExprLoc(), WasEvaluated
467 ? diag::warn_side_effects_typeid
468 : diag::warn_side_effects_unevaluated_context);
469 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000470
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000471 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
472 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000473}
474
475/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000476ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000477Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
478 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000479 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000480 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000481 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000482
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl) {
484 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
485 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
486 LookupQualifiedName(R, getStdNamespace());
487 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000488 // Microsoft's typeinfo doesn't have type_info in std but in the global
489 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000490 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000491 LookupQualifiedName(R, Context.getTranslationUnitDecl());
492 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
493 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000494 if (!CXXTypeInfoDecl)
495 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
Nico Weber1b7f39d2012-05-20 01:27:21 +0000498 if (!getLangOpts().RTTI) {
499 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
500 }
501
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000502 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 if (isType) {
505 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000506 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000507 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
508 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000509 if (T.isNull())
510 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
Douglas Gregor9da64192010-04-26 22:37:10 +0000512 if (!TInfo)
513 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000514
Douglas Gregor9da64192010-04-26 22:37:10 +0000515 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000519 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000520}
521
David Majnemer1dbc7a72016-03-27 04:46:07 +0000522/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
523/// a single GUID.
524static void
525getUuidAttrOfType(Sema &SemaRef, QualType QT,
526 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
527 // Optionally remove one level of pointer, reference or array indirection.
528 const Type *Ty = QT.getTypePtr();
529 if (QT->isPointerType() || QT->isReferenceType())
530 Ty = QT->getPointeeType().getTypePtr();
531 else if (QT->isArrayType())
532 Ty = Ty->getBaseElementTypeUnsafe();
533
Reid Klecknere516eab2016-12-13 18:58:09 +0000534 const auto *TD = Ty->getAsTagDecl();
535 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000536 return;
537
Reid Klecknere516eab2016-12-13 18:58:09 +0000538 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000539 UuidAttrs.insert(Uuid);
540 return;
541 }
542
543 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000544 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000545 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
546 for (const TemplateArgument &TA : TAL.asArray()) {
547 const UuidAttr *UuidForTA = nullptr;
548 if (TA.getKind() == TemplateArgument::Type)
549 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
550 else if (TA.getKind() == TemplateArgument::Declaration)
551 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
552
553 if (UuidForTA)
554 UuidAttrs.insert(UuidForTA);
555 }
556 }
557}
558
Francois Pichet9f4f2072010-09-08 12:20:18 +0000559/// \brief Build a Microsoft __uuidof expression with a type operand.
560ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
561 SourceLocation TypeidLoc,
562 TypeSourceInfo *Operand,
563 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000564 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000565 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000566 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
567 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
568 if (UuidAttrs.empty())
569 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
570 if (UuidAttrs.size() > 1)
571 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000572 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
David Majnemer2041b462016-03-28 03:19:50 +0000575 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000576 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000577}
578
579/// \brief Build a Microsoft __uuidof expression with an expression operand.
580ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
581 SourceLocation TypeidLoc,
582 Expr *E,
583 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000584 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000585 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000586 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
587 UuidStr = "00000000-0000-0000-0000-000000000000";
588 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000589 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
590 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
591 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000592 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000593 if (UuidAttrs.size() > 1)
594 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000595 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000596 }
Francois Pichetb7577652010-12-27 01:32:00 +0000597 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000598
David Majnemer2041b462016-03-28 03:19:50 +0000599 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000600 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000601}
602
603/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
604ExprResult
605Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
606 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000608 if (!MSVCGuidDecl) {
609 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
610 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
611 LookupQualifiedName(R, Context.getTranslationUnitDecl());
612 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
613 if (!MSVCGuidDecl)
614 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615 }
616
Francois Pichet9f4f2072010-09-08 12:20:18 +0000617 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Francois Pichet9f4f2072010-09-08 12:20:18 +0000619 if (isType) {
620 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000621 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000622 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
623 &TInfo);
624 if (T.isNull())
625 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Francois Pichet9f4f2072010-09-08 12:20:18 +0000627 if (!TInfo)
628 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
629
630 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
631 }
632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000634 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
635}
636
Steve Naroff66356bd2007-09-16 14:56:35 +0000637/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000638ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000639Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000640 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000641 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000642 return new (Context)
643 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000644}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000645
Sebastian Redl576fd422009-05-10 18:38:11 +0000646/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000647ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000648Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000649 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000650}
651
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000652/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000653ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000654Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
655 bool IsThrownVarInScope = false;
656 if (Ex) {
657 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000658 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000659 // copy/move construction of a class object [...]
660 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000661 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000662 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000663 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000664 // innermost enclosing try-block (if there is one), the copy/move
665 // operation from the operand to the exception object (15.1) can be
666 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000667 // exception object
668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
669 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
670 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
671 for( ; S; S = S->getParent()) {
672 if (S->isDeclScope(Var)) {
673 IsThrownVarInScope = true;
674 break;
675 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000676
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000677 if (S->getFlags() &
678 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
679 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
680 Scope::TryScope))
681 break;
682 }
683 }
684 }
685 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000686
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000687 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
688}
689
Simon Pilgrim75c26882016-09-30 14:25:09 +0000690ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000691 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000692 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000693 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000694 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000695 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000696
Justin Lebar2a8db342016-09-28 22:45:54 +0000697 // Exceptions aren't allowed in CUDA device code.
698 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000699 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
700 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000701
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000702 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
703 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
704
John Wiegley01296292011-04-08 18:41:53 +0000705 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000706 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
707 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000708 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000709
710 // Initialize the exception result. This implicitly weeds out
711 // abstract types or types with inaccessible copy constructors.
712
713 // C++0x [class.copymove]p31:
714 // When certain criteria are met, an implementation is allowed to omit the
715 // copy/move construction of a class object [...]
716 //
717 // - in a throw-expression, when the operand is the name of a
718 // non-volatile automatic object (other than a function or
719 // catch-clause
720 // parameter) whose scope does not extend beyond the end of the
721 // innermost enclosing try-block (if there is one), the copy/move
722 // operation from the operand to the exception object (15.1) can be
723 // omitted by constructing the automatic object directly into the
724 // exception object
725 const VarDecl *NRVOVariable = nullptr;
726 if (IsThrownVarInScope)
727 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
728
729 InitializedEntity Entity = InitializedEntity::InitializeException(
730 OpLoc, ExceptionObjectTy,
731 /*NRVO=*/NRVOVariable != nullptr);
732 ExprResult Res = PerformMoveOrCopyInitialization(
733 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
734 if (Res.isInvalid())
735 return ExprError();
736 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000737 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000738
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000739 return new (Context)
740 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000741}
742
David Majnemere7a818f2015-03-06 18:53:55 +0000743static void
744collectPublicBases(CXXRecordDecl *RD,
745 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
746 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
747 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
748 bool ParentIsPublic) {
749 for (const CXXBaseSpecifier &BS : RD->bases()) {
750 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
751 bool NewSubobject;
752 // Virtual bases constitute the same subobject. Non-virtual bases are
753 // always distinct subobjects.
754 if (BS.isVirtual())
755 NewSubobject = VBases.insert(BaseDecl).second;
756 else
757 NewSubobject = true;
758
759 if (NewSubobject)
760 ++SubobjectsSeen[BaseDecl];
761
762 // Only add subobjects which have public access throughout the entire chain.
763 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
764 if (PublicPath)
765 PublicSubobjectsSeen.insert(BaseDecl);
766
767 // Recurse on to each base subobject.
768 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
769 PublicPath);
770 }
771}
772
773static void getUnambiguousPublicSubobjects(
774 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
775 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
776 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
777 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
778 SubobjectsSeen[RD] = 1;
779 PublicSubobjectsSeen.insert(RD);
780 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
781 /*ParentIsPublic=*/true);
782
783 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
784 // Skip ambiguous objects.
785 if (SubobjectsSeen[PublicSubobject] > 1)
786 continue;
787
788 Objects.push_back(PublicSubobject);
789 }
790}
791
Sebastian Redl4de47b42009-04-27 20:27:31 +0000792/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000793bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
794 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000795 // If the type of the exception would be an incomplete type or a pointer
796 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000797 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000798 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000799 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000800 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000801 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802 }
803 if (!isPointer || !Ty->isVoidType()) {
804 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000805 isPointer ? diag::err_throw_incomplete_ptr
806 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000807 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000808 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000809
David Majnemerd09a51c2015-03-03 01:50:05 +0000810 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000811 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000812 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000813 }
814
Eli Friedman91a3d272010-06-03 20:39:03 +0000815 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000816 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
817 if (!RD)
818 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000819
Douglas Gregor88d292c2010-05-13 16:44:06 +0000820 // If we are throwing a polymorphic class type or pointer thereof,
821 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000822 MarkVTableUsed(ThrowLoc, RD);
823
Eli Friedman36ebbec2010-10-12 20:32:36 +0000824 // If a pointer is thrown, the referenced object will not be destroyed.
825 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000826 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000827
Richard Smitheec915d62012-02-18 04:13:32 +0000828 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000829 if (!RD->hasIrrelevantDestructor()) {
830 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
831 MarkFunctionReferenced(E->getExprLoc(), Destructor);
832 CheckDestructorAccess(E->getExprLoc(), Destructor,
833 PDiag(diag::err_access_dtor_exception) << Ty);
834 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000835 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000836 }
837 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000838
David Majnemerdfa6d202015-03-11 18:36:39 +0000839 // The MSVC ABI creates a list of all types which can catch the exception
840 // object. This list also references the appropriate copy constructor to call
841 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000843 // We are only interested in the public, unambiguous bases contained within
844 // the exception object. Bases which are ambiguous or otherwise
845 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000846 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
847 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000848
David Majnemere7a818f2015-03-06 18:53:55 +0000849 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000850 // Attempt to lookup the copy constructor. Various pieces of machinery
851 // will spring into action, like template instantiation, which means this
852 // cannot be a simple walk of the class's decls. Instead, we must perform
853 // lookup and overload resolution.
854 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
855 if (!CD)
856 continue;
857
858 // Mark the constructor referenced as it is used by this throw expression.
859 MarkFunctionReferenced(E->getExprLoc(), CD);
860
861 // Skip this copy constructor if it is trivial, we don't need to record it
862 // in the catchable type data.
863 if (CD->isTrivial())
864 continue;
865
866 // The copy constructor is non-trivial, create a mapping from this class
867 // type to this constructor.
868 // N.B. The selection of copy constructor is not sensitive to this
869 // particular throw-site. Lookup will be performed at the catch-site to
870 // ensure that the copy constructor is, in fact, accessible (via
871 // friendship or any other means).
872 Context.addCopyConstructorForExceptionObject(Subobject, CD);
873
874 // We don't keep the instantiated default argument expressions around so
875 // we must rebuild them here.
876 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000877 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
878 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000879 }
880 }
881 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000882
David Majnemerba3e5ec2015-03-13 18:26:17 +0000883 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000884}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885
Faisal Vali67b04462016-06-11 16:41:54 +0000886static QualType adjustCVQualifiersForCXXThisWithinLambda(
887 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
888 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
889
890 QualType ClassType = ThisTy->getPointeeType();
891 LambdaScopeInfo *CurLSI = nullptr;
892 DeclContext *CurDC = CurSemaContext;
893
894 // Iterate through the stack of lambdas starting from the innermost lambda to
895 // the outermost lambda, checking if '*this' is ever captured by copy - since
896 // that could change the cv-qualifiers of the '*this' object.
897 // The object referred to by '*this' starts out with the cv-qualifiers of its
898 // member function. We then start with the innermost lambda and iterate
899 // outward checking to see if any lambda performs a by-copy capture of '*this'
900 // - and if so, any nested lambda must respect the 'constness' of that
901 // capturing lamdbda's call operator.
902 //
903
904 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
905 // since ScopeInfos are pushed on during parsing and treetransforming. But
906 // since a generic lambda's call operator can be instantiated anywhere (even
907 // end of the TU) we need to be able to examine its enclosing lambdas and so
908 // we use the DeclContext to get a hold of the closure-class and query it for
909 // capture information. The reason we don't just resort to always using the
910 // DeclContext chain is that it is only mature for lambda expressions
911 // enclosing generic lambda's call operators that are being instantiated.
912
913 for (int I = FunctionScopes.size();
914 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
915 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
916 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000917
918 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000919 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000920
Faisal Vali67b04462016-06-11 16:41:54 +0000921 auto C = CurLSI->getCXXThisCapture();
922
923 if (C.isCopyCapture()) {
924 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
925 if (CurLSI->CallOperator->isConst())
926 ClassType.addConst();
927 return ASTCtx.getPointerType(ClassType);
928 }
929 }
930 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
931 // happen during instantiation of generic lambdas)
932 if (isLambdaCallOperator(CurDC)) {
933 assert(CurLSI);
934 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
935 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000936
Faisal Vali67b04462016-06-11 16:41:54 +0000937 auto IsThisCaptured =
938 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
939 IsConst = false;
940 IsByCopy = false;
941 for (auto &&C : Closure->captures()) {
942 if (C.capturesThis()) {
943 if (C.getCaptureKind() == LCK_StarThis)
944 IsByCopy = true;
945 if (Closure->getLambdaCallOperator()->isConst())
946 IsConst = true;
947 return true;
948 }
949 }
950 return false;
951 };
952
953 bool IsByCopyCapture = false;
954 bool IsConstCapture = false;
955 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
956 while (Closure &&
957 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
958 if (IsByCopyCapture) {
959 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
960 if (IsConstCapture)
961 ClassType.addConst();
962 return ASTCtx.getPointerType(ClassType);
963 }
964 Closure = isLambdaCallOperator(Closure->getParent())
965 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
966 : nullptr;
967 }
968 }
969 return ASTCtx.getPointerType(ClassType);
970}
971
Eli Friedman73a04092012-01-07 04:59:52 +0000972QualType Sema::getCurrentThisType() {
973 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000974 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000975
Richard Smith938f40b2011-06-11 17:19:42 +0000976 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
977 if (method && method->isInstance())
978 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000979 }
Faisal Validc6b5962016-03-21 09:25:37 +0000980
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000981 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
982 !ActiveTemplateInstantiations.empty()) {
Faisal Validc6b5962016-03-21 09:25:37 +0000983
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000984 assert(isa<CXXRecordDecl>(DC) &&
985 "Trying to get 'this' type from static method?");
986
987 // This is a lambda call operator that is being instantiated as a default
988 // initializer. DC must point to the enclosing class type, so we can recover
989 // the 'this' type from it.
990
991 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
992 // There are no cv-qualifiers for 'this' within default initializers,
993 // per [expr.prim.general]p4.
994 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +0000995 }
Faisal Vali67b04462016-06-11 16:41:54 +0000996
997 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
998 // might need to be adjusted if the lambda or any of its enclosing lambda's
999 // captures '*this' by copy.
1000 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1001 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1002 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001003 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001004}
1005
Simon Pilgrim75c26882016-09-30 14:25:09 +00001006Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001007 Decl *ContextDecl,
1008 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001009 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001010 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1011{
1012 if (!Enabled || !ContextDecl)
1013 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001014
1015 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001016 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1017 Record = Template->getTemplatedDecl();
1018 else
1019 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001020
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001021 // We care only for CVR qualifiers here, so cut everything else.
1022 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001023 S.CXXThisTypeOverride
1024 = S.Context.getPointerType(
1025 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001026
Douglas Gregor3024f072012-04-16 07:05:22 +00001027 this->Enabled = true;
1028}
1029
1030
1031Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1032 if (Enabled) {
1033 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1034 }
1035}
1036
Faisal Validc6b5962016-03-21 09:25:37 +00001037static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1038 QualType ThisTy, SourceLocation Loc,
1039 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001040
Faisal Vali67b04462016-06-11 16:41:54 +00001041 QualType AdjustedThisTy = ThisTy;
1042 // The type of the corresponding data member (not a 'this' pointer if 'by
1043 // copy').
1044 QualType CaptureThisFieldTy = ThisTy;
1045 if (ByCopy) {
1046 // If we are capturing the object referred to by '*this' by copy, ignore any
1047 // cv qualifiers inherited from the type of the member function for the type
1048 // of the closure-type's corresponding data member and any use of 'this'.
1049 CaptureThisFieldTy = ThisTy->getPointeeType();
1050 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1051 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1052 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001053
Faisal Vali67b04462016-06-11 16:41:54 +00001054 FieldDecl *Field = FieldDecl::Create(
1055 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1056 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1057 ICIS_NoInit);
1058
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001059 Field->setImplicit(true);
1060 Field->setAccess(AS_private);
1061 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001062 Expr *This =
1063 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001064 if (ByCopy) {
1065 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1066 UO_Deref,
1067 This).get();
1068 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001069 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001070 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1071 InitializationSequence Init(S, Entity, InitKind, StarThis);
1072 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1073 if (ER.isInvalid()) return nullptr;
1074 return ER.get();
1075 }
1076 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001077}
1078
Simon Pilgrim75c26882016-09-30 14:25:09 +00001079bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001080 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1081 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001082 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001083 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001084 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001085
Faisal Validc6b5962016-03-21 09:25:37 +00001086 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001087
Faisal Valia17d19f2013-11-07 05:17:06 +00001088 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001089 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001090
Simon Pilgrim75c26882016-09-30 14:25:09 +00001091 // Check that we can capture the *enclosing object* (referred to by '*this')
1092 // by the capturing-entity/closure (lambda/block/etc) at
1093 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1094
1095 // Note: The *enclosing object* can only be captured by-value by a
1096 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001097 // [*this] { ... }.
1098 // Every other capture of the *enclosing object* results in its by-reference
1099 // capture.
1100
1101 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1102 // stack), we can capture the *enclosing object* only if:
1103 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1104 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001105 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001106 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001107 // -- or, there is some enclosing closure 'E' that has already captured the
1108 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001109 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001110 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001111 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001112
1113
Faisal Validc6b5962016-03-21 09:25:37 +00001114 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001115 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001116 if (CapturingScopeInfo *CSI =
1117 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1118 if (CSI->CXXThisCaptureIndex != 0) {
1119 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001120 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001121 break;
1122 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001123 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1124 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1125 // This context can't implicitly capture 'this'; fail out.
1126 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001127 Diag(Loc, diag::err_this_capture)
1128 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001129 return true;
1130 }
Eli Friedman20139d32012-01-11 02:36:31 +00001131 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001132 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001133 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001134 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001135 (Explicit && idx == MaxFunctionScopesIndex)) {
1136 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1137 // iteration through can be an explicit capture, all enclosing closures,
1138 // if any, must perform implicit captures.
1139
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001140 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001141 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001142 continue;
1143 }
Eli Friedman20139d32012-01-11 02:36:31 +00001144 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001145 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001146 Diag(Loc, diag::err_this_capture)
1147 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001148 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001149 }
Eli Friedman73a04092012-01-07 04:59:52 +00001150 break;
1151 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001152 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001153
1154 // If we got here, then the closure at MaxFunctionScopesIndex on the
1155 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1156 // (including implicit by-reference captures in any enclosing closures).
1157
1158 // In the loop below, respect the ByCopy flag only for the closure requesting
1159 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001160 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001161 // implicitly capturing the *enclosing object* by reference (see loop
1162 // above)).
1163 assert((!ByCopy ||
1164 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1165 "Only a lambda can capture the enclosing object (referred to by "
1166 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001167 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1168 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001169 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001170 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001171 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001172 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001173 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001174
Faisal Validc6b5962016-03-21 09:25:37 +00001175 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1176 // For lambda expressions, build a field and an initializing expression,
1177 // and capture the *enclosing object* by copy only if this is the first
1178 // iteration.
1179 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1180 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001181
Faisal Validc6b5962016-03-21 09:25:37 +00001182 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001183 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001184 ThisExpr =
1185 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1186 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001187
Faisal Validc6b5962016-03-21 09:25:37 +00001188 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001189 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001190 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001191 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001192}
1193
Richard Smith938f40b2011-06-11 17:19:42 +00001194ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001195 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1196 /// is a non-lvalue expression whose value is the address of the object for
1197 /// which the function is called.
1198
Douglas Gregor09deffa2011-10-18 16:47:30 +00001199 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001200 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001201
Eli Friedman73a04092012-01-07 04:59:52 +00001202 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001203 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001204}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001205
Douglas Gregor3024f072012-04-16 07:05:22 +00001206bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1207 // If we're outside the body of a member function, then we'll have a specified
1208 // type for 'this'.
1209 if (CXXThisTypeOverride.isNull())
1210 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001211
Douglas Gregor3024f072012-04-16 07:05:22 +00001212 // Determine whether we're looking into a class that's currently being
1213 // defined.
1214 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1215 return Class && Class->isBeingDefined();
1216}
1217
John McCalldadc5752010-08-24 06:29:42 +00001218ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001219Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001220 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001221 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001222 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001223 if (!TypeRep)
1224 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
John McCall97513962010-01-15 18:39:57 +00001226 TypeSourceInfo *TInfo;
1227 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1228 if (!TInfo)
1229 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001230
Serge Pavlov38526372016-11-12 15:38:55 +00001231 // Handle errors like: int({0})
1232 if (exprs.size() == 1 && !canInitializeWithParenthesizedList(Ty) &&
1233 LParenLoc.isValid() && RParenLoc.isValid())
1234 if (auto IList = dyn_cast<InitListExpr>(exprs[0])) {
1235 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1236 << Ty << IList->getSourceRange()
1237 << FixItHint::CreateRemoval(LParenLoc)
1238 << FixItHint::CreateRemoval(RParenLoc);
1239 LParenLoc = RParenLoc = SourceLocation();
1240 }
1241
Richard Smithb8c414c2016-06-30 20:24:30 +00001242 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1243 // Avoid creating a non-type-dependent expression that contains typos.
1244 // Non-type-dependent expressions are liable to be discarded without
1245 // checking for embedded typos.
1246 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1247 !Result.get()->isTypeDependent())
1248 Result = CorrectDelayedTyposInExpr(Result.get());
1249 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001250}
1251
1252/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1253/// Can be interpreted either as function-style casting ("int(x)")
1254/// or class type construction ("ClassType(x,y,z)")
1255/// or creation of a value-initialized type ("int()").
1256ExprResult
1257Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1258 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001259 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001260 SourceLocation RParenLoc) {
1261 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001262 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001263
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001264 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001265 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1266 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001267 }
1268
Richard Smith600b5262017-01-26 20:40:47 +00001269 // C++1z [expr.type.conv]p1:
1270 // If the type is a placeholder for a deduced class type, [...perform class
1271 // template argument deduction...]
1272 DeducedType *Deduced = Ty->getContainedDeducedType();
1273 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1274 Diag(TyBeginLoc, diag::err_deduced_class_template_not_supported);
1275 return ExprError();
1276 }
1277
Sebastian Redld74dd492012-02-12 18:41:05 +00001278 bool ListInitialization = LParenLoc.isInvalid();
Richard Smith600b5262017-01-26 20:40:47 +00001279 assert((!ListInitialization ||
1280 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1281 "List initialization must have initializer list as expression.");
Sebastian Redld74dd492012-02-12 18:41:05 +00001282 SourceRange FullRange = SourceRange(TyBeginLoc,
1283 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1284
Douglas Gregordd04d332009-01-16 18:33:17 +00001285 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001286 // If the expression list is a single expression, the type conversion
1287 // expression is equivalent (in definedness, and if defined in meaning) to the
1288 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001289 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001290 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001291 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001292 }
1293
David Majnemer7eddcff2015-09-14 07:05:00 +00001294 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1295 // simple-type-specifier or typename-specifier for a non-array complete
1296 // object type or the (possibly cv-qualified) void type, creates a prvalue
1297 // of the specified type, whose value is that produced by value-initializing
1298 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001299 QualType ElemTy = Ty;
1300 if (Ty->isArrayType()) {
1301 if (!ListInitialization)
1302 return ExprError(Diag(TyBeginLoc,
1303 diag::err_value_init_for_array_type) << FullRange);
1304 ElemTy = Context.getBaseElementType(Ty);
1305 }
1306
David Majnemer7eddcff2015-09-14 07:05:00 +00001307 if (!ListInitialization && Ty->isFunctionType())
1308 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1309 << FullRange);
1310
Eli Friedman576cbd02012-02-29 00:00:28 +00001311 if (!Ty->isVoidType() &&
1312 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001313 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001314 return ExprError();
1315
Douglas Gregor8ec51732010-09-08 21:40:08 +00001316 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001317 InitializationKind Kind =
1318 Exprs.size() ? ListInitialization
1319 ? InitializationKind::CreateDirectList(TyBeginLoc)
1320 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1321 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1322 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1323 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001324
Richard Smith90061902013-09-23 02:20:00 +00001325 if (Result.isInvalid() || !ListInitialization)
1326 return Result;
1327
1328 Expr *Inner = Result.get();
1329 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1330 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001331 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1332 // If we created a CXXTemporaryObjectExpr, that node also represents the
1333 // functional cast. Otherwise, create an explicit cast to represent
1334 // the syntactic form of a functional-style cast that was used here.
1335 //
1336 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1337 // would give a more consistent AST representation than using a
1338 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1339 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001340 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001341 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001342 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001343 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001344 }
1345
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001346 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001347}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001348
Richard Smithb2f0f052016-10-10 18:54:32 +00001349/// \brief Determine whether the given function is a non-placement
1350/// deallocation function.
1351static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1352 if (FD->isInvalidDecl())
1353 return false;
1354
1355 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1356 return Method->isUsualDeallocationFunction();
1357
1358 if (FD->getOverloadedOperator() != OO_Delete &&
1359 FD->getOverloadedOperator() != OO_Array_Delete)
1360 return false;
1361
1362 unsigned UsualParams = 1;
1363
1364 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1365 S.Context.hasSameUnqualifiedType(
1366 FD->getParamDecl(UsualParams)->getType(),
1367 S.Context.getSizeType()))
1368 ++UsualParams;
1369
1370 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1371 S.Context.hasSameUnqualifiedType(
1372 FD->getParamDecl(UsualParams)->getType(),
1373 S.Context.getTypeDeclType(S.getStdAlignValT())))
1374 ++UsualParams;
1375
1376 return UsualParams == FD->getNumParams();
1377}
1378
1379namespace {
1380 struct UsualDeallocFnInfo {
1381 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001382 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001383 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001384 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001385 // A function template declaration is never a usual deallocation function.
1386 if (!FD)
1387 return;
1388 if (FD->getNumParams() == 3)
1389 HasAlignValT = HasSizeT = true;
1390 else if (FD->getNumParams() == 2) {
1391 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1392 HasAlignValT = !HasSizeT;
1393 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001394
1395 // In CUDA, determine how much we'd like / dislike to call this.
1396 if (S.getLangOpts().CUDA)
1397 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1398 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001399 }
1400
1401 operator bool() const { return FD; }
1402
Richard Smithf75dcbe2016-10-11 00:21:10 +00001403 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1404 bool WantAlign) const {
1405 // C++17 [expr.delete]p10:
1406 // If the type has new-extended alignment, a function with a parameter
1407 // of type std::align_val_t is preferred; otherwise a function without
1408 // such a parameter is preferred
1409 if (HasAlignValT != Other.HasAlignValT)
1410 return HasAlignValT == WantAlign;
1411
1412 if (HasSizeT != Other.HasSizeT)
1413 return HasSizeT == WantSize;
1414
1415 // Use CUDA call preference as a tiebreaker.
1416 return CUDAPref > Other.CUDAPref;
1417 }
1418
Richard Smithb2f0f052016-10-10 18:54:32 +00001419 DeclAccessPair Found;
1420 FunctionDecl *FD;
1421 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001422 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001423 };
1424}
1425
1426/// Determine whether a type has new-extended alignment. This may be called when
1427/// the type is incomplete (for a delete-expression with an incomplete pointee
1428/// type), in which case it will conservatively return false if the alignment is
1429/// not known.
1430static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1431 return S.getLangOpts().AlignedAllocation &&
1432 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1433 S.getASTContext().getTargetInfo().getNewAlign();
1434}
1435
1436/// Select the correct "usual" deallocation function to use from a selection of
1437/// deallocation functions (either global or class-scope).
1438static UsualDeallocFnInfo resolveDeallocationOverload(
1439 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1440 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1441 UsualDeallocFnInfo Best;
1442
Richard Smithb2f0f052016-10-10 18:54:32 +00001443 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001444 UsualDeallocFnInfo Info(S, I.getPair());
1445 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1446 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001447 continue;
1448
1449 if (!Best) {
1450 Best = Info;
1451 if (BestFns)
1452 BestFns->push_back(Info);
1453 continue;
1454 }
1455
Richard Smithf75dcbe2016-10-11 00:21:10 +00001456 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001457 continue;
1458
1459 // If more than one preferred function is found, all non-preferred
1460 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001461 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001462 BestFns->clear();
1463
1464 Best = Info;
1465 if (BestFns)
1466 BestFns->push_back(Info);
1467 }
1468
1469 return Best;
1470}
1471
1472/// Determine whether a given type is a class for which 'delete[]' would call
1473/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1474/// we need to store the array size (even if the type is
1475/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001476static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1477 QualType allocType) {
1478 const RecordType *record =
1479 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1480 if (!record) return false;
1481
1482 // Try to find an operator delete[] in class scope.
1483
1484 DeclarationName deleteName =
1485 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1486 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1487 S.LookupQualifiedName(ops, record->getDecl());
1488
1489 // We're just doing this for information.
1490 ops.suppressDiagnostics();
1491
1492 // Very likely: there's no operator delete[].
1493 if (ops.empty()) return false;
1494
1495 // If it's ambiguous, it should be illegal to call operator delete[]
1496 // on this thing, so it doesn't matter if we allocate extra space or not.
1497 if (ops.isAmbiguous()) return false;
1498
Richard Smithb2f0f052016-10-10 18:54:32 +00001499 // C++17 [expr.delete]p10:
1500 // If the deallocation functions have class scope, the one without a
1501 // parameter of type std::size_t is selected.
1502 auto Best = resolveDeallocationOverload(
1503 S, ops, /*WantSize*/false,
1504 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1505 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001506}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001507
Sebastian Redld74dd492012-02-12 18:41:05 +00001508/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001509///
Sebastian Redld74dd492012-02-12 18:41:05 +00001510/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001511/// @code new (memory) int[size][4] @endcode
1512/// or
1513/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001514///
1515/// \param StartLoc The first location of the expression.
1516/// \param UseGlobal True if 'new' was prefixed with '::'.
1517/// \param PlacementLParen Opening paren of the placement arguments.
1518/// \param PlacementArgs Placement new arguments.
1519/// \param PlacementRParen Closing paren of the placement arguments.
1520/// \param TypeIdParens If the type is in parens, the source range.
1521/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001522/// \param Initializer The initializing expression or initializer-list, or null
1523/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001524ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001525Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001526 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001528 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001529 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001530 // If the specified type is an array, unwrap it and save the expression.
1531 if (D.getNumTypeObjects() > 0 &&
1532 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001533 DeclaratorChunk &Chunk = D.getTypeObject(0);
1534 if (D.getDeclSpec().containsPlaceholderType())
Richard Smith30482bc2011-02-20 03:19:35 +00001535 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1536 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001537 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001538 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1539 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001540 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001541 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1542 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001543
Sebastian Redl351bb782008-12-02 14:43:59 +00001544 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001545 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001546 }
1547
Douglas Gregor73341c42009-09-11 00:18:58 +00001548 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001549 if (ArraySize) {
1550 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001551 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1552 break;
1553
1554 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1555 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001556 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001557 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001558 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1559 // shall be a converted constant expression (5.19) of type std::size_t
1560 // and shall evaluate to a strictly positive value.
1561 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1562 assert(IntWidth && "Builtin type of size 0?");
1563 llvm::APSInt Value(IntWidth);
1564 Array.NumElts
1565 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1566 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001567 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001568 } else {
1569 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001570 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001571 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001572 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001573 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001574 if (!Array.NumElts)
1575 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001576 }
1577 }
1578 }
1579 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001580
Craig Topperc3ec1492014-05-26 06:22:03 +00001581 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001582 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001583 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001584 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001585
Sebastian Redl6047f072012-02-16 12:22:20 +00001586 SourceRange DirectInitRange;
Serge Pavlov38526372016-11-12 15:38:55 +00001587 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001588 DirectInitRange = List->getSourceRange();
Serge Pavlov38526372016-11-12 15:38:55 +00001589 // Handle errors like: new int a({0})
1590 if (List->getNumExprs() == 1 &&
1591 !canInitializeWithParenthesizedList(AllocType))
1592 if (auto IList = dyn_cast<InitListExpr>(List->getExpr(0))) {
1593 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1594 << AllocType << List->getSourceRange()
1595 << FixItHint::CreateRemoval(List->getLocStart())
1596 << FixItHint::CreateRemoval(List->getLocEnd());
1597 DirectInitRange = SourceRange();
1598 Initializer = IList;
1599 }
1600 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001601
David Blaikie7b97aef2012-11-07 00:12:38 +00001602 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001603 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001604 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001605 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001606 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001607 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001608 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001609 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001610 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001611 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001612}
1613
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001614static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1615 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001616 if (!Init)
1617 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001618 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1619 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001620 if (isa<ImplicitValueInitExpr>(Init))
1621 return true;
1622 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1623 return !CCE->isListInitialization() &&
1624 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001625 else if (Style == CXXNewExpr::ListInit) {
1626 assert(isa<InitListExpr>(Init) &&
1627 "Shouldn't create list CXXConstructExprs for arrays.");
1628 return true;
1629 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001630 return false;
1631}
1632
John McCalldadc5752010-08-24 06:29:42 +00001633ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001634Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001635 SourceLocation PlacementLParen,
1636 MultiExprArg PlacementArgs,
1637 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001638 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001639 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001640 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001641 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001642 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001643 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001644 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001645 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001646
Sebastian Redl6047f072012-02-16 12:22:20 +00001647 CXXNewExpr::InitializationStyle initStyle;
1648 if (DirectInitRange.isValid()) {
1649 assert(Initializer && "Have parens but no initializer.");
1650 initStyle = CXXNewExpr::CallInit;
1651 } else if (Initializer && isa<InitListExpr>(Initializer))
1652 initStyle = CXXNewExpr::ListInit;
1653 else {
1654 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1655 isa<CXXConstructExpr>(Initializer)) &&
1656 "Initializer expression that cannot have been implicitly created.");
1657 initStyle = CXXNewExpr::NoInit;
1658 }
1659
1660 Expr **Inits = &Initializer;
1661 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001662 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1663 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1664 Inits = List->getExprs();
1665 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001666 }
1667
Richard Smith66204ec2014-03-12 17:42:45 +00001668 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith3beb7c62017-01-12 02:27:38 +00001669 if (AllocType->isUndeducedType()) {
Richard Smith600b5262017-01-26 20:40:47 +00001670 if (isa<DeducedTemplateSpecializationType>(
1671 AllocType->getContainedDeducedType()))
1672 return ExprError(Diag(TypeRange.getBegin(),
1673 diag::err_deduced_class_template_not_supported));
1674
Sebastian Redl6047f072012-02-16 12:22:20 +00001675 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001676 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1677 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001678 if (initStyle == CXXNewExpr::ListInit ||
1679 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001680 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001681 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001682 << AllocType << TypeRange);
1683 if (NumInits > 1) {
1684 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001685 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001686 diag::err_auto_new_ctor_multiple_expressions)
1687 << AllocType << TypeRange);
1688 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001689 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001690 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001691 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001692 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001693 << AllocType << Deduce->getType()
1694 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001695 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001696 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001697 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001698 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001699
Douglas Gregorcda95f42010-05-16 16:01:03 +00001700 // Per C++0x [expr.new]p5, the type being constructed may be a
1701 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001702 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001703 if (const ConstantArrayType *Array
1704 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001705 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1706 Context.getSizeType(),
1707 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001708 AllocType = Array->getElementType();
1709 }
1710 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001711
Douglas Gregor3999e152010-10-06 16:00:31 +00001712 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1713 return ExprError();
1714
Craig Topperc3ec1492014-05-26 06:22:03 +00001715 if (initStyle == CXXNewExpr::ListInit &&
1716 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001717 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1718 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001719 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001720 }
1721
Simon Pilgrim75c26882016-09-30 14:25:09 +00001722 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001723 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001724 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1725 AllocType->isObjCLifetimeType()) {
1726 AllocType = Context.getLifetimeQualifiedType(AllocType,
1727 AllocType->getObjCARCImplicitLifetime());
1728 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001729
John McCall31168b02011-06-15 23:02:42 +00001730 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001731
John McCall5e77d762013-04-16 07:28:30 +00001732 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1733 ExprResult result = CheckPlaceholderExpr(ArraySize);
1734 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001735 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001736 }
Richard Smith8dd34252012-02-04 07:07:42 +00001737 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1738 // integral or enumeration type with a non-negative value."
1739 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1740 // enumeration type, or a class type for which a single non-explicit
1741 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001742 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001743 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001744 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001745 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001746 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001747 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001748 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1749
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001750 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1751 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001752
Simon Pilgrim75c26882016-09-30 14:25:09 +00001753 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001754 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001755 // Diagnose the compatibility of this conversion.
1756 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1757 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001758 } else {
1759 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1760 protected:
1761 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001762
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001763 public:
1764 SizeConvertDiagnoser(Expr *ArraySize)
1765 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1766 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001767
1768 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1769 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001770 return S.Diag(Loc, diag::err_array_size_not_integral)
1771 << S.getLangOpts().CPlusPlus11 << T;
1772 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001773
1774 SemaDiagnosticBuilder diagnoseIncomplete(
1775 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001776 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1777 << T << ArraySize->getSourceRange();
1778 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001779
1780 SemaDiagnosticBuilder diagnoseExplicitConv(
1781 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001782 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1783 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001784
1785 SemaDiagnosticBuilder noteExplicitConv(
1786 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001787 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1788 << ConvTy->isEnumeralType() << ConvTy;
1789 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001790
1791 SemaDiagnosticBuilder diagnoseAmbiguous(
1792 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001793 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1794 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001795
1796 SemaDiagnosticBuilder noteAmbiguous(
1797 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001798 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1799 << ConvTy->isEnumeralType() << ConvTy;
1800 }
Richard Smithccc11812013-05-21 19:05:48 +00001801
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001802 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1803 QualType T,
1804 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001805 return S.Diag(Loc,
1806 S.getLangOpts().CPlusPlus11
1807 ? diag::warn_cxx98_compat_array_size_conversion
1808 : diag::ext_array_size_conversion)
1809 << T << ConvTy->isEnumeralType() << ConvTy;
1810 }
1811 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001812
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001813 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1814 SizeDiagnoser);
1815 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001816 if (ConvertedSize.isInvalid())
1817 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001819 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001820 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001821
Douglas Gregor0bf31402010-10-08 23:50:27 +00001822 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001823 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001825 // C++98 [expr.new]p7:
1826 // The expression in a direct-new-declarator shall have integral type
1827 // with a non-negative value.
1828 //
Richard Smith0511d232016-10-05 22:41:02 +00001829 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1830 // per CWG1464. Otherwise, if it's not a constant, we must have an
1831 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001832 if (!ArraySize->isValueDependent()) {
1833 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001834 // We've already performed any required implicit conversion to integer or
1835 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001836 // FIXME: Per CWG1464, we are required to check the value prior to
1837 // converting to size_t. This will never find a negative array size in
1838 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001839 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001840 if (Value.isSigned() && Value.isNegative()) {
1841 return ExprError(Diag(ArraySize->getLocStart(),
1842 diag::err_typecheck_negative_array_size)
1843 << ArraySize->getSourceRange());
1844 }
1845
1846 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001847 unsigned ActiveSizeBits =
1848 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001849 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1850 return ExprError(Diag(ArraySize->getLocStart(),
1851 diag::err_array_too_large)
1852 << Value.toString(10)
1853 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001854 }
Richard Smith0511d232016-10-05 22:41:02 +00001855
1856 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001857 } else if (TypeIdParens.isValid()) {
1858 // Can't have dynamic array size when the type-id is in parentheses.
1859 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1860 << ArraySize->getSourceRange()
1861 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1862 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
Douglas Gregorf2753b32010-07-13 15:54:32 +00001864 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001865 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
John McCall036f2f62011-05-15 07:14:44 +00001868 // Note that we do *not* convert the argument in any way. It can
1869 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001870 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001871
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 FunctionDecl *OperatorNew = nullptr;
1873 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001874 unsigned Alignment =
1875 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1876 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1877 bool PassAlignment = getLangOpts().AlignedAllocation &&
1878 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001879
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001880 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001881 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001882 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001883 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001884 UseGlobal, AllocType, ArraySize, PassAlignment,
1885 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001886 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001887
1888 // If this is an array allocation, compute whether the usual array
1889 // deallocation function for the type has a size_t parameter.
1890 bool UsualArrayDeleteWantsSize = false;
1891 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001892 UsualArrayDeleteWantsSize =
1893 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001894
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001895 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001896 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001898 OperatorNew->getType()->getAs<FunctionProtoType>();
1899 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1900 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
Richard Smithd6f9e732014-05-13 19:56:21 +00001902 // We've already converted the placement args, just fill in any default
1903 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001904 // argument. Skip the second parameter too if we're passing in the
1905 // alignment; we've already filled it in.
1906 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1907 PassAlignment ? 2 : 1, PlacementArgs,
1908 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001909 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001910
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001911 if (!AllPlaceArgs.empty())
1912 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001913
Richard Smithd6f9e732014-05-13 19:56:21 +00001914 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001915 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001916
1917 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918
Richard Smithb2f0f052016-10-10 18:54:32 +00001919 // Warn if the type is over-aligned and is being allocated by (unaligned)
1920 // global operator new.
1921 if (PlacementArgs.empty() && !PassAlignment &&
1922 (OperatorNew->isImplicit() ||
1923 (OperatorNew->getLocStart().isValid() &&
1924 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1925 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001926 Diag(StartLoc, diag::warn_overaligned_type)
1927 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001928 << unsigned(Alignment / Context.getCharWidth())
1929 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001930 }
1931 }
1932
Sebastian Redl6047f072012-02-16 12:22:20 +00001933 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001934 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1935 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001936 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1937 SourceRange InitRange(Inits[0]->getLocStart(),
1938 Inits[NumInits - 1]->getLocEnd());
1939 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1940 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001941 }
1942
Richard Smithdd2ca572012-11-26 08:32:48 +00001943 // If we can perform the initialization, and we've not already done so,
1944 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001945 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001946 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001947 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001948 // The type we initialize is the complete type, including the array bound.
1949 QualType InitType;
1950 if (KnownArraySize)
1951 InitType = Context.getConstantArrayType(
1952 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1953 *KnownArraySize),
1954 ArrayType::Normal, 0);
1955 else if (ArraySize)
1956 InitType =
1957 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1958 else
1959 InitType = AllocType;
1960
Sebastian Redld74dd492012-02-12 18:41:05 +00001961 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001962 // A new-expression that creates an object of type T initializes that
1963 // object as follows:
1964 InitializationKind Kind
1965 // - If the new-initializer is omitted, the object is default-
1966 // initialized (8.5); if no initialization is performed,
1967 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001968 = initStyle == CXXNewExpr::NoInit
1969 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001971 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001972 : initStyle == CXXNewExpr::ListInit
1973 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1974 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1975 DirectInitRange.getBegin(),
1976 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
Douglas Gregor85dabae2009-12-16 01:38:02 +00001978 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001979 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001980 InitializationSequence InitSeq(*this, Entity, Kind,
1981 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001983 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001984 if (FullInit.isInvalid())
1985 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Sebastian Redl6047f072012-02-16 12:22:20 +00001987 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1988 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001989 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001990 if (CXXBindTemporaryExpr *Binder =
1991 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001992 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001994 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996
Douglas Gregor6642ca22010-02-26 05:06:18 +00001997 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001998 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001999 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2000 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002001 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002002 }
2003 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002004 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2005 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002006 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002007 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002008
John McCall928a2572011-07-13 20:12:57 +00002009 // C++0x [expr.new]p17:
2010 // If the new expression creates an array of objects of class type,
2011 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002012 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2013 if (ArraySize && !BaseAllocType->isDependentType()) {
2014 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2015 if (CXXDestructorDecl *dtor = LookupDestructor(
2016 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2017 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002018 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002019 PDiag(diag::err_access_dtor)
2020 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002021 if (DiagnoseUseOfDecl(dtor, StartLoc))
2022 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002023 }
John McCall928a2572011-07-13 20:12:57 +00002024 }
2025 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002027 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002028 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002029 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2030 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2031 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002032}
2033
Sebastian Redl6047f072012-02-16 12:22:20 +00002034/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002035/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002036bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002037 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002038 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2039 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002040 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002041 return Diag(Loc, diag::err_bad_new_type)
2042 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002043 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002044 return Diag(Loc, diag::err_bad_new_type)
2045 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002046 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002047 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002048 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002049 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002050 diag::err_allocation_of_abstract_type))
2051 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002052 else if (AllocType->isVariablyModifiedType())
2053 return Diag(Loc, diag::err_variably_modified_new_type)
2054 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002055 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2056 return Diag(Loc, diag::err_address_space_qualified_new)
2057 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002058 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002059 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2060 QualType BaseAllocType = Context.getBaseElementType(AT);
2061 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2062 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002063 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002064 << BaseAllocType;
2065 }
2066 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002067
Sebastian Redlbd150f42008-11-21 19:14:01 +00002068 return false;
2069}
2070
Richard Smithb2f0f052016-10-10 18:54:32 +00002071static bool
2072resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2073 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2074 FunctionDecl *&Operator,
2075 OverloadCandidateSet *AlignedCandidates = nullptr,
2076 Expr *AlignArg = nullptr) {
2077 OverloadCandidateSet Candidates(R.getNameLoc(),
2078 OverloadCandidateSet::CSK_Normal);
2079 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2080 Alloc != AllocEnd; ++Alloc) {
2081 // Even member operator new/delete are implicitly treated as
2082 // static, so don't use AddMemberCandidate.
2083 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2084
2085 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2086 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2087 /*ExplicitTemplateArgs=*/nullptr, Args,
2088 Candidates,
2089 /*SuppressUserConversions=*/false);
2090 continue;
2091 }
2092
2093 FunctionDecl *Fn = cast<FunctionDecl>(D);
2094 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2095 /*SuppressUserConversions=*/false);
2096 }
2097
2098 // Do the resolution.
2099 OverloadCandidateSet::iterator Best;
2100 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2101 case OR_Success: {
2102 // Got one!
2103 FunctionDecl *FnDecl = Best->Function;
2104 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2105 Best->FoundDecl) == Sema::AR_inaccessible)
2106 return true;
2107
2108 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002109 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002110 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002111
Richard Smithb2f0f052016-10-10 18:54:32 +00002112 case OR_No_Viable_Function:
2113 // C++17 [expr.new]p13:
2114 // If no matching function is found and the allocated object type has
2115 // new-extended alignment, the alignment argument is removed from the
2116 // argument list, and overload resolution is performed again.
2117 if (PassAlignment) {
2118 PassAlignment = false;
2119 AlignArg = Args[1];
2120 Args.erase(Args.begin() + 1);
2121 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2122 Operator, &Candidates, AlignArg);
2123 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002124
Richard Smithb2f0f052016-10-10 18:54:32 +00002125 // MSVC will fall back on trying to find a matching global operator new
2126 // if operator new[] cannot be found. Also, MSVC will leak by not
2127 // generating a call to operator delete or operator delete[], but we
2128 // will not replicate that bug.
2129 // FIXME: Find out how this interacts with the std::align_val_t fallback
2130 // once MSVC implements it.
2131 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2132 S.Context.getLangOpts().MSVCCompat) {
2133 R.clear();
2134 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2135 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2136 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2137 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2138 Operator, nullptr);
2139 }
Richard Smith1cdec012013-09-29 04:40:38 +00002140
Richard Smithb2f0f052016-10-10 18:54:32 +00002141 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2142 << R.getLookupName() << Range;
2143
2144 // If we have aligned candidates, only note the align_val_t candidates
2145 // from AlignedCandidates and the non-align_val_t candidates from
2146 // Candidates.
2147 if (AlignedCandidates) {
2148 auto IsAligned = [](OverloadCandidate &C) {
2149 return C.Function->getNumParams() > 1 &&
2150 C.Function->getParamDecl(1)->getType()->isAlignValT();
2151 };
2152 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2153
2154 // This was an overaligned allocation, so list the aligned candidates
2155 // first.
2156 Args.insert(Args.begin() + 1, AlignArg);
2157 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2158 R.getNameLoc(), IsAligned);
2159 Args.erase(Args.begin() + 1);
2160 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2161 IsUnaligned);
2162 } else {
2163 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2164 }
Richard Smith1cdec012013-09-29 04:40:38 +00002165 return true;
2166
Richard Smithb2f0f052016-10-10 18:54:32 +00002167 case OR_Ambiguous:
2168 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2169 << R.getLookupName() << Range;
2170 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2171 return true;
2172
2173 case OR_Deleted: {
2174 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2175 << Best->Function->isDeleted()
2176 << R.getLookupName()
2177 << S.getDeletedOrUnavailableSuffix(Best->Function)
2178 << Range;
2179 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2180 return true;
2181 }
2182 }
2183 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002184}
2185
Richard Smithb2f0f052016-10-10 18:54:32 +00002186
Sebastian Redlfaf68082008-12-03 20:26:15 +00002187/// FindAllocationFunctions - Finds the overloads of operator new and delete
2188/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002189bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2190 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002191 bool IsArray, bool &PassAlignment,
2192 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002193 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002194 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002195 // --- Choosing an allocation function ---
2196 // C++ 5.3.4p8 - 14 & 18
2197 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2198 // in the scope of the allocated class.
2199 // 2) If an array size is given, look for operator new[], else look for
2200 // operator new.
2201 // 3) The first argument is always size_t. Append the arguments from the
2202 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002203
Richard Smithb2f0f052016-10-10 18:54:32 +00002204 SmallVector<Expr*, 8> AllocArgs;
2205 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2206
2207 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002208 // FIXME: Should the Sema create the expression and embed it in the syntax
2209 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002210 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002211 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002212 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002213 Context.getSizeType(),
2214 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002215 AllocArgs.push_back(&Size);
2216
2217 QualType AlignValT = Context.VoidTy;
2218 if (PassAlignment) {
2219 DeclareGlobalNewDelete();
2220 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2221 }
2222 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2223 if (PassAlignment)
2224 AllocArgs.push_back(&Align);
2225
2226 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002227
Douglas Gregor6642ca22010-02-26 05:06:18 +00002228 // C++ [expr.new]p8:
2229 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002230 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002231 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002232 // type, the allocation function's name is operator new[] and the
2233 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002234 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002235 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002236
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002237 QualType AllocElemType = Context.getBaseElementType(AllocType);
2238
Richard Smithb2f0f052016-10-10 18:54:32 +00002239 // Find the allocation function.
2240 {
2241 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2242
2243 // C++1z [expr.new]p9:
2244 // If the new-expression begins with a unary :: operator, the allocation
2245 // function's name is looked up in the global scope. Otherwise, if the
2246 // allocated type is a class type T or array thereof, the allocation
2247 // function's name is looked up in the scope of T.
2248 if (AllocElemType->isRecordType() && !UseGlobal)
2249 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2250
2251 // We can see ambiguity here if the allocation function is found in
2252 // multiple base classes.
2253 if (R.isAmbiguous())
2254 return true;
2255
2256 // If this lookup fails to find the name, or if the allocated type is not
2257 // a class type, the allocation function's name is looked up in the
2258 // global scope.
2259 if (R.empty())
2260 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2261
2262 assert(!R.empty() && "implicitly declared allocation functions not found");
2263 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2264
2265 // We do our own custom access checks below.
2266 R.suppressDiagnostics();
2267
2268 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2269 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002270 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002271 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002272
Richard Smithb2f0f052016-10-10 18:54:32 +00002273 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002274 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002275 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002276 return false;
2277 }
2278
Richard Smithb2f0f052016-10-10 18:54:32 +00002279 // Note, the name of OperatorNew might have been changed from array to
2280 // non-array by resolveAllocationOverload.
2281 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2282 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2283 ? OO_Array_Delete
2284 : OO_Delete);
2285
Douglas Gregor6642ca22010-02-26 05:06:18 +00002286 // C++ [expr.new]p19:
2287 //
2288 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002289 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002290 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002291 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002292 // the scope of T. If this lookup fails to find the name, or if
2293 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002294 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002295 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002296 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002297 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002298 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002299 LookupQualifiedName(FoundDelete, RD);
2300 }
John McCallfb6f5262010-03-18 08:19:33 +00002301 if (FoundDelete.isAmbiguous())
2302 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002303
Richard Smithb2f0f052016-10-10 18:54:32 +00002304 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002305 if (FoundDelete.empty()) {
2306 DeclareGlobalNewDelete();
2307 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2308 }
2309
2310 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002311
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002312 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002313
John McCalld3be2c82010-09-14 21:34:24 +00002314 // Whether we're looking for a placement operator delete is dictated
2315 // by whether we selected a placement operator new, not by whether
2316 // we had explicit placement arguments. This matters for things like
2317 // struct A { void *operator new(size_t, int = 0); ... };
2318 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002319 //
2320 // We don't have any definition for what a "placement allocation function"
2321 // is, but we assume it's any allocation function whose
2322 // parameter-declaration-clause is anything other than (size_t).
2323 //
2324 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2325 // This affects whether an exception from the constructor of an overaligned
2326 // type uses the sized or non-sized form of aligned operator delete.
2327 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2328 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002329
2330 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002331 // C++ [expr.new]p20:
2332 // A declaration of a placement deallocation function matches the
2333 // declaration of a placement allocation function if it has the
2334 // same number of parameters and, after parameter transformations
2335 // (8.3.5), all parameter types except the first are
2336 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002337 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002338 // To perform this comparison, we compute the function type that
2339 // the deallocation function should have, and use that type both
2340 // for template argument deduction and for comparison purposes.
2341 QualType ExpectedFunctionType;
2342 {
2343 const FunctionProtoType *Proto
2344 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002345
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002346 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002348 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2349 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002350
John McCalldb40c7f2010-12-14 08:05:40 +00002351 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002352 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002353 EPI.Variadic = Proto->isVariadic();
2354
Douglas Gregor6642ca22010-02-26 05:06:18 +00002355 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002356 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002357 }
2358
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002359 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002360 DEnd = FoundDelete.end();
2361 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002362 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002363 if (FunctionTemplateDecl *FnTmpl =
2364 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002365 // Perform template argument deduction to try to match the
2366 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002367 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002368 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2369 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002370 continue;
2371 } else
2372 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2373
Richard Smithbaa47832016-12-01 02:11:49 +00002374 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2375 ExpectedFunctionType,
2376 /*AdjustExcpetionSpec*/true),
2377 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002378 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002379 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002380
Richard Smithb2f0f052016-10-10 18:54:32 +00002381 if (getLangOpts().CUDA)
2382 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2383 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002384 // C++1y [expr.new]p22:
2385 // For a non-placement allocation function, the normal deallocation
2386 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002387 //
2388 // Per [expr.delete]p10, this lookup prefers a member operator delete
2389 // without a size_t argument, but prefers a non-member operator delete
2390 // with a size_t where possible (which it always is in this case).
2391 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2392 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2393 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2394 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2395 &BestDeallocFns);
2396 if (Selected)
2397 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2398 else {
2399 // If we failed to select an operator, all remaining functions are viable
2400 // but ambiguous.
2401 for (auto Fn : BestDeallocFns)
2402 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002403 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002404 }
2405
2406 // C++ [expr.new]p20:
2407 // [...] If the lookup finds a single matching deallocation
2408 // function, that function will be called; otherwise, no
2409 // deallocation function will be called.
2410 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002411 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002412
Richard Smithb2f0f052016-10-10 18:54:32 +00002413 // C++1z [expr.new]p23:
2414 // If the lookup finds a usual deallocation function (3.7.4.2)
2415 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002416 // as a placement deallocation function, would have been
2417 // selected as a match for the allocation function, the program
2418 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002419 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002420 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002421 UsualDeallocFnInfo Info(*this,
2422 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002423 // Core issue, per mail to core reflector, 2016-10-09:
2424 // If this is a member operator delete, and there is a corresponding
2425 // non-sized member operator delete, this isn't /really/ a sized
2426 // deallocation function, it just happens to have a size_t parameter.
2427 bool IsSizedDelete = Info.HasSizeT;
2428 if (IsSizedDelete && !FoundGlobalDelete) {
2429 auto NonSizedDelete =
2430 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2431 /*WantAlign*/Info.HasAlignValT);
2432 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2433 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2434 IsSizedDelete = false;
2435 }
2436
2437 if (IsSizedDelete) {
2438 SourceRange R = PlaceArgs.empty()
2439 ? SourceRange()
2440 : SourceRange(PlaceArgs.front()->getLocStart(),
2441 PlaceArgs.back()->getLocEnd());
2442 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2443 if (!OperatorDelete->isImplicit())
2444 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2445 << DeleteName;
2446 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002447 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002448
2449 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2450 Matches[0].first);
2451 } else if (!Matches.empty()) {
2452 // We found multiple suitable operators. Per [expr.new]p20, that means we
2453 // call no 'operator delete' function, but we should at least warn the user.
2454 // FIXME: Suppress this warning if the construction cannot throw.
2455 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2456 << DeleteName << AllocElemType;
2457
2458 for (auto &Match : Matches)
2459 Diag(Match.second->getLocation(),
2460 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002461 }
2462
Sebastian Redlfaf68082008-12-03 20:26:15 +00002463 return false;
2464}
2465
2466/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2467/// delete. These are:
2468/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002469/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002470/// void* operator new(std::size_t) throw(std::bad_alloc);
2471/// void* operator new[](std::size_t) throw(std::bad_alloc);
2472/// void operator delete(void *) throw();
2473/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002474/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002475/// void* operator new(std::size_t);
2476/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002477/// void operator delete(void *) noexcept;
2478/// void operator delete[](void *) noexcept;
2479/// // C++1y:
2480/// void* operator new(std::size_t);
2481/// void* operator new[](std::size_t);
2482/// void operator delete(void *) noexcept;
2483/// void operator delete[](void *) noexcept;
2484/// void operator delete(void *, std::size_t) noexcept;
2485/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002486/// @endcode
2487/// Note that the placement and nothrow forms of new are *not* implicitly
2488/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002489void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002490 if (GlobalNewDeleteDeclared)
2491 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002492
Douglas Gregor87f54062009-09-15 22:30:29 +00002493 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002494 // [...] The following allocation and deallocation functions (18.4) are
2495 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002496 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497 //
Sebastian Redl37588092011-03-14 18:08:30 +00002498 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002499 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002500 // void* operator new[](std::size_t) throw(std::bad_alloc);
2501 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002502 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002503 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002504 // void* operator new(std::size_t);
2505 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002506 // void operator delete(void*) noexcept;
2507 // void operator delete[](void*) noexcept;
2508 // C++1y:
2509 // void* operator new(std::size_t);
2510 // void* operator new[](std::size_t);
2511 // void operator delete(void*) noexcept;
2512 // void operator delete[](void*) noexcept;
2513 // void operator delete(void*, std::size_t) noexcept;
2514 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002515 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002517 // new, operator new[], operator delete, operator delete[].
2518 //
2519 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2520 // "std" or "bad_alloc" as necessary to form the exception specification.
2521 // However, we do not make these implicit declarations visible to name
2522 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002523 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002524 // The "std::bad_alloc" class has not yet been declared, so build it
2525 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002526 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2527 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002528 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002530 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002531 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002532 }
Richard Smith59139022016-09-30 22:41:36 +00002533 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002534 // The "std::align_val_t" enum class has not yet been declared, so build it
2535 // implicitly.
2536 auto *AlignValT = EnumDecl::Create(
2537 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2538 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2539 AlignValT->setIntegerType(Context.getSizeType());
2540 AlignValT->setPromotionType(Context.getSizeType());
2541 AlignValT->setImplicit(true);
2542 StdAlignValT = AlignValT;
2543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544
Sebastian Redlfaf68082008-12-03 20:26:15 +00002545 GlobalNewDeleteDeclared = true;
2546
2547 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2548 QualType SizeT = Context.getSizeType();
2549
Richard Smith96269c52016-09-29 22:49:46 +00002550 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2551 QualType Return, QualType Param) {
2552 llvm::SmallVector<QualType, 3> Params;
2553 Params.push_back(Param);
2554
2555 // Create up to four variants of the function (sized/aligned).
2556 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2557 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002558 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002559
2560 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2561 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2562 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002563 if (Sized)
2564 Params.push_back(SizeT);
2565
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002566 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002567 if (Aligned)
2568 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2569
2570 DeclareGlobalAllocationFunction(
2571 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2572
2573 if (Aligned)
2574 Params.pop_back();
2575 }
2576 }
2577 };
2578
2579 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2580 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2581 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2582 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002583}
2584
2585/// DeclareGlobalAllocationFunction - Declares a single implicit global
2586/// allocation function if it doesn't already exist.
2587void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002588 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002589 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002590 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2591
2592 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002593 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2594 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2595 Alloc != AllocEnd; ++Alloc) {
2596 // Only look at non-template functions, as it is the predefined,
2597 // non-templated allocation function we are trying to declare here.
2598 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002599 if (Func->getNumParams() == Params.size()) {
2600 llvm::SmallVector<QualType, 3> FuncParams;
2601 for (auto *P : Func->parameters())
2602 FuncParams.push_back(
2603 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2604 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002605 // Make the function visible to name lookup, even if we found it in
2606 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002607 // allocation function, or is suppressing that function.
2608 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002609 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002610 }
Chandler Carruth93538422010-02-03 11:02:14 +00002611 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002612 }
2613 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002614
Richard Smithc015bc22014-02-07 22:39:53 +00002615 FunctionProtoType::ExtProtoInfo EPI;
2616
Richard Smithf8b417c2014-02-08 00:42:45 +00002617 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002619 = (Name.getCXXOverloadedOperator() == OO_New ||
2620 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002621 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002622 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002623 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002624 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002625 EPI.ExceptionSpec.Type = EST_Dynamic;
2626 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002627 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002628 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002629 EPI.ExceptionSpec =
2630 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002632
Artem Belevich07db5cf2016-10-21 20:34:05 +00002633 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2634 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2635 FunctionDecl *Alloc = FunctionDecl::Create(
2636 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2637 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2638 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002639
Artem Belevich07db5cf2016-10-21 20:34:05 +00002640 // Implicit sized deallocation functions always have default visibility.
2641 Alloc->addAttr(
2642 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002643
Artem Belevich07db5cf2016-10-21 20:34:05 +00002644 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2645 for (QualType T : Params) {
2646 ParamDecls.push_back(ParmVarDecl::Create(
2647 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2648 /*TInfo=*/nullptr, SC_None, nullptr));
2649 ParamDecls.back()->setImplicit();
2650 }
2651 Alloc->setParams(ParamDecls);
2652 if (ExtraAttr)
2653 Alloc->addAttr(ExtraAttr);
2654 Context.getTranslationUnitDecl()->addDecl(Alloc);
2655 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2656 };
2657
2658 if (!LangOpts.CUDA)
2659 CreateAllocationFunctionDecl(nullptr);
2660 else {
2661 // Host and device get their own declaration so each can be
2662 // defined or re-declared independently.
2663 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2664 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002665 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002666}
2667
Richard Smith1cdec012013-09-29 04:40:38 +00002668FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2669 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002670 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002671 DeclarationName Name) {
2672 DeclareGlobalNewDelete();
2673
2674 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2675 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2676
Richard Smithb2f0f052016-10-10 18:54:32 +00002677 // FIXME: It's possible for this to result in ambiguity, through a
2678 // user-declared variadic operator delete or the enable_if attribute. We
2679 // should probably not consider those cases to be usual deallocation
2680 // functions. But for now we just make an arbitrary choice in that case.
2681 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2682 Overaligned);
2683 assert(Result.FD && "operator delete missing from global scope?");
2684 return Result.FD;
2685}
Richard Smith1cdec012013-09-29 04:40:38 +00002686
Richard Smithb2f0f052016-10-10 18:54:32 +00002687FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2688 CXXRecordDecl *RD) {
2689 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002690
Richard Smithb2f0f052016-10-10 18:54:32 +00002691 FunctionDecl *OperatorDelete = nullptr;
2692 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2693 return nullptr;
2694 if (OperatorDelete)
2695 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002696
Richard Smithb2f0f052016-10-10 18:54:32 +00002697 // If there's no class-specific operator delete, look up the global
2698 // non-array delete.
2699 return FindUsualDeallocationFunction(
2700 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2701 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002702}
2703
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002704bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2705 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002706 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002707 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002708 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002709 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710
John McCall27b18f82009-11-17 02:14:36 +00002711 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002712 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002713
Chandler Carruthb6f99172010-06-28 00:30:51 +00002714 Found.suppressDiagnostics();
2715
Richard Smithb2f0f052016-10-10 18:54:32 +00002716 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002717
Richard Smithb2f0f052016-10-10 18:54:32 +00002718 // C++17 [expr.delete]p10:
2719 // If the deallocation functions have class scope, the one without a
2720 // parameter of type std::size_t is selected.
2721 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2722 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2723 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002724
Richard Smithb2f0f052016-10-10 18:54:32 +00002725 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002726 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002727 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002728
Richard Smithb2f0f052016-10-10 18:54:32 +00002729 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002730 if (Operator->isDeleted()) {
2731 if (Diagnose) {
2732 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002733 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002734 }
2735 return true;
2736 }
2737
Richard Smith921bd202012-02-26 09:11:52 +00002738 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002739 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002740 return true;
2741
John McCall66a87592010-08-04 00:31:26 +00002742 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002743 }
John McCall66a87592010-08-04 00:31:26 +00002744
Richard Smithb2f0f052016-10-10 18:54:32 +00002745 // We found multiple suitable operators; complain about the ambiguity.
2746 // FIXME: The standard doesn't say to do this; it appears that the intent
2747 // is that this should never happen.
2748 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002749 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002750 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2751 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002752 for (auto &Match : Matches)
2753 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002754 }
John McCall66a87592010-08-04 00:31:26 +00002755 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002756 }
2757
2758 // We did find operator delete/operator delete[] declarations, but
2759 // none of them were suitable.
2760 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002761 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002762 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2763 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002764
Richard Smithb2f0f052016-10-10 18:54:32 +00002765 for (NamedDecl *D : Found)
2766 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002767 diag::note_member_declared_here) << Name;
2768 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002769 return true;
2770 }
2771
Craig Topperc3ec1492014-05-26 06:22:03 +00002772 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002773 return false;
2774}
2775
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002776namespace {
2777/// \brief Checks whether delete-expression, and new-expression used for
2778/// initializing deletee have the same array form.
2779class MismatchingNewDeleteDetector {
2780public:
2781 enum MismatchResult {
2782 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2783 NoMismatch,
2784 /// Indicates that variable is initialized with mismatching form of \a new.
2785 VarInitMismatches,
2786 /// Indicates that member is initialized with mismatching form of \a new.
2787 MemberInitMismatches,
2788 /// Indicates that 1 or more constructors' definitions could not been
2789 /// analyzed, and they will be checked again at the end of translation unit.
2790 AnalyzeLater
2791 };
2792
2793 /// \param EndOfTU True, if this is the final analysis at the end of
2794 /// translation unit. False, if this is the initial analysis at the point
2795 /// delete-expression was encountered.
2796 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002797 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002798 HasUndefinedConstructors(false) {}
2799
2800 /// \brief Checks whether pointee of a delete-expression is initialized with
2801 /// matching form of new-expression.
2802 ///
2803 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2804 /// point where delete-expression is encountered, then a warning will be
2805 /// issued immediately. If return value is \c AnalyzeLater at the point where
2806 /// delete-expression is seen, then member will be analyzed at the end of
2807 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2808 /// couldn't be analyzed. If at least one constructor initializes the member
2809 /// with matching type of new, the return value is \c NoMismatch.
2810 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2811 /// \brief Analyzes a class member.
2812 /// \param Field Class member to analyze.
2813 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2814 /// for deleting the \p Field.
2815 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002816 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002817 /// List of mismatching new-expressions used for initialization of the pointee
2818 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2819 /// Indicates whether delete-expression was in array form.
2820 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002821
2822private:
2823 const bool EndOfTU;
2824 /// \brief Indicates that there is at least one constructor without body.
2825 bool HasUndefinedConstructors;
2826 /// \brief Returns \c CXXNewExpr from given initialization expression.
2827 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002828 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002829 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2830 /// \brief Returns whether member is initialized with mismatching form of
2831 /// \c new either by the member initializer or in-class initialization.
2832 ///
2833 /// If bodies of all constructors are not visible at the end of translation
2834 /// unit or at least one constructor initializes member with the matching
2835 /// form of \c new, mismatch cannot be proven, and this function will return
2836 /// \c NoMismatch.
2837 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2838 /// \brief Returns whether variable is initialized with mismatching form of
2839 /// \c new.
2840 ///
2841 /// If variable is initialized with matching form of \c new or variable is not
2842 /// initialized with a \c new expression, this function will return true.
2843 /// If variable is initialized with mismatching form of \c new, returns false.
2844 /// \param D Variable to analyze.
2845 bool hasMatchingVarInit(const DeclRefExpr *D);
2846 /// \brief Checks whether the constructor initializes pointee with mismatching
2847 /// form of \c new.
2848 ///
2849 /// Returns true, if member is initialized with matching form of \c new in
2850 /// member initializer list. Returns false, if member is initialized with the
2851 /// matching form of \c new in this constructor's initializer or given
2852 /// constructor isn't defined at the point where delete-expression is seen, or
2853 /// member isn't initialized by the constructor.
2854 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2855 /// \brief Checks whether member is initialized with matching form of
2856 /// \c new in member initializer list.
2857 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2858 /// Checks whether member is initialized with mismatching form of \c new by
2859 /// in-class initializer.
2860 MismatchResult analyzeInClassInitializer();
2861};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002862}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002863
2864MismatchingNewDeleteDetector::MismatchResult
2865MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2866 NewExprs.clear();
2867 assert(DE && "Expected delete-expression");
2868 IsArrayForm = DE->isArrayForm();
2869 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2870 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2871 return analyzeMemberExpr(ME);
2872 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2873 if (!hasMatchingVarInit(D))
2874 return VarInitMismatches;
2875 }
2876 return NoMismatch;
2877}
2878
2879const CXXNewExpr *
2880MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2881 assert(E != nullptr && "Expected a valid initializer expression");
2882 E = E->IgnoreParenImpCasts();
2883 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2884 if (ILE->getNumInits() == 1)
2885 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2886 }
2887
2888 return dyn_cast_or_null<const CXXNewExpr>(E);
2889}
2890
2891bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2892 const CXXCtorInitializer *CI) {
2893 const CXXNewExpr *NE = nullptr;
2894 if (Field == CI->getMember() &&
2895 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2896 if (NE->isArray() == IsArrayForm)
2897 return true;
2898 else
2899 NewExprs.push_back(NE);
2900 }
2901 return false;
2902}
2903
2904bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2905 const CXXConstructorDecl *CD) {
2906 if (CD->isImplicit())
2907 return false;
2908 const FunctionDecl *Definition = CD;
2909 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2910 HasUndefinedConstructors = true;
2911 return EndOfTU;
2912 }
2913 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2914 if (hasMatchingNewInCtorInit(CI))
2915 return true;
2916 }
2917 return false;
2918}
2919
2920MismatchingNewDeleteDetector::MismatchResult
2921MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2922 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002923 const Expr *InitExpr = Field->getInClassInitializer();
2924 if (!InitExpr)
2925 return EndOfTU ? NoMismatch : AnalyzeLater;
2926 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002927 if (NE->isArray() != IsArrayForm) {
2928 NewExprs.push_back(NE);
2929 return MemberInitMismatches;
2930 }
2931 }
2932 return NoMismatch;
2933}
2934
2935MismatchingNewDeleteDetector::MismatchResult
2936MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2937 bool DeleteWasArrayForm) {
2938 assert(Field != nullptr && "Analysis requires a valid class member.");
2939 this->Field = Field;
2940 IsArrayForm = DeleteWasArrayForm;
2941 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2942 for (const auto *CD : RD->ctors()) {
2943 if (hasMatchingNewInCtor(CD))
2944 return NoMismatch;
2945 }
2946 if (HasUndefinedConstructors)
2947 return EndOfTU ? NoMismatch : AnalyzeLater;
2948 if (!NewExprs.empty())
2949 return MemberInitMismatches;
2950 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2951 : NoMismatch;
2952}
2953
2954MismatchingNewDeleteDetector::MismatchResult
2955MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2956 assert(ME != nullptr && "Expected a member expression");
2957 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2958 return analyzeField(F, IsArrayForm);
2959 return NoMismatch;
2960}
2961
2962bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2963 const CXXNewExpr *NE = nullptr;
2964 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2965 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2966 NE->isArray() != IsArrayForm) {
2967 NewExprs.push_back(NE);
2968 }
2969 }
2970 return NewExprs.empty();
2971}
2972
2973static void
2974DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2975 const MismatchingNewDeleteDetector &Detector) {
2976 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2977 FixItHint H;
2978 if (!Detector.IsArrayForm)
2979 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2980 else {
2981 SourceLocation RSquare = Lexer::findLocationAfterToken(
2982 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2983 SemaRef.getLangOpts(), true);
2984 if (RSquare.isValid())
2985 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2986 }
2987 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2988 << Detector.IsArrayForm << H;
2989
2990 for (const auto *NE : Detector.NewExprs)
2991 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2992 << Detector.IsArrayForm;
2993}
2994
2995void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2996 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2997 return;
2998 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2999 switch (Detector.analyzeDeleteExpr(DE)) {
3000 case MismatchingNewDeleteDetector::VarInitMismatches:
3001 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3002 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3003 break;
3004 }
3005 case MismatchingNewDeleteDetector::AnalyzeLater: {
3006 DeleteExprs[Detector.Field].push_back(
3007 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3008 break;
3009 }
3010 case MismatchingNewDeleteDetector::NoMismatch:
3011 break;
3012 }
3013}
3014
3015void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3016 bool DeleteWasArrayForm) {
3017 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3018 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3019 case MismatchingNewDeleteDetector::VarInitMismatches:
3020 llvm_unreachable("This analysis should have been done for class members.");
3021 case MismatchingNewDeleteDetector::AnalyzeLater:
3022 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3023 "translation unit.");
3024 case MismatchingNewDeleteDetector::MemberInitMismatches:
3025 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3026 break;
3027 case MismatchingNewDeleteDetector::NoMismatch:
3028 break;
3029 }
3030}
3031
Sebastian Redlbd150f42008-11-21 19:14:01 +00003032/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3033/// @code ::delete ptr; @endcode
3034/// or
3035/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003036ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003037Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003038 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003039 // C++ [expr.delete]p1:
3040 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003041 // non-explicit conversion function to a pointer type. The result has type
3042 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003043 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003044 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3045
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003046 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003047 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003048 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003049 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003050
John Wiegley01296292011-04-08 18:41:53 +00003051 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003052 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003053 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003054 if (Ex.isInvalid())
3055 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003056
John Wiegley01296292011-04-08 18:41:53 +00003057 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003058
Richard Smithccc11812013-05-21 19:05:48 +00003059 class DeleteConverter : public ContextualImplicitConverter {
3060 public:
3061 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062
Craig Toppere14c0f82014-03-12 04:55:44 +00003063 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003064 // FIXME: If we have an operator T* and an operator void*, we must pick
3065 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003066 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003067 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003068 return true;
3069 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003070 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003071
Richard Smithccc11812013-05-21 19:05:48 +00003072 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003073 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003074 return S.Diag(Loc, diag::err_delete_operand) << T;
3075 }
3076
3077 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003078 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003079 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3080 }
3081
3082 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003083 QualType T,
3084 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003085 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3086 }
3087
3088 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003089 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003090 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3091 << ConvTy;
3092 }
3093
3094 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003095 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003096 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3097 }
3098
3099 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003100 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003101 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3102 << ConvTy;
3103 }
3104
3105 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003106 QualType T,
3107 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003108 llvm_unreachable("conversion functions are permitted");
3109 }
3110 } Converter;
3111
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003112 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003113 if (Ex.isInvalid())
3114 return ExprError();
3115 Type = Ex.get()->getType();
3116 if (!Converter.match(Type))
3117 // FIXME: PerformContextualImplicitConversion should return ExprError
3118 // itself in this case.
3119 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003120
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003121 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003122 QualType PointeeElem = Context.getBaseElementType(Pointee);
3123
3124 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003125 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003126 diag::err_address_space_qualified_delete)
3127 << Pointee.getUnqualifiedType() << AddressSpace;
3128
Craig Topperc3ec1492014-05-26 06:22:03 +00003129 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003130 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003132 // effectively bans deletion of "void*". However, most compilers support
3133 // this, so we treat it as a warning unless we're in a SFINAE context.
3134 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003135 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003136 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003137 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003138 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003139 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003140 // FIXME: This can result in errors if the definition was imported from a
3141 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003142 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003143 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003144 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3145 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3146 }
3147 }
3148
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003149 if (Pointee->isArrayType() && !ArrayForm) {
3150 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003151 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003152 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003153 ArrayForm = true;
3154 }
3155
Anders Carlssona471db02009-08-16 20:29:29 +00003156 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3157 ArrayForm ? OO_Array_Delete : OO_Delete);
3158
Eli Friedmanae4280f2011-07-26 22:25:31 +00003159 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003160 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003161 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3162 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003163 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
John McCall284c48f2011-01-27 09:37:56 +00003165 // If we're allocating an array of records, check whether the
3166 // usual operator delete[] has a size_t parameter.
3167 if (ArrayForm) {
3168 // If the user specifically asked to use the global allocator,
3169 // we'll need to do the lookup into the class.
3170 if (UseGlobal)
3171 UsualArrayDeleteWantsSize =
3172 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3173
3174 // Otherwise, the usual operator delete[] should be the
3175 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003176 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003177 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003178 UsualDeallocFnInfo(*this,
3179 DeclAccessPair::make(OperatorDelete, AS_public))
3180 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003181 }
3182
Richard Smitheec915d62012-02-18 04:13:32 +00003183 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003184 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003185 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003186 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003187 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3188 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003189 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003190
Nico Weber5a9259c2016-01-15 21:45:31 +00003191 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3192 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3193 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3194 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
Richard Smithb2f0f052016-10-10 18:54:32 +00003197 if (!OperatorDelete) {
3198 bool IsComplete = isCompleteType(StartLoc, Pointee);
3199 bool CanProvideSize =
3200 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3201 Pointee.isDestructedType());
3202 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3203
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003204 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003205 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3206 Overaligned, DeleteName);
3207 }
Mike Stump11289f42009-09-09 15:08:12 +00003208
Eli Friedmanfa0df832012-02-02 03:46:19 +00003209 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003210
Douglas Gregorfa778132011-02-01 15:50:11 +00003211 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003212 if (PointeeRD) {
3213 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003214 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003215 PDiag(diag::err_access_dtor) << PointeeElem);
3216 }
3217 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003218 }
3219
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003220 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003221 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3222 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003223 AnalyzeDeleteExprMismatch(Result);
3224 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003225}
3226
Nico Weber5a9259c2016-01-15 21:45:31 +00003227void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3228 bool IsDelete, bool CallCanBeVirtual,
3229 bool WarnOnNonAbstractTypes,
3230 SourceLocation DtorLoc) {
3231 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3232 return;
3233
3234 // C++ [expr.delete]p3:
3235 // In the first alternative (delete object), if the static type of the
3236 // object to be deleted is different from its dynamic type, the static
3237 // type shall be a base class of the dynamic type of the object to be
3238 // deleted and the static type shall have a virtual destructor or the
3239 // behavior is undefined.
3240 //
3241 const CXXRecordDecl *PointeeRD = dtor->getParent();
3242 // Note: a final class cannot be derived from, no issue there
3243 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3244 return;
3245
3246 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3247 if (PointeeRD->isAbstract()) {
3248 // If the class is abstract, we warn by default, because we're
3249 // sure the code has undefined behavior.
3250 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3251 << ClassType;
3252 } else if (WarnOnNonAbstractTypes) {
3253 // Otherwise, if this is not an array delete, it's a bit suspect,
3254 // but not necessarily wrong.
3255 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3256 << ClassType;
3257 }
3258 if (!IsDelete) {
3259 std::string TypeStr;
3260 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3261 Diag(DtorLoc, diag::note_delete_non_virtual)
3262 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3263 }
3264}
3265
Richard Smith03a4aa32016-06-23 19:02:52 +00003266Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3267 SourceLocation StmtLoc,
3268 ConditionKind CK) {
3269 ExprResult E =
3270 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3271 if (E.isInvalid())
3272 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003273 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3274 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003275}
3276
Douglas Gregor633caca2009-11-23 23:44:04 +00003277/// \brief Check the use of the given variable as a C++ condition in an if,
3278/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003279ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003280 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003281 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003282 if (ConditionVar->isInvalidDecl())
3283 return ExprError();
3284
Douglas Gregor633caca2009-11-23 23:44:04 +00003285 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286
Douglas Gregor633caca2009-11-23 23:44:04 +00003287 // C++ [stmt.select]p2:
3288 // The declarator shall not specify a function or an array.
3289 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003291 diag::err_invalid_use_of_function_type)
3292 << ConditionVar->getSourceRange());
3293 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003295 diag::err_invalid_use_of_array_type)
3296 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003297
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003298 ExprResult Condition = DeclRefExpr::Create(
3299 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3300 /*enclosing*/ false, ConditionVar->getLocation(),
3301 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003302
Eli Friedmanfa0df832012-02-02 03:46:19 +00003303 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003304
Richard Smith03a4aa32016-06-23 19:02:52 +00003305 switch (CK) {
3306 case ConditionKind::Boolean:
3307 return CheckBooleanCondition(StmtLoc, Condition.get());
3308
Richard Smithb130fe72016-06-23 19:16:49 +00003309 case ConditionKind::ConstexprIf:
3310 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3311
Richard Smith03a4aa32016-06-23 19:02:52 +00003312 case ConditionKind::Switch:
3313 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315
Richard Smith03a4aa32016-06-23 19:02:52 +00003316 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003317}
3318
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003319/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003320ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003321 // C++ 6.4p4:
3322 // The value of a condition that is an initialized declaration in a statement
3323 // other than a switch statement is the value of the declared variable
3324 // implicitly converted to type bool. If that conversion is ill-formed, the
3325 // program is ill-formed.
3326 // The value of a condition that is an expression is the value of the
3327 // expression, implicitly converted to bool.
3328 //
Richard Smithb130fe72016-06-23 19:16:49 +00003329 // FIXME: Return this value to the caller so they don't need to recompute it.
3330 llvm::APSInt Value(/*BitWidth*/1);
3331 return (IsConstexpr && !CondExpr->isValueDependent())
3332 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3333 CCEK_ConstexprIf)
3334 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003335}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003336
3337/// Helper function to determine whether this is the (deprecated) C++
3338/// conversion from a string literal to a pointer to non-const char or
3339/// non-const wchar_t (for narrow and wide string literals,
3340/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003341bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003342Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3343 // Look inside the implicit cast, if it exists.
3344 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3345 From = Cast->getSubExpr();
3346
3347 // A string literal (2.13.4) that is not a wide string literal can
3348 // be converted to an rvalue of type "pointer to char"; a wide
3349 // string literal can be converted to an rvalue of type "pointer
3350 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003351 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003352 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003353 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003354 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003355 // This conversion is considered only when there is an
3356 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003357 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3358 switch (StrLit->getKind()) {
3359 case StringLiteral::UTF8:
3360 case StringLiteral::UTF16:
3361 case StringLiteral::UTF32:
3362 // We don't allow UTF literals to be implicitly converted
3363 break;
3364 case StringLiteral::Ascii:
3365 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3366 ToPointeeType->getKind() == BuiltinType::Char_S);
3367 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003368 return Context.typesAreCompatible(Context.getWideCharType(),
3369 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003370 }
3371 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003372 }
3373
3374 return false;
3375}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003376
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003378 SourceLocation CastLoc,
3379 QualType Ty,
3380 CastKind Kind,
3381 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003382 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003383 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003384 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003385 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003386 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003387 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003388 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003389 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Richard Smith72d74052013-07-20 19:41:36 +00003391 if (S.RequireNonAbstractType(CastLoc, Ty,
3392 diag::err_allocation_of_abstract_type))
3393 return ExprError();
3394
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003395 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003396 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003397
Richard Smith5179eb72016-06-28 19:03:57 +00003398 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3399 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003400 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003401 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003402
Richard Smithf8adcdc2014-07-17 05:12:35 +00003403 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003404 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003405 ConstructorArgs, HadMultipleCandidates,
3406 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3407 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003408 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003409 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003411 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
John McCalle3027922010-08-25 11:45:40 +00003414 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003415 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Richard Smithd3f2d322015-02-24 21:16:19 +00003417 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003418 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003419 return ExprError();
3420
Douglas Gregora4253922010-04-16 22:17:36 +00003421 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003422 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3423 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003424 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003425 if (Result.isInvalid())
3426 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003427 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003428 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3429 CK_UserDefinedConversion, Result.get(),
3430 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431
Douglas Gregor668443e2011-01-20 00:18:04 +00003432 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003433 }
3434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435}
Douglas Gregora4253922010-04-16 22:17:36 +00003436
Douglas Gregor5fb53972009-01-14 15:45:31 +00003437/// PerformImplicitConversion - Perform an implicit conversion of the
3438/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003439/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003440/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003441/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003442ExprResult
3443Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003444 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003445 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003446 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003447 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003448 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003449 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3450 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003451 if (Res.isInvalid())
3452 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003453 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003454 break;
John Wiegley01296292011-04-08 18:41:53 +00003455 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003456
Anders Carlsson110b07b2009-09-15 06:28:28 +00003457 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003459 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003460 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003461 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003462 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003463 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003464 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
Anders Carlsson110b07b2009-09-15 06:28:28 +00003466 // If the user-defined conversion is specified by a conversion function,
3467 // the initial standard conversion sequence converts the source type to
3468 // the implicit object parameter of the conversion function.
3469 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003470 } else {
3471 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003472 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003473 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003474 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003476 // initial standard conversion sequence converts the source type to
3477 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003478 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480 }
Richard Smith72d74052013-07-20 19:41:36 +00003481 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003482 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003483 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003484 PerformImplicitConversion(From, BeforeToType,
3485 ICS.UserDefined.Before, AA_Converting,
3486 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003487 if (Res.isInvalid())
3488 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003489 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
3492 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003493 = BuildCXXCastArgument(*this,
3494 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003495 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003496 CastKind, cast<CXXMethodDecl>(FD),
3497 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003498 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003499 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003500
3501 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003502 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003503
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003504 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003505
Richard Smith507840d2011-11-29 22:48:16 +00003506 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3507 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003508 }
John McCall0d1da222010-01-12 00:44:57 +00003509
3510 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003511 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003512 PDiag(diag::err_typecheck_ambiguous_condition)
3513 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003514 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515
Douglas Gregor39c16d42008-10-24 04:54:22 +00003516 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003517 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003518
3519 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003520 bool Diagnosed =
3521 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3522 From->getType(), From, Action);
3523 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003524 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003525 }
3526
3527 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003528 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003529}
3530
Richard Smith507840d2011-11-29 22:48:16 +00003531/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003532/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003533/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003534/// expression. Flavor is the context in which we're performing this
3535/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003536ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003537Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003538 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003539 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003540 CheckedConversionKind CCK) {
3541 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003542
Mike Stump87c57ac2009-05-16 07:39:55 +00003543 // Overall FIXME: we are recomputing too many types here and doing far too
3544 // much extra work. What this means is that we need to keep track of more
3545 // information that is computed when we try the implicit conversion initially,
3546 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003547 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003548
Douglas Gregor2fe98832008-11-03 19:09:14 +00003549 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003550 // FIXME: When can ToType be a reference type?
3551 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003552 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003553 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003554 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003555 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003556 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003557 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003558 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003559 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3560 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003561 ConstructorArgs, /*HadMultipleCandidates*/ false,
3562 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3563 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003564 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003565 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003566 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3567 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003568 From, /*HadMultipleCandidates*/ false,
3569 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3570 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003571 }
3572
Douglas Gregor980fb162010-04-29 18:24:40 +00003573 // Resolve overloaded function references.
3574 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3575 DeclAccessPair Found;
3576 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3577 true, Found);
3578 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003579 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003580
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003581 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003582 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregor980fb162010-04-29 18:24:40 +00003584 From = FixOverloadedFunctionReference(From, Found, Fn);
3585 FromType = From->getType();
3586 }
3587
Richard Smitha23ab512013-05-23 00:30:41 +00003588 // If we're converting to an atomic type, first convert to the corresponding
3589 // non-atomic type.
3590 QualType ToAtomicType;
3591 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3592 ToAtomicType = ToType;
3593 ToType = ToAtomic->getValueType();
3594 }
3595
George Burgess IV8d141e02015-12-14 22:00:49 +00003596 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003597 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003598 switch (SCS.First) {
3599 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003600 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3601 FromType = FromAtomic->getValueType().getUnqualifiedType();
3602 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3603 From, /*BasePath=*/nullptr, VK_RValue);
3604 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003605 break;
3606
Eli Friedman946b7b52012-01-24 22:51:26 +00003607 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003608 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003609 ExprResult FromRes = DefaultLvalueConversion(From);
3610 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003611 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003612 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003613 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003614 }
John McCall34376a62010-12-04 03:47:34 +00003615
Douglas Gregor39c16d42008-10-24 04:54:22 +00003616 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003617 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003618 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003619 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003620 break;
3621
3622 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003623 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003624 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003625 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003626 break;
3627
3628 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003629 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003630 }
3631
Richard Smith507840d2011-11-29 22:48:16 +00003632 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003633 switch (SCS.Second) {
3634 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003635 // C++ [except.spec]p5:
3636 // [For] assignment to and initialization of pointers to functions,
3637 // pointers to member functions, and references to functions: the
3638 // target entity shall allow at least the exceptions allowed by the
3639 // source value in the assignment or initialization.
3640 switch (Action) {
3641 case AA_Assigning:
3642 case AA_Initializing:
3643 // Note, function argument passing and returning are initialization.
3644 case AA_Passing:
3645 case AA_Returning:
3646 case AA_Sending:
3647 case AA_Passing_CFAudited:
3648 if (CheckExceptionSpecCompatibility(From, ToType))
3649 return ExprError();
3650 break;
3651
3652 case AA_Casting:
3653 case AA_Converting:
3654 // Casts and implicit conversions are not initialization, so are not
3655 // checked for exception specification mismatches.
3656 break;
3657 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003658 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003659 break;
3660
3661 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003662 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003663 if (ToType->isBooleanType()) {
3664 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3665 SCS.Second == ICK_Integral_Promotion &&
3666 "only enums with fixed underlying type can promote to bool");
3667 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003668 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003669 } else {
3670 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003671 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003672 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003673 break;
3674
3675 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003676 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003677 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003678 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003679 break;
3680
3681 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003682 case ICK_Complex_Conversion: {
3683 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3684 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3685 CastKind CK;
3686 if (FromEl->isRealFloatingType()) {
3687 if (ToEl->isRealFloatingType())
3688 CK = CK_FloatingComplexCast;
3689 else
3690 CK = CK_FloatingComplexToIntegralComplex;
3691 } else if (ToEl->isRealFloatingType()) {
3692 CK = CK_IntegralComplexToFloatingComplex;
3693 } else {
3694 CK = CK_IntegralComplexCast;
3695 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003696 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003697 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003698 break;
John McCall8cb679e2010-11-15 09:13:47 +00003699 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003700
Douglas Gregor39c16d42008-10-24 04:54:22 +00003701 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003702 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003703 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003704 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003705 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003706 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003707 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003708 break;
3709
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003710 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003711 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003712 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003713 break;
3714
John McCall31168b02011-06-15 23:02:42 +00003715 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003716 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003717 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003718 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003719 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003720 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003721 diag::ext_typecheck_convert_incompatible_pointer)
3722 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003723 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003724 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003725 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003726 diag::ext_typecheck_convert_incompatible_pointer)
3727 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003728 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003729
Douglas Gregor33823722011-06-11 01:09:30 +00003730 if (From->getType()->isObjCObjectPointerType() &&
3731 ToType->isObjCObjectPointerType())
3732 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003733 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003734 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003735 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003736 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003737 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003738 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003739 diag::err_arc_weak_unavailable_assign);
3740 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003741 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003742 diag::err_arc_convesion_of_weak_unavailable)
3743 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003744 << From->getSourceRange();
3745 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003746
John McCall8cb679e2010-11-15 09:13:47 +00003747 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003748 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003749 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003750 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003751
3752 // Make sure we extend blocks if necessary.
3753 // FIXME: doing this here is really ugly.
3754 if (Kind == CK_BlockPointerToObjCPointerCast) {
3755 ExprResult E = From;
3756 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003757 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003758 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003759 if (getLangOpts().ObjCAutoRefCount)
3760 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003761 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003762 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003763 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003766 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003767 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003768 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003769 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003770 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003771 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003772 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003773
3774 // We may not have been able to figure out what this member pointer resolved
3775 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003776 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003777 (void)isCompleteType(From->getExprLoc(), From->getType());
3778 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003779 }
David Majnemerd96b9972014-08-08 00:10:39 +00003780
Richard Smith507840d2011-11-29 22:48:16 +00003781 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003782 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003783 break;
3784 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003786 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003787 // Perform half-to-boolean conversion via float.
3788 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003789 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003790 FromType = Context.FloatTy;
3791 }
3792
Richard Smith507840d2011-11-29 22:48:16 +00003793 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003794 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003795 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003796 break;
3797
Douglas Gregor88d292c2010-05-13 16:44:06 +00003798 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003799 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003801 ToType.getNonReferenceType(),
3802 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003804 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003805 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003806 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003807
Richard Smith507840d2011-11-29 22:48:16 +00003808 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3809 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003810 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003811 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003812 }
3813
Douglas Gregor46188682010-05-18 22:42:18 +00003814 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003815 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003816 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003817 break;
3818
George Burgess IVdf1ed002016-01-13 01:52:39 +00003819 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003820 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003821 Expr *Elem = prepareVectorSplat(ToType, From).get();
3822 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3823 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003824 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826
Douglas Gregor46188682010-05-18 22:42:18 +00003827 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003828 // Case 1. x -> _Complex y
3829 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3830 QualType ElType = ToComplex->getElementType();
3831 bool isFloatingComplex = ElType->isRealFloatingType();
3832
3833 // x -> y
3834 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3835 // do nothing
3836 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003837 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003838 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003839 } else {
3840 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003841 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003842 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003843 }
3844 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003845 From = ImpCastExprToType(From, ToType,
3846 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003847 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003848
3849 // Case 2. _Complex x -> y
3850 } else {
3851 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3852 assert(FromComplex);
3853
3854 QualType ElType = FromComplex->getElementType();
3855 bool isFloatingComplex = ElType->isRealFloatingType();
3856
3857 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003858 From = ImpCastExprToType(From, ElType,
3859 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003860 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003861 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003862
3863 // x -> y
3864 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3865 // do nothing
3866 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003867 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003868 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003869 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003870 } else {
3871 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003872 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003873 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003874 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003875 }
3876 }
Douglas Gregor46188682010-05-18 22:42:18 +00003877 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003878
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003879 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003880 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003881 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003882 break;
3883 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003884
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003885 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003886 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003887 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003888 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3889 if (FromRes.isInvalid())
3890 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003891 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003892 assert ((ConvTy == Sema::Compatible) &&
3893 "Improper transparent union conversion");
3894 (void)ConvTy;
3895 break;
3896 }
3897
Guy Benyei259f9f42013-02-07 16:05:33 +00003898 case ICK_Zero_Event_Conversion:
3899 From = ImpCastExprToType(From, ToType,
3900 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003901 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003902 break;
3903
Egor Churaev89831422016-12-23 14:55:49 +00003904 case ICK_Zero_Queue_Conversion:
3905 From = ImpCastExprToType(From, ToType,
3906 CK_ZeroToOCLQueue,
3907 From->getValueKind()).get();
3908 break;
3909
Douglas Gregor46188682010-05-18 22:42:18 +00003910 case ICK_Lvalue_To_Rvalue:
3911 case ICK_Array_To_Pointer:
3912 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003913 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003914 case ICK_Qualification:
3915 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003916 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003917 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003918 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003919 }
3920
3921 switch (SCS.Third) {
3922 case ICK_Identity:
3923 // Nothing to do.
3924 break;
3925
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003926 case ICK_Function_Conversion:
3927 // If both sides are functions (or pointers/references to them), there could
3928 // be incompatible exception declarations.
3929 if (CheckExceptionSpecCompatibility(From, ToType))
3930 return ExprError();
3931
3932 From = ImpCastExprToType(From, ToType, CK_NoOp,
3933 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3934 break;
3935
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003936 case ICK_Qualification: {
3937 // The qualification keeps the category of the inner expression, unless the
3938 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003939 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003940 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003941 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003942 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003943
Douglas Gregore981bb02011-03-14 16:13:32 +00003944 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003945 !getLangOpts().WritableStrings) {
3946 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3947 ? diag::ext_deprecated_string_literal_conversion
3948 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003949 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003950 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003951
Douglas Gregor39c16d42008-10-24 04:54:22 +00003952 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003953 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003954
Douglas Gregor39c16d42008-10-24 04:54:22 +00003955 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003956 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003957 }
3958
Douglas Gregor298f43d2012-04-12 20:42:30 +00003959 // If this conversion sequence involved a scalar -> atomic conversion, perform
3960 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003961 if (!ToAtomicType.isNull()) {
3962 assert(Context.hasSameType(
3963 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3964 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003965 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003966 }
3967
George Burgess IV8d141e02015-12-14 22:00:49 +00003968 // If this conversion sequence succeeded and involved implicitly converting a
3969 // _Nullable type to a _Nonnull one, complain.
3970 if (CCK == CCK_ImplicitConversion)
3971 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3972 From->getLocStart());
3973
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003974 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003975}
3976
Chandler Carruth8e172c62011-05-01 06:51:22 +00003977/// \brief Check the completeness of a type in a unary type trait.
3978///
3979/// If the particular type trait requires a complete type, tries to complete
3980/// it. If completing the type fails, a diagnostic is emitted and false
3981/// returned. If completing the type succeeds or no completion was required,
3982/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003983static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003984 SourceLocation Loc,
3985 QualType ArgTy) {
3986 // C++0x [meta.unary.prop]p3:
3987 // For all of the class templates X declared in this Clause, instantiating
3988 // that template with a template argument that is a class template
3989 // specialization may result in the implicit instantiation of the template
3990 // argument if and only if the semantics of X require that the argument
3991 // must be a complete type.
3992 // We apply this rule to all the type trait expressions used to implement
3993 // these class templates. We also try to follow any GCC documented behavior
3994 // in these expressions to ensure portability of standard libraries.
3995 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003996 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003997 // is_complete_type somewhat obviously cannot require a complete type.
3998 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003999 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004000
4001 // These traits are modeled on the type predicates in C++0x
4002 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4003 // requiring a complete type, as whether or not they return true cannot be
4004 // impacted by the completeness of the type.
4005 case UTT_IsVoid:
4006 case UTT_IsIntegral:
4007 case UTT_IsFloatingPoint:
4008 case UTT_IsArray:
4009 case UTT_IsPointer:
4010 case UTT_IsLvalueReference:
4011 case UTT_IsRvalueReference:
4012 case UTT_IsMemberFunctionPointer:
4013 case UTT_IsMemberObjectPointer:
4014 case UTT_IsEnum:
4015 case UTT_IsUnion:
4016 case UTT_IsClass:
4017 case UTT_IsFunction:
4018 case UTT_IsReference:
4019 case UTT_IsArithmetic:
4020 case UTT_IsFundamental:
4021 case UTT_IsObject:
4022 case UTT_IsScalar:
4023 case UTT_IsCompound:
4024 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004025 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004026
4027 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4028 // which requires some of its traits to have the complete type. However,
4029 // the completeness of the type cannot impact these traits' semantics, and
4030 // so they don't require it. This matches the comments on these traits in
4031 // Table 49.
4032 case UTT_IsConst:
4033 case UTT_IsVolatile:
4034 case UTT_IsSigned:
4035 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004036
4037 // This type trait always returns false, checking the type is moot.
4038 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004039 return true;
4040
David Majnemer213bea32015-11-16 06:58:51 +00004041 // C++14 [meta.unary.prop]:
4042 // If T is a non-union class type, T shall be a complete type.
4043 case UTT_IsEmpty:
4044 case UTT_IsPolymorphic:
4045 case UTT_IsAbstract:
4046 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4047 if (!RD->isUnion())
4048 return !S.RequireCompleteType(
4049 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4050 return true;
4051
4052 // C++14 [meta.unary.prop]:
4053 // If T is a class type, T shall be a complete type.
4054 case UTT_IsFinal:
4055 case UTT_IsSealed:
4056 if (ArgTy->getAsCXXRecordDecl())
4057 return !S.RequireCompleteType(
4058 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4059 return true;
4060
4061 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4062 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004063 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004064 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004065 case UTT_IsStandardLayout:
4066 case UTT_IsPOD:
4067 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004068
Alp Toker73287bf2014-01-20 00:24:09 +00004069 case UTT_IsDestructible:
4070 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004071 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004072
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004073 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004074 // [meta.unary.prop] despite not being named the same. They are specified
4075 // by both GCC and the Embarcadero C++ compiler, and require the complete
4076 // type due to the overarching C++0x type predicates being implemented
4077 // requiring the complete type.
4078 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004079 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004080 case UTT_HasNothrowConstructor:
4081 case UTT_HasNothrowCopy:
4082 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004083 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004084 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004085 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004086 case UTT_HasTrivialCopy:
4087 case UTT_HasTrivialDestructor:
4088 case UTT_HasVirtualDestructor:
4089 // Arrays of unknown bound are expressly allowed.
4090 QualType ElTy = ArgTy;
4091 if (ArgTy->isIncompleteArrayType())
4092 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4093
4094 // The void type is expressly allowed.
4095 if (ElTy->isVoidType())
4096 return true;
4097
4098 return !S.RequireCompleteType(
4099 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004100 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004101}
4102
Joao Matosc9523d42013-03-27 01:34:16 +00004103static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4104 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004105 bool (CXXRecordDecl::*HasTrivial)() const,
4106 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004107 bool (CXXMethodDecl::*IsDesiredOp)() const)
4108{
4109 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4110 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4111 return true;
4112
4113 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4114 DeclarationNameInfo NameInfo(Name, KeyLoc);
4115 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4116 if (Self.LookupQualifiedName(Res, RD)) {
4117 bool FoundOperator = false;
4118 Res.suppressDiagnostics();
4119 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4120 Op != OpEnd; ++Op) {
4121 if (isa<FunctionTemplateDecl>(*Op))
4122 continue;
4123
4124 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4125 if((Operator->*IsDesiredOp)()) {
4126 FoundOperator = true;
4127 const FunctionProtoType *CPT =
4128 Operator->getType()->getAs<FunctionProtoType>();
4129 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004130 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004131 return false;
4132 }
4133 }
4134 return FoundOperator;
4135 }
4136 return false;
4137}
4138
Alp Toker95e7ff22014-01-01 05:57:51 +00004139static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004140 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004141 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004142
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004143 ASTContext &C = Self.Context;
4144 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004145 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004146 // Type trait expressions corresponding to the primary type category
4147 // predicates in C++0x [meta.unary.cat].
4148 case UTT_IsVoid:
4149 return T->isVoidType();
4150 case UTT_IsIntegral:
4151 return T->isIntegralType(C);
4152 case UTT_IsFloatingPoint:
4153 return T->isFloatingType();
4154 case UTT_IsArray:
4155 return T->isArrayType();
4156 case UTT_IsPointer:
4157 return T->isPointerType();
4158 case UTT_IsLvalueReference:
4159 return T->isLValueReferenceType();
4160 case UTT_IsRvalueReference:
4161 return T->isRValueReferenceType();
4162 case UTT_IsMemberFunctionPointer:
4163 return T->isMemberFunctionPointerType();
4164 case UTT_IsMemberObjectPointer:
4165 return T->isMemberDataPointerType();
4166 case UTT_IsEnum:
4167 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004168 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004169 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004170 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004171 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004172 case UTT_IsFunction:
4173 return T->isFunctionType();
4174
4175 // Type trait expressions which correspond to the convenient composition
4176 // predicates in C++0x [meta.unary.comp].
4177 case UTT_IsReference:
4178 return T->isReferenceType();
4179 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004180 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004181 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004182 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004183 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004184 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004185 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004186 // Note: semantic analysis depends on Objective-C lifetime types to be
4187 // considered scalar types. However, such types do not actually behave
4188 // like scalar types at run time (since they may require retain/release
4189 // operations), so we report them as non-scalar.
4190 if (T->isObjCLifetimeType()) {
4191 switch (T.getObjCLifetime()) {
4192 case Qualifiers::OCL_None:
4193 case Qualifiers::OCL_ExplicitNone:
4194 return true;
4195
4196 case Qualifiers::OCL_Strong:
4197 case Qualifiers::OCL_Weak:
4198 case Qualifiers::OCL_Autoreleasing:
4199 return false;
4200 }
4201 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004202
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004203 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004204 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004205 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004206 case UTT_IsMemberPointer:
4207 return T->isMemberPointerType();
4208
4209 // Type trait expressions which correspond to the type property predicates
4210 // in C++0x [meta.unary.prop].
4211 case UTT_IsConst:
4212 return T.isConstQualified();
4213 case UTT_IsVolatile:
4214 return T.isVolatileQualified();
4215 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004216 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004217 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004218 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004219 case UTT_IsStandardLayout:
4220 return T->isStandardLayoutType();
4221 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004222 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004223 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004224 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004225 case UTT_IsEmpty:
4226 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4227 return !RD->isUnion() && RD->isEmpty();
4228 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004229 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004230 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004231 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004232 return false;
4233 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004234 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004235 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004236 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004237 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4238 // even then only when it is used with the 'interface struct ...' syntax
4239 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004240 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004241 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004242 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004243 case UTT_IsSealed:
4244 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004245 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004246 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004247 case UTT_IsSigned:
4248 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004249 case UTT_IsUnsigned:
4250 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004251
4252 // Type trait expressions which query classes regarding their construction,
4253 // destruction, and copying. Rather than being based directly on the
4254 // related type predicates in the standard, they are specified by both
4255 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4256 // specifications.
4257 //
4258 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4259 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004260 //
4261 // Note that these builtins do not behave as documented in g++: if a class
4262 // has both a trivial and a non-trivial special member of a particular kind,
4263 // they return false! For now, we emulate this behavior.
4264 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4265 // does not correctly compute triviality in the presence of multiple special
4266 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004267 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004268 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4269 // If __is_pod (type) is true then the trait is true, else if type is
4270 // a cv class or union type (or array thereof) with a trivial default
4271 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004272 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004273 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004274 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4275 return RD->hasTrivialDefaultConstructor() &&
4276 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004277 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004278 case UTT_HasTrivialMoveConstructor:
4279 // This trait is implemented by MSVC 2012 and needed to parse the
4280 // standard library headers. Specifically this is used as the logic
4281 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004282 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004283 return true;
4284 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4285 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4286 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004287 case UTT_HasTrivialCopy:
4288 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4289 // If __is_pod (type) is true or type is a reference type then
4290 // the trait is true, else if type is a cv class or union type
4291 // with a trivial copy constructor ([class.copy]) then the trait
4292 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004293 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004294 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004295 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4296 return RD->hasTrivialCopyConstructor() &&
4297 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004298 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004299 case UTT_HasTrivialMoveAssign:
4300 // This trait is implemented by MSVC 2012 and needed to parse the
4301 // standard library headers. Specifically it is used as the logic
4302 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004303 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004304 return true;
4305 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4306 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4307 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004308 case UTT_HasTrivialAssign:
4309 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4310 // If type is const qualified or is a reference type then the
4311 // trait is false. Otherwise if __is_pod (type) is true then the
4312 // trait is true, else if type is a cv class or union type with
4313 // a trivial copy assignment ([class.copy]) then the trait is
4314 // true, else it is false.
4315 // Note: the const and reference restrictions are interesting,
4316 // given that const and reference members don't prevent a class
4317 // from having a trivial copy assignment operator (but do cause
4318 // errors if the copy assignment operator is actually used, q.v.
4319 // [class.copy]p12).
4320
Richard Smith92f241f2012-12-08 02:53:02 +00004321 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004322 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004323 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004324 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004325 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4326 return RD->hasTrivialCopyAssignment() &&
4327 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004328 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004329 case UTT_IsDestructible:
4330 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004331 // C++14 [meta.unary.prop]:
4332 // For reference types, is_destructible<T>::value is true.
4333 if (T->isReferenceType())
4334 return true;
4335
4336 // Objective-C++ ARC: autorelease types don't require destruction.
4337 if (T->isObjCLifetimeType() &&
4338 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4339 return true;
4340
4341 // C++14 [meta.unary.prop]:
4342 // For incomplete types and function types, is_destructible<T>::value is
4343 // false.
4344 if (T->isIncompleteType() || T->isFunctionType())
4345 return false;
4346
4347 // C++14 [meta.unary.prop]:
4348 // For object types and given U equal to remove_all_extents_t<T>, if the
4349 // expression std::declval<U&>().~U() is well-formed when treated as an
4350 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4351 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4352 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4353 if (!Destructor)
4354 return false;
4355 // C++14 [dcl.fct.def.delete]p2:
4356 // A program that refers to a deleted function implicitly or
4357 // explicitly, other than to declare it, is ill-formed.
4358 if (Destructor->isDeleted())
4359 return false;
4360 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4361 return false;
4362 if (UTT == UTT_IsNothrowDestructible) {
4363 const FunctionProtoType *CPT =
4364 Destructor->getType()->getAs<FunctionProtoType>();
4365 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4366 if (!CPT || !CPT->isNothrow(C))
4367 return false;
4368 }
4369 }
4370 return true;
4371
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004372 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004373 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004374 // If __is_pod (type) is true or type is a reference type
4375 // then the trait is true, else if type is a cv class or union
4376 // type (or array thereof) with a trivial destructor
4377 // ([class.dtor]) then the trait is true, else it is
4378 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004379 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004380 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004381
John McCall31168b02011-06-15 23:02:42 +00004382 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004383 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004384 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4385 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004386
Richard Smith92f241f2012-12-08 02:53:02 +00004387 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4388 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004389 return false;
4390 // TODO: Propagate nothrowness for implicitly declared special members.
4391 case UTT_HasNothrowAssign:
4392 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4393 // If type is const qualified or is a reference type then the
4394 // trait is false. Otherwise if __has_trivial_assign (type)
4395 // is true then the trait is true, else if type is a cv class
4396 // or union type with copy assignment operators that are known
4397 // not to throw an exception then the trait is true, else it is
4398 // false.
4399 if (C.getBaseElementType(T).isConstQualified())
4400 return false;
4401 if (T->isReferenceType())
4402 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004403 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004404 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004405
Joao Matosc9523d42013-03-27 01:34:16 +00004406 if (const RecordType *RT = T->getAs<RecordType>())
4407 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4408 &CXXRecordDecl::hasTrivialCopyAssignment,
4409 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4410 &CXXMethodDecl::isCopyAssignmentOperator);
4411 return false;
4412 case UTT_HasNothrowMoveAssign:
4413 // This trait is implemented by MSVC 2012 and needed to parse the
4414 // standard library headers. Specifically this is used as the logic
4415 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004416 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004417 return true;
4418
4419 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4420 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4421 &CXXRecordDecl::hasTrivialMoveAssignment,
4422 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4423 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004424 return false;
4425 case UTT_HasNothrowCopy:
4426 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4427 // If __has_trivial_copy (type) is true then the trait is true, else
4428 // if type is a cv class or union type with copy constructors that are
4429 // known not to throw an exception then the trait is true, else it is
4430 // false.
John McCall31168b02011-06-15 23:02:42 +00004431 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004432 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004433 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4434 if (RD->hasTrivialCopyConstructor() &&
4435 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004436 return true;
4437
4438 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004439 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004440 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004441 // A template constructor is never a copy constructor.
4442 // FIXME: However, it may actually be selected at the actual overload
4443 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004444 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004445 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004446 // UsingDecl itself is not a constructor
4447 if (isa<UsingDecl>(ND))
4448 continue;
4449 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004450 if (Constructor->isCopyConstructor(FoundTQs)) {
4451 FoundConstructor = true;
4452 const FunctionProtoType *CPT
4453 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004454 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4455 if (!CPT)
4456 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004457 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004458 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004459 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004460 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004461 }
4462 }
4463
Richard Smith938f40b2011-06-11 17:19:42 +00004464 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004465 }
4466 return false;
4467 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004468 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004469 // If __has_trivial_constructor (type) is true then the trait is
4470 // true, else if type is a cv class or union type (or array
4471 // thereof) with a default constructor that is known not to
4472 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004473 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004474 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004475 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4476 if (RD->hasTrivialDefaultConstructor() &&
4477 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004478 return true;
4479
Alp Tokerb4bca412014-01-20 00:23:47 +00004480 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004481 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004482 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004483 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004484 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004485 // UsingDecl itself is not a constructor
4486 if (isa<UsingDecl>(ND))
4487 continue;
4488 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004489 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004490 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004491 const FunctionProtoType *CPT
4492 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004493 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4494 if (!CPT)
4495 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004496 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004497 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004498 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004499 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004500 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004501 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004502 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004503 }
4504 return false;
4505 case UTT_HasVirtualDestructor:
4506 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4507 // If type is a class type with a virtual destructor ([class.dtor])
4508 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004509 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004510 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004511 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004512 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004513
4514 // These type trait expressions are modeled on the specifications for the
4515 // Embarcadero C++0x type trait functions:
4516 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4517 case UTT_IsCompleteType:
4518 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4519 // Returns True if and only if T is a complete type at the point of the
4520 // function call.
4521 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004522 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004523}
Sebastian Redl5822f082009-02-07 20:10:22 +00004524
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004525/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4526/// ARC mode.
4527static bool hasNontrivialObjCLifetime(QualType T) {
4528 switch (T.getObjCLifetime()) {
4529 case Qualifiers::OCL_ExplicitNone:
4530 return false;
4531
4532 case Qualifiers::OCL_Strong:
4533 case Qualifiers::OCL_Weak:
4534 case Qualifiers::OCL_Autoreleasing:
4535 return true;
4536
4537 case Qualifiers::OCL_None:
4538 return T->isObjCLifetimeType();
4539 }
4540
4541 llvm_unreachable("Unknown ObjC lifetime qualifier");
4542}
4543
Alp Tokercbb90342013-12-13 20:49:58 +00004544static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4545 QualType RhsT, SourceLocation KeyLoc);
4546
Douglas Gregor29c42f22012-02-24 07:38:34 +00004547static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4548 ArrayRef<TypeSourceInfo *> Args,
4549 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004550 if (Kind <= UTT_Last)
4551 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4552
Alp Tokercbb90342013-12-13 20:49:58 +00004553 if (Kind <= BTT_Last)
4554 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4555 Args[1]->getType(), RParenLoc);
4556
Douglas Gregor29c42f22012-02-24 07:38:34 +00004557 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004558 case clang::TT_IsConstructible:
4559 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004560 case clang::TT_IsTriviallyConstructible: {
4561 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004562 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004563 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004564 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004565 // definition for is_constructible, as defined below, is known to call
4566 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004567 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004568 // The predicate condition for a template specialization
4569 // is_constructible<T, Args...> shall be satisfied if and only if the
4570 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004571 // variable t:
4572 //
4573 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004574 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004575
4576 // Precondition: T and all types in the parameter pack Args shall be
4577 // complete types, (possibly cv-qualified) void, or arrays of
4578 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004579 for (const auto *TSI : Args) {
4580 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004581 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004582 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004583
Simon Pilgrim75c26882016-09-30 14:25:09 +00004584 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004585 diag::err_incomplete_type_used_in_type_trait_expr))
4586 return false;
4587 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004588
David Majnemer9658ecc2015-11-13 05:32:43 +00004589 // Make sure the first argument is not incomplete nor a function type.
4590 QualType T = Args[0]->getType();
4591 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004592 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004593
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004594 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004595 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004596 if (RD && RD->isAbstract())
4597 return false;
4598
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004599 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4600 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004601 ArgExprs.reserve(Args.size() - 1);
4602 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004603 QualType ArgTy = Args[I]->getType();
4604 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4605 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004606 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004607 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4608 ArgTy.getNonLValueExprType(S.Context),
4609 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004610 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004611 for (Expr &E : OpaqueArgExprs)
4612 ArgExprs.push_back(&E);
4613
Simon Pilgrim75c26882016-09-30 14:25:09 +00004614 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004615 // trap at translation unit scope.
4616 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4617 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4618 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4619 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4620 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4621 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004622 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004623 if (Init.Failed())
4624 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004625
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004626 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004627 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4628 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004629
Alp Toker73287bf2014-01-20 00:24:09 +00004630 if (Kind == clang::TT_IsConstructible)
4631 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004632
Alp Toker73287bf2014-01-20 00:24:09 +00004633 if (Kind == clang::TT_IsNothrowConstructible)
4634 return S.canThrow(Result.get()) == CT_Cannot;
4635
4636 if (Kind == clang::TT_IsTriviallyConstructible) {
4637 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4638 // lifetime, this is a non-trivial construction.
4639 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004640 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004641 return false;
4642
4643 // The initialization succeeded; now make sure there are no non-trivial
4644 // calls.
4645 return !Result.get()->hasNonTrivialCall(S.Context);
4646 }
4647
4648 llvm_unreachable("unhandled type trait");
4649 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004650 }
Alp Tokercbb90342013-12-13 20:49:58 +00004651 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004652 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004653
Douglas Gregor29c42f22012-02-24 07:38:34 +00004654 return false;
4655}
4656
Simon Pilgrim75c26882016-09-30 14:25:09 +00004657ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4658 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004659 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004660 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004661
Alp Toker95e7ff22014-01-01 05:57:51 +00004662 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4663 *this, Kind, KWLoc, Args[0]->getType()))
4664 return ExprError();
4665
Douglas Gregor29c42f22012-02-24 07:38:34 +00004666 bool Dependent = false;
4667 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4668 if (Args[I]->getType()->isDependentType()) {
4669 Dependent = true;
4670 break;
4671 }
4672 }
Alp Tokercbb90342013-12-13 20:49:58 +00004673
4674 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004675 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004676 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4677
4678 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4679 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004680}
4681
Alp Toker88f64e62013-12-13 21:19:30 +00004682ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4683 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004684 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004685 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004686 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004687
Douglas Gregor29c42f22012-02-24 07:38:34 +00004688 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4689 TypeSourceInfo *TInfo;
4690 QualType T = GetTypeFromParser(Args[I], &TInfo);
4691 if (!TInfo)
4692 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004693
4694 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004695 }
Alp Tokercbb90342013-12-13 20:49:58 +00004696
Douglas Gregor29c42f22012-02-24 07:38:34 +00004697 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4698}
4699
Alp Tokercbb90342013-12-13 20:49:58 +00004700static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4701 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004702 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4703 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004704
4705 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004706 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004707 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004708 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004709 // Base and Derived are not unions and name the same class type without
4710 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004711
John McCall388ef532011-01-28 22:02:36 +00004712 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4713 if (!lhsRecord) return false;
4714
4715 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4716 if (!rhsRecord) return false;
4717
4718 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4719 == (lhsRecord == rhsRecord));
4720
4721 if (lhsRecord == rhsRecord)
4722 return !lhsRecord->getDecl()->isUnion();
4723
4724 // C++0x [meta.rel]p2:
4725 // If Base and Derived are class types and are different types
4726 // (ignoring possible cv-qualifiers) then Derived shall be a
4727 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004728 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004729 diag::err_incomplete_type_used_in_type_trait_expr))
4730 return false;
4731
4732 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4733 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4734 }
John Wiegley65497cc2011-04-27 23:09:49 +00004735 case BTT_IsSame:
4736 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004737 case BTT_TypeCompatible:
4738 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4739 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004740 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004741 case BTT_IsConvertibleTo: {
4742 // C++0x [meta.rel]p4:
4743 // Given the following function prototype:
4744 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004745 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004746 // typename add_rvalue_reference<T>::type create();
4747 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004748 // the predicate condition for a template specialization
4749 // is_convertible<From, To> shall be satisfied if and only if
4750 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004751 // well-formed, including any implicit conversions to the return
4752 // type of the function:
4753 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004754 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004755 // return create<From>();
4756 // }
4757 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004758 // Access checking is performed as if in a context unrelated to To and
4759 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004760 // of the return-statement (including conversions to the return type)
4761 // is considered.
4762 //
4763 // We model the initialization as a copy-initialization of a temporary
4764 // of the appropriate type, which for this expression is identical to the
4765 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004766
4767 // Functions aren't allowed to return function or array types.
4768 if (RhsT->isFunctionType() || RhsT->isArrayType())
4769 return false;
4770
4771 // A return statement in a void function must have void type.
4772 if (RhsT->isVoidType())
4773 return LhsT->isVoidType();
4774
4775 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004776 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004777 return false;
4778
4779 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004780 if (LhsT->isObjectType() || LhsT->isFunctionType())
4781 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004782
4783 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004784 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004785 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004786 Expr::getValueKindForType(LhsT));
4787 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004788 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004789 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004790
4791 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004792 // trap at translation unit scope.
4793 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004794 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4795 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004796 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004797 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004798 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004799
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004800 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004801 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4802 }
Alp Toker73287bf2014-01-20 00:24:09 +00004803
David Majnemerb3d96882016-05-23 17:21:55 +00004804 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004805 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004806 case BTT_IsTriviallyAssignable: {
4807 // C++11 [meta.unary.prop]p3:
4808 // is_trivially_assignable is defined as:
4809 // is_assignable<T, U>::value is true and the assignment, as defined by
4810 // is_assignable, is known to call no operation that is not trivial
4811 //
4812 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004813 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004814 // treated as an unevaluated operand (Clause 5).
4815 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004816 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004817 // void, or arrays of unknown bound.
4818 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004819 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004820 diag::err_incomplete_type_used_in_type_trait_expr))
4821 return false;
4822 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004823 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004824 diag::err_incomplete_type_used_in_type_trait_expr))
4825 return false;
4826
4827 // cv void is never assignable.
4828 if (LhsT->isVoidType() || RhsT->isVoidType())
4829 return false;
4830
Simon Pilgrim75c26882016-09-30 14:25:09 +00004831 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004832 // declval<U>().
4833 if (LhsT->isObjectType() || LhsT->isFunctionType())
4834 LhsT = Self.Context.getRValueReferenceType(LhsT);
4835 if (RhsT->isObjectType() || RhsT->isFunctionType())
4836 RhsT = Self.Context.getRValueReferenceType(RhsT);
4837 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4838 Expr::getValueKindForType(LhsT));
4839 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4840 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004841
4842 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004843 // trap at translation unit scope.
4844 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4845 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4846 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004847 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4848 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004849 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4850 return false;
4851
David Majnemerb3d96882016-05-23 17:21:55 +00004852 if (BTT == BTT_IsAssignable)
4853 return true;
4854
Alp Toker73287bf2014-01-20 00:24:09 +00004855 if (BTT == BTT_IsNothrowAssignable)
4856 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004857
Alp Toker73287bf2014-01-20 00:24:09 +00004858 if (BTT == BTT_IsTriviallyAssignable) {
4859 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4860 // lifetime, this is a non-trivial assignment.
4861 if (Self.getLangOpts().ObjCAutoRefCount &&
4862 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4863 return false;
4864
4865 return !Result.get()->hasNonTrivialCall(Self.Context);
4866 }
4867
4868 llvm_unreachable("unhandled type trait");
4869 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004870 }
Alp Tokercbb90342013-12-13 20:49:58 +00004871 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004872 }
4873 llvm_unreachable("Unknown type trait or not implemented");
4874}
4875
John Wiegley6242b6a2011-04-28 00:16:57 +00004876ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4877 SourceLocation KWLoc,
4878 ParsedType Ty,
4879 Expr* DimExpr,
4880 SourceLocation RParen) {
4881 TypeSourceInfo *TSInfo;
4882 QualType T = GetTypeFromParser(Ty, &TSInfo);
4883 if (!TSInfo)
4884 TSInfo = Context.getTrivialTypeSourceInfo(T);
4885
4886 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4887}
4888
4889static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4890 QualType T, Expr *DimExpr,
4891 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004892 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004893
4894 switch(ATT) {
4895 case ATT_ArrayRank:
4896 if (T->isArrayType()) {
4897 unsigned Dim = 0;
4898 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4899 ++Dim;
4900 T = AT->getElementType();
4901 }
4902 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004903 }
John Wiegleyd3522222011-04-28 02:06:46 +00004904 return 0;
4905
John Wiegley6242b6a2011-04-28 00:16:57 +00004906 case ATT_ArrayExtent: {
4907 llvm::APSInt Value;
4908 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004909 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004910 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004911 false).isInvalid())
4912 return 0;
4913 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004914 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4915 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004916 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004917 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004918 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004919
4920 if (T->isArrayType()) {
4921 unsigned D = 0;
4922 bool Matched = false;
4923 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4924 if (Dim == D) {
4925 Matched = true;
4926 break;
4927 }
4928 ++D;
4929 T = AT->getElementType();
4930 }
4931
John Wiegleyd3522222011-04-28 02:06:46 +00004932 if (Matched && T->isArrayType()) {
4933 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4934 return CAT->getSize().getLimitedValue();
4935 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004936 }
John Wiegleyd3522222011-04-28 02:06:46 +00004937 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004938 }
4939 }
4940 llvm_unreachable("Unknown type trait or not implemented");
4941}
4942
4943ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4944 SourceLocation KWLoc,
4945 TypeSourceInfo *TSInfo,
4946 Expr* DimExpr,
4947 SourceLocation RParen) {
4948 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004949
Chandler Carruthc5276e52011-05-01 08:48:21 +00004950 // FIXME: This should likely be tracked as an APInt to remove any host
4951 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004952 uint64_t Value = 0;
4953 if (!T->isDependentType())
4954 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4955
Chandler Carruthc5276e52011-05-01 08:48:21 +00004956 // While the specification for these traits from the Embarcadero C++
4957 // compiler's documentation says the return type is 'unsigned int', Clang
4958 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4959 // compiler, there is no difference. On several other platforms this is an
4960 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004961 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4962 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004963}
4964
John Wiegleyf9f65842011-04-25 06:54:41 +00004965ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004966 SourceLocation KWLoc,
4967 Expr *Queried,
4968 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004969 // If error parsing the expression, ignore.
4970 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004971 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004972
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004973 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004974
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004975 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004976}
4977
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004978static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4979 switch (ET) {
4980 case ET_IsLValueExpr: return E->isLValue();
4981 case ET_IsRValueExpr: return E->isRValue();
4982 }
4983 llvm_unreachable("Expression trait not covered by switch");
4984}
4985
John Wiegleyf9f65842011-04-25 06:54:41 +00004986ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004987 SourceLocation KWLoc,
4988 Expr *Queried,
4989 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004990 if (Queried->isTypeDependent()) {
4991 // Delay type-checking for type-dependent expressions.
4992 } else if (Queried->getType()->isPlaceholderType()) {
4993 ExprResult PE = CheckPlaceholderExpr(Queried);
4994 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004995 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004996 }
4997
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004998 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004999
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005000 return new (Context)
5001 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005002}
5003
Richard Trieu82402a02011-09-15 21:56:47 +00005004QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005005 ExprValueKind &VK,
5006 SourceLocation Loc,
5007 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005008 assert(!LHS.get()->getType()->isPlaceholderType() &&
5009 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005010 "placeholders should have been weeded out by now");
5011
Richard Smith4baaa5a2016-12-03 01:14:32 +00005012 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5013 // temporary materialization conversion otherwise.
5014 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005015 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005016 else if (LHS.get()->isRValue())
5017 LHS = TemporaryMaterializationConversion(LHS.get());
5018 if (LHS.isInvalid())
5019 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005020
5021 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005022 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005023 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005024
Sebastian Redl5822f082009-02-07 20:10:22 +00005025 const char *OpSpelling = isIndirect ? "->*" : ".*";
5026 // C++ 5.5p2
5027 // The binary operator .* [p3: ->*] binds its second operand, which shall
5028 // be of type "pointer to member of T" (where T is a completely-defined
5029 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005030 QualType RHSType = RHS.get()->getType();
5031 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005032 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005033 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005034 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005035 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005036 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005037
Sebastian Redl5822f082009-02-07 20:10:22 +00005038 QualType Class(MemPtr->getClass(), 0);
5039
Douglas Gregord07ba342010-10-13 20:41:14 +00005040 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5041 // member pointer points must be completely-defined. However, there is no
5042 // reason for this semantic distinction, and the rule is not enforced by
5043 // other compilers. Therefore, we do not check this property, as it is
5044 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005045
Sebastian Redl5822f082009-02-07 20:10:22 +00005046 // C++ 5.5p2
5047 // [...] to its first operand, which shall be of class T or of a class of
5048 // which T is an unambiguous and accessible base class. [p3: a pointer to
5049 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005050 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005051 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005052 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5053 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005054 else {
5055 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005056 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005057 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005058 return QualType();
5059 }
5060 }
5061
Richard Trieu82402a02011-09-15 21:56:47 +00005062 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005063 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005064 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5065 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005066 return QualType();
5067 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005068
Richard Smith0f59cb32015-12-18 21:45:41 +00005069 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005070 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005071 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005072 return QualType();
5073 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005074
5075 CXXCastPath BasePath;
5076 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5077 SourceRange(LHS.get()->getLocStart(),
5078 RHS.get()->getLocEnd()),
5079 &BasePath))
5080 return QualType();
5081
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005082 // Cast LHS to type of use.
5083 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005084 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005085 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005086 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005087 }
5088
Richard Trieu82402a02011-09-15 21:56:47 +00005089 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005090 // Diagnose use of pointer-to-member type which when used as
5091 // the functional cast in a pointer-to-member expression.
5092 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5093 return QualType();
5094 }
John McCall7decc9e2010-11-18 06:31:45 +00005095
Sebastian Redl5822f082009-02-07 20:10:22 +00005096 // C++ 5.5p2
5097 // The result is an object or a function of the type specified by the
5098 // second operand.
5099 // The cv qualifiers are the union of those in the pointer and the left side,
5100 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005101 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005102 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005103
Douglas Gregor1d042092011-01-26 16:40:18 +00005104 // C++0x [expr.mptr.oper]p6:
5105 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106 // ill-formed if the second operand is a pointer to member function with
5107 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5108 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005109 // is a pointer to member function with ref-qualifier &&.
5110 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5111 switch (Proto->getRefQualifier()) {
5112 case RQ_None:
5113 // Do nothing
5114 break;
5115
5116 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005117 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005118 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005119 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005120 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005121
Douglas Gregor1d042092011-01-26 16:40:18 +00005122 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005123 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005124 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005125 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005126 break;
5127 }
5128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005129
John McCall7decc9e2010-11-18 06:31:45 +00005130 // C++ [expr.mptr.oper]p6:
5131 // The result of a .* expression whose second operand is a pointer
5132 // to a data member is of the same value category as its
5133 // first operand. The result of a .* expression whose second
5134 // operand is a pointer to a member function is a prvalue. The
5135 // result of an ->* expression is an lvalue if its second operand
5136 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005137 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005138 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005139 return Context.BoundMemberTy;
5140 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005141 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005142 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005143 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005144 }
John McCall7decc9e2010-11-18 06:31:45 +00005145
Sebastian Redl5822f082009-02-07 20:10:22 +00005146 return Result;
5147}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005148
Richard Smith2414bca2016-04-25 19:30:37 +00005149/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005150///
5151/// This is part of the parameter validation for the ? operator. If either
5152/// value operand is a class type, the two operands are attempted to be
5153/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005154/// It returns true if the program is ill-formed and has already been diagnosed
5155/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005156static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5157 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005158 bool &HaveConversion,
5159 QualType &ToType) {
5160 HaveConversion = false;
5161 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005162
5163 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005164 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005165 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005166 // The process for determining whether an operand expression E1 of type T1
5167 // can be converted to match an operand expression E2 of type T2 is defined
5168 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005169 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5170 // implicitly converted to type "lvalue reference to T2", subject to the
5171 // constraint that in the conversion the reference must bind directly to
5172 // an lvalue.
5173 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5174 // implicitly conveted to the type "rvalue reference to R2", subject to
5175 // the constraint that the reference must bind directly.
5176 if (To->isLValue() || To->isXValue()) {
5177 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5178 : Self.Context.getRValueReferenceType(ToType);
5179
Douglas Gregor838fcc32010-03-26 20:14:36 +00005180 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005182 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005183 if (InitSeq.isDirectReferenceBinding()) {
5184 ToType = T;
5185 HaveConversion = true;
5186 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005188
Douglas Gregor838fcc32010-03-26 20:14:36 +00005189 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005190 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005191 }
John McCall65eb8792010-02-25 01:37:24 +00005192
Sebastian Redl1a99f442009-04-16 17:51:27 +00005193 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5194 // -- if E1 and E2 have class type, and the underlying class types are
5195 // the same or one is a base class of the other:
5196 QualType FTy = From->getType();
5197 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005198 const RecordType *FRec = FTy->getAs<RecordType>();
5199 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005201 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5202 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5203 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005204 // E1 can be converted to match E2 if the class of T2 is the
5205 // same type as, or a base class of, the class of T1, and
5206 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005207 if (FRec == TRec || FDerivedFromT) {
5208 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005209 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005210 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005211 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005212 HaveConversion = true;
5213 return false;
5214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215
Douglas Gregor838fcc32010-03-26 20:14:36 +00005216 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005217 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005220
Douglas Gregor838fcc32010-03-26 20:14:36 +00005221 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005223
Douglas Gregor838fcc32010-03-26 20:14:36 +00005224 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5225 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005227 // an rvalue).
5228 //
5229 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5230 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005231 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005232
Douglas Gregor838fcc32010-03-26 20:14:36 +00005233 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005234 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005235 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005236 ToType = TTy;
5237 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005238 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005239
Sebastian Redl1a99f442009-04-16 17:51:27 +00005240 return false;
5241}
5242
5243/// \brief Try to find a common type for two according to C++0x 5.16p5.
5244///
5245/// This is part of the parameter validation for the ? operator. If either
5246/// value operand is a class type, overload resolution is used to find a
5247/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005248static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005249 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005250 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005251 OverloadCandidateSet CandidateSet(QuestionLoc,
5252 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005253 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005254 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005255
5256 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005257 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005258 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005259 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005260 ExprResult LHSRes =
5261 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5262 Best->Conversions[0], Sema::AA_Converting);
5263 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005264 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005265 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005266
5267 ExprResult RHSRes =
5268 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5269 Best->Conversions[1], Sema::AA_Converting);
5270 if (RHSRes.isInvalid())
5271 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005272 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005273 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005274 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005275 return false;
John Wiegley01296292011-04-08 18:41:53 +00005276 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005277
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005278 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005279
5280 // Emit a better diagnostic if one of the expressions is a null pointer
5281 // constant and the other is a pointer type. In this case, the user most
5282 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005283 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005284 return true;
5285
5286 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005287 << LHS.get()->getType() << RHS.get()->getType()
5288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005289 return true;
5290
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005291 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005292 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005293 << LHS.get()->getType() << RHS.get()->getType()
5294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005295 // FIXME: Print the possible common types by printing the return types of
5296 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005297 break;
5298
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005299 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005300 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005301 }
5302 return true;
5303}
5304
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005305/// \brief Perform an "extended" implicit conversion as returned by
5306/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005307static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005308 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005309 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005310 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005311 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005312 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005313 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005314 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005315 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316
John Wiegley01296292011-04-08 18:41:53 +00005317 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005318 return false;
5319}
5320
Sebastian Redl1a99f442009-04-16 17:51:27 +00005321/// \brief Check the operands of ?: under C++ semantics.
5322///
5323/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5324/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005325QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5326 ExprResult &RHS, ExprValueKind &VK,
5327 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005328 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005329 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5330 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005331
Richard Smith45edb702012-08-07 22:06:48 +00005332 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005333 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005334 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005335 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005336 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005337 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005338 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005339 }
5340
John McCall7decc9e2010-11-18 06:31:45 +00005341 // Assume r-value.
5342 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005343 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005344
Sebastian Redl1a99f442009-04-16 17:51:27 +00005345 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005346 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005347 return Context.DependentTy;
5348
Richard Smith45edb702012-08-07 22:06:48 +00005349 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005350 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005351 QualType LTy = LHS.get()->getType();
5352 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005353 bool LVoid = LTy->isVoidType();
5354 bool RVoid = RTy->isVoidType();
5355 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005356 // ... one of the following shall hold:
5357 // -- The second or the third operand (but not both) is a (possibly
5358 // parenthesized) throw-expression; the result is of the type
5359 // and value category of the other.
5360 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5361 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5362 if (LThrow != RThrow) {
5363 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5364 VK = NonThrow->getValueKind();
5365 // DR (no number yet): the result is a bit-field if the
5366 // non-throw-expression operand is a bit-field.
5367 OK = NonThrow->getObjectKind();
5368 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005369 }
5370
Sebastian Redl1a99f442009-04-16 17:51:27 +00005371 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005372 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005373 if (LVoid && RVoid)
5374 return Context.VoidTy;
5375
5376 // Neither holds, error.
5377 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5378 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005380 return QualType();
5381 }
5382
5383 // Neither is void.
5384
Richard Smithf2b084f2012-08-08 06:13:49 +00005385 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005386 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005387 // either has (cv) class type [...] an attempt is made to convert each of
5388 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005389 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005390 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005391 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005392 QualType L2RType, R2LType;
5393 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005394 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005395 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005396 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005397 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Sebastian Redl1a99f442009-04-16 17:51:27 +00005399 // If both can be converted, [...] the program is ill-formed.
5400 if (HaveL2R && HaveR2L) {
5401 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005402 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005403 return QualType();
5404 }
5405
5406 // If exactly one conversion is possible, that conversion is applied to
5407 // the chosen operand and the converted operands are used in place of the
5408 // original operands for the remainder of this section.
5409 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005410 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005411 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005412 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005413 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005414 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005415 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005416 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005417 }
5418 }
5419
Richard Smithf2b084f2012-08-08 06:13:49 +00005420 // C++11 [expr.cond]p3
5421 // if both are glvalues of the same value category and the same type except
5422 // for cv-qualification, an attempt is made to convert each of those
5423 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005424 // FIXME:
5425 // Resolving a defect in P0012R1: we extend this to cover all cases where
5426 // one of the operands is reference-compatible with the other, in order
5427 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005428 ExprValueKind LVK = LHS.get()->getValueKind();
5429 ExprValueKind RVK = RHS.get()->getValueKind();
5430 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005431 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005432 // DerivedToBase was already handled by the class-specific case above.
5433 // FIXME: Should we allow ObjC conversions here?
5434 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5435 if (CompareReferenceRelationship(
5436 QuestionLoc, LTy, RTy, DerivedToBase,
5437 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005438 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5439 // [...] subject to the constraint that the reference must bind
5440 // directly [...]
5441 !RHS.get()->refersToBitField() &&
5442 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005443 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005444 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005445 } else if (CompareReferenceRelationship(
5446 QuestionLoc, RTy, LTy, DerivedToBase,
5447 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005448 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5449 !LHS.get()->refersToBitField() &&
5450 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005451 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5452 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005453 }
5454 }
5455
5456 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005457 // If the second and third operands are glvalues of the same value
5458 // category and have the same type, the result is of that type and
5459 // value category and it is a bit-field if the second or the third
5460 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005461 // We only extend this to bitfields, not to the crazy other kinds of
5462 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005463 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005464 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005465 LHS.get()->isOrdinaryOrBitFieldObject() &&
5466 RHS.get()->isOrdinaryOrBitFieldObject()) {
5467 VK = LHS.get()->getValueKind();
5468 if (LHS.get()->getObjectKind() == OK_BitField ||
5469 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005470 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005471
5472 // If we have function pointer types, unify them anyway to unify their
5473 // exception specifications, if any.
5474 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5475 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005476 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005477 /*ConvertArgs*/false);
5478 LTy = Context.getQualifiedType(LTy, Qs);
5479
5480 assert(!LTy.isNull() && "failed to find composite pointer type for "
5481 "canonically equivalent function ptr types");
5482 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5483 }
5484
John McCall7decc9e2010-11-18 06:31:45 +00005485 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005486 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005487
Richard Smithf2b084f2012-08-08 06:13:49 +00005488 // C++11 [expr.cond]p5
5489 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005490 // do not have the same type, and either has (cv) class type, ...
5491 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5492 // ... overload resolution is used to determine the conversions (if any)
5493 // to be applied to the operands. If the overload resolution fails, the
5494 // program is ill-formed.
5495 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5496 return QualType();
5497 }
5498
Richard Smithf2b084f2012-08-08 06:13:49 +00005499 // C++11 [expr.cond]p6
5500 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005501 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005502 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5503 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005504 if (LHS.isInvalid() || RHS.isInvalid())
5505 return QualType();
5506 LTy = LHS.get()->getType();
5507 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005508
5509 // After those conversions, one of the following shall hold:
5510 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005511 // is of that type. If the operands have class type, the result
5512 // is a prvalue temporary of the result type, which is
5513 // copy-initialized from either the second operand or the third
5514 // operand depending on the value of the first operand.
5515 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5516 if (LTy->isRecordType()) {
5517 // The operands have class type. Make a temporary copy.
5518 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005519
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005520 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5521 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005522 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005523 if (LHSCopy.isInvalid())
5524 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525
5526 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5527 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005528 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005529 if (RHSCopy.isInvalid())
5530 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531
John Wiegley01296292011-04-08 18:41:53 +00005532 LHS = LHSCopy;
5533 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005534 }
5535
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005536 // If we have function pointer types, unify them anyway to unify their
5537 // exception specifications, if any.
5538 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5539 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5540 assert(!LTy.isNull() && "failed to find composite pointer type for "
5541 "canonically equivalent function ptr types");
5542 }
5543
Sebastian Redl1a99f442009-04-16 17:51:27 +00005544 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005545 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005546
Douglas Gregor46188682010-05-18 22:42:18 +00005547 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005548 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005549 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5550 /*AllowBothBool*/true,
5551 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005552
Sebastian Redl1a99f442009-04-16 17:51:27 +00005553 // -- The second and third operands have arithmetic or enumeration type;
5554 // the usual arithmetic conversions are performed to bring them to a
5555 // common type, and the result is of that type.
5556 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005557 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005558 if (LHS.isInvalid() || RHS.isInvalid())
5559 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005560 if (ResTy.isNull()) {
5561 Diag(QuestionLoc,
5562 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5563 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5564 return QualType();
5565 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005566
5567 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5568 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5569
5570 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005571 }
5572
5573 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005574 // type and the other is a null pointer constant, or both are null
5575 // pointer constants, at least one of which is non-integral; pointer
5576 // conversions and qualification conversions are performed to bring them
5577 // to their composite pointer type. The result is of the composite
5578 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005579 // -- The second and third operands have pointer to member type, or one has
5580 // pointer to member type and the other is a null pointer constant;
5581 // pointer to member conversions and qualification conversions are
5582 // performed to bring them to a common type, whose cv-qualification
5583 // shall match the cv-qualification of either the second or the third
5584 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005585 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5586 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005587 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor697a3912010-04-01 22:47:07 +00005589 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005590 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5591 if (!Composite.isNull())
5592 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005593
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005594 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005595 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005596 return QualType();
5597
Sebastian Redl1a99f442009-04-16 17:51:27 +00005598 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005599 << LHS.get()->getType() << RHS.get()->getType()
5600 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005601 return QualType();
5602}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005603
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005604static FunctionProtoType::ExceptionSpecInfo
5605mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5606 FunctionProtoType::ExceptionSpecInfo ESI2,
5607 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5608 ExceptionSpecificationType EST1 = ESI1.Type;
5609 ExceptionSpecificationType EST2 = ESI2.Type;
5610
5611 // If either of them can throw anything, that is the result.
5612 if (EST1 == EST_None) return ESI1;
5613 if (EST2 == EST_None) return ESI2;
5614 if (EST1 == EST_MSAny) return ESI1;
5615 if (EST2 == EST_MSAny) return ESI2;
5616
5617 // If either of them is non-throwing, the result is the other.
5618 if (EST1 == EST_DynamicNone) return ESI2;
5619 if (EST2 == EST_DynamicNone) return ESI1;
5620 if (EST1 == EST_BasicNoexcept) return ESI2;
5621 if (EST2 == EST_BasicNoexcept) return ESI1;
5622
5623 // If either of them is a non-value-dependent computed noexcept, that
5624 // determines the result.
5625 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5626 !ESI2.NoexceptExpr->isValueDependent())
5627 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5628 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5629 !ESI1.NoexceptExpr->isValueDependent())
5630 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5631 // If we're left with value-dependent computed noexcept expressions, we're
5632 // stuck. Before C++17, we can just drop the exception specification entirely,
5633 // since it's not actually part of the canonical type. And this should never
5634 // happen in C++17, because it would mean we were computing the composite
5635 // pointer type of dependent types, which should never happen.
5636 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5637 assert(!S.getLangOpts().CPlusPlus1z &&
5638 "computing composite pointer type of dependent types");
5639 return FunctionProtoType::ExceptionSpecInfo();
5640 }
5641
5642 // Switch over the possibilities so that people adding new values know to
5643 // update this function.
5644 switch (EST1) {
5645 case EST_None:
5646 case EST_DynamicNone:
5647 case EST_MSAny:
5648 case EST_BasicNoexcept:
5649 case EST_ComputedNoexcept:
5650 llvm_unreachable("handled above");
5651
5652 case EST_Dynamic: {
5653 // This is the fun case: both exception specifications are dynamic. Form
5654 // the union of the two lists.
5655 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5656 llvm::SmallPtrSet<QualType, 8> Found;
5657 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5658 for (QualType E : Exceptions)
5659 if (Found.insert(S.Context.getCanonicalType(E)).second)
5660 ExceptionTypeStorage.push_back(E);
5661
5662 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5663 Result.Exceptions = ExceptionTypeStorage;
5664 return Result;
5665 }
5666
5667 case EST_Unevaluated:
5668 case EST_Uninstantiated:
5669 case EST_Unparsed:
5670 llvm_unreachable("shouldn't see unresolved exception specifications here");
5671 }
5672
5673 llvm_unreachable("invalid ExceptionSpecificationType");
5674}
5675
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005676/// \brief Find a merged pointer type and convert the two expressions to it.
5677///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005678/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005679/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005680/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005681/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005682///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005683/// \param Loc The location of the operator requiring these two expressions to
5684/// be converted to the composite pointer type.
5685///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005686/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005687QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005688 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005689 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005690 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005691
5692 // C++1z [expr]p14:
5693 // The composite pointer type of two operands p1 and p2 having types T1
5694 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005695 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005696
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005697 // where at least one is a pointer or pointer to member type or
5698 // std::nullptr_t is:
5699 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5700 T1->isNullPtrType();
5701 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5702 T2->isNullPtrType();
5703 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005704 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005705
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005706 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5707 // This can't actually happen, following the standard, but we also use this
5708 // to implement the end of [expr.conv], which hits this case.
5709 //
5710 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5711 if (T1IsPointerLike &&
5712 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005713 if (ConvertArgs)
5714 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5715 ? CK_NullToMemberPointer
5716 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005717 return T1;
5718 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005719 if (T2IsPointerLike &&
5720 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005721 if (ConvertArgs)
5722 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5723 ? CK_NullToMemberPointer
5724 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005725 return T2;
5726 }
Mike Stump11289f42009-09-09 15:08:12 +00005727
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005728 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005729 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005730 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005731 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5732 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005733
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005734 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5735 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5736 // the union of cv1 and cv2;
5737 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5738 // "pointer to function", where the function types are otherwise the same,
5739 // "pointer to function";
5740 // FIXME: This rule is defective: it should also permit removing noexcept
5741 // from a pointer to member function. As a Clang extension, we also
5742 // permit removing 'noreturn', so we generalize this rule to;
5743 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5744 // "pointer to member function" and the pointee types can be unified
5745 // by a function pointer conversion, that conversion is applied
5746 // before checking the following rules.
5747 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5748 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5749 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5750 // respectively;
5751 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5752 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5753 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5754 // T1 or the cv-combined type of T1 and T2, respectively;
5755 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5756 // T2;
5757 //
5758 // If looked at in the right way, these bullets all do the same thing.
5759 // What we do here is, we build the two possible cv-combined types, and try
5760 // the conversions in both directions. If only one works, or if the two
5761 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005762 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005763 //
5764 // Note that this will fail to find a composite pointer type for "pointer
5765 // to void" and "pointer to function". We can't actually perform the final
5766 // conversion in this case, even though a composite pointer type formally
5767 // exists.
5768 SmallVector<unsigned, 4> QualifierUnion;
5769 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005770 QualType Composite1 = T1;
5771 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005773 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005774 const PointerType *Ptr1, *Ptr2;
5775 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5776 (Ptr2 = Composite2->getAs<PointerType>())) {
5777 Composite1 = Ptr1->getPointeeType();
5778 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005780 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005782 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005783 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005784
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005785 QualifierUnion.push_back(
5786 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005787 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005788 continue;
5789 }
Mike Stump11289f42009-09-09 15:08:12 +00005790
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005791 const MemberPointerType *MemPtr1, *MemPtr2;
5792 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5793 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5794 Composite1 = MemPtr1->getPointeeType();
5795 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005796
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005797 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005798 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005799 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005800 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005801
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005802 QualifierUnion.push_back(
5803 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5804 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5805 MemPtr2->getClass()));
5806 continue;
5807 }
Mike Stump11289f42009-09-09 15:08:12 +00005808
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005809 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005810
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005811 // Cannot unwrap any more types.
5812 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005813 }
Mike Stump11289f42009-09-09 15:08:12 +00005814
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005815 // Apply the function pointer conversion to unify the types. We've already
5816 // unwrapped down to the function types, and we want to merge rather than
5817 // just convert, so do this ourselves rather than calling
5818 // IsFunctionConversion.
5819 //
5820 // FIXME: In order to match the standard wording as closely as possible, we
5821 // currently only do this under a single level of pointers. Ideally, we would
5822 // allow this in general, and set NeedConstBefore to the relevant depth on
5823 // the side(s) where we changed anything.
5824 if (QualifierUnion.size() == 1) {
5825 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5826 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5827 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5828 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5829
5830 // The result is noreturn if both operands are.
5831 bool Noreturn =
5832 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5833 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5834 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5835
5836 // The result is nothrow if both operands are.
5837 SmallVector<QualType, 8> ExceptionTypeStorage;
5838 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5839 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5840 ExceptionTypeStorage);
5841
5842 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5843 FPT1->getParamTypes(), EPI1);
5844 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5845 FPT2->getParamTypes(), EPI2);
5846 }
5847 }
5848 }
5849
Richard Smith5e9746f2016-10-21 22:00:42 +00005850 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005851 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005853 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005854 for (unsigned I = 0; I != NeedConstBefore; ++I)
5855 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005856 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005858
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005859 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005860 auto MOC = MemberOfClass.rbegin();
5861 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5862 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5863 auto Classes = *MOC++;
5864 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005865 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005866 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005867 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005868 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005869 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005870 } else {
5871 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005872 Composite1 =
5873 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5874 Composite2 =
5875 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005876 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005877 }
5878
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005879 struct Conversion {
5880 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005881 Expr *&E1, *&E2;
5882 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005883 InitializedEntity Entity;
5884 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005885 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005886 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005887
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005888 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5889 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005890 : S(S), E1(E1), E2(E2), Composite(Composite),
5891 Entity(InitializedEntity::InitializeTemporary(Composite)),
5892 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5893 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5894 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005895
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005896 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005897 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5898 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005899 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005900 E1 = E1Result.getAs<Expr>();
5901
5902 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5903 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005904 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005905 E2 = E2Result.getAs<Expr>();
5906
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005907 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005908 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005909 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005910
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005911 // Try to convert to each composite pointer type.
5912 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005913 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5914 if (ConvertArgs && C1.perform())
5915 return QualType();
5916 return C1.Composite;
5917 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005918 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005919
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005920 if (C1.Viable == C2.Viable) {
5921 // Either Composite1 and Composite2 are viable and are different, or
5922 // neither is viable.
5923 // FIXME: How both be viable and different?
5924 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005925 }
5926
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005927 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005928 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5929 return QualType();
5930
5931 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005932}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005933
John McCalldadc5752010-08-24 06:29:42 +00005934ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005935 if (!E)
5936 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
John McCall31168b02011-06-15 23:02:42 +00005938 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5939
5940 // If the result is a glvalue, we shouldn't bind it.
5941 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005942 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005943
John McCall31168b02011-06-15 23:02:42 +00005944 // In ARC, calls that return a retainable type can return retained,
5945 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005946 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005947 E->getType()->isObjCRetainableType()) {
5948
5949 bool ReturnsRetained;
5950
5951 // For actual calls, we compute this by examining the type of the
5952 // called value.
5953 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5954 Expr *Callee = Call->getCallee()->IgnoreParens();
5955 QualType T = Callee->getType();
5956
5957 if (T == Context.BoundMemberTy) {
5958 // Handle pointer-to-members.
5959 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5960 T = BinOp->getRHS()->getType();
5961 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5962 T = Mem->getMemberDecl()->getType();
5963 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005964
John McCall31168b02011-06-15 23:02:42 +00005965 if (const PointerType *Ptr = T->getAs<PointerType>())
5966 T = Ptr->getPointeeType();
5967 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5968 T = Ptr->getPointeeType();
5969 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5970 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005971
John McCall31168b02011-06-15 23:02:42 +00005972 const FunctionType *FTy = T->getAs<FunctionType>();
5973 assert(FTy && "call to value not of function type?");
5974 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5975
5976 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5977 // type always produce a +1 object.
5978 } else if (isa<StmtExpr>(E)) {
5979 ReturnsRetained = true;
5980
Ted Kremeneke65b0862012-03-06 20:05:56 +00005981 // We hit this case with the lambda conversion-to-block optimization;
5982 // we don't want any extra casts here.
5983 } else if (isa<CastExpr>(E) &&
5984 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005985 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005986
John McCall31168b02011-06-15 23:02:42 +00005987 // For message sends and property references, we try to find an
5988 // actual method. FIXME: we should infer retention by selector in
5989 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005990 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005991 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005992 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5993 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005994 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5995 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005996 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5997 D = ArrayLit->getArrayWithObjectsMethod();
5998 } else if (ObjCDictionaryLiteral *DictLit
5999 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6000 D = DictLit->getDictWithObjectsMethod();
6001 }
John McCall31168b02011-06-15 23:02:42 +00006002
6003 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006004
6005 // Don't do reclaims on performSelector calls; despite their
6006 // return type, the invoked method doesn't necessarily actually
6007 // return an object.
6008 if (!ReturnsRetained &&
6009 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006010 return E;
John McCall31168b02011-06-15 23:02:42 +00006011 }
6012
John McCall16de4d22011-11-14 19:53:16 +00006013 // Don't reclaim an object of Class type.
6014 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006015 return E;
John McCall16de4d22011-11-14 19:53:16 +00006016
Tim Shen4a05bb82016-06-21 20:29:17 +00006017 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006018
John McCall2d637d22011-09-10 06:18:15 +00006019 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6020 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006021 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6022 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006023 }
6024
David Blaikiebbafb8a2012-03-11 07:00:24 +00006025 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006026 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006027
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006028 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6029 // a fast path for the common case that the type is directly a RecordType.
6030 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006031 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006032 while (!RT) {
6033 switch (T->getTypeClass()) {
6034 case Type::Record:
6035 RT = cast<RecordType>(T);
6036 break;
6037 case Type::ConstantArray:
6038 case Type::IncompleteArray:
6039 case Type::VariableArray:
6040 case Type::DependentSizedArray:
6041 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6042 break;
6043 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006044 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006045 }
6046 }
Mike Stump11289f42009-09-09 15:08:12 +00006047
Richard Smithfd555f62012-02-22 02:04:18 +00006048 // That should be enough to guarantee that this type is complete, if we're
6049 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006050 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006051 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006052 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006053
6054 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006055 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006056
John McCall31168b02011-06-15 23:02:42 +00006057 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006058 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006059 CheckDestructorAccess(E->getExprLoc(), Destructor,
6060 PDiag(diag::err_access_dtor_temp)
6061 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006062 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6063 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006064
Richard Smithfd555f62012-02-22 02:04:18 +00006065 // If destructor is trivial, we can avoid the extra copy.
6066 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006067 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006068
John McCall28fc7092011-11-10 05:35:25 +00006069 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006070 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006071 }
Richard Smitheec915d62012-02-18 04:13:32 +00006072
6073 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006074 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6075
6076 if (IsDecltype)
6077 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006079 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006080}
6081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006082ExprResult
John McCall5d413782010-12-06 08:20:24 +00006083Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006084 if (SubExpr.isInvalid())
6085 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006086
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006087 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006088}
6089
John McCall28fc7092011-11-10 05:35:25 +00006090Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006091 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006092
Eli Friedman3bda6b12012-02-02 23:15:15 +00006093 CleanupVarDeclMarking();
6094
John McCall28fc7092011-11-10 05:35:25 +00006095 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6096 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006097 assert(Cleanup.exprNeedsCleanups() ||
6098 ExprCleanupObjects.size() == FirstCleanup);
6099 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006100 return SubExpr;
6101
Craig Topper5fc8fc22014-08-27 06:28:36 +00006102 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6103 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006104
Tim Shen4a05bb82016-06-21 20:29:17 +00006105 auto *E = ExprWithCleanups::Create(
6106 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006107 DiscardCleanupsInEvaluationContext();
6108
6109 return E;
6110}
6111
John McCall5d413782010-12-06 08:20:24 +00006112Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006113 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006114
Eli Friedman3bda6b12012-02-02 23:15:15 +00006115 CleanupVarDeclMarking();
6116
Tim Shen4a05bb82016-06-21 20:29:17 +00006117 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006118 return SubStmt;
6119
6120 // FIXME: In order to attach the temporaries, wrap the statement into
6121 // a StmtExpr; currently this is only used for asm statements.
6122 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6123 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006124 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006125 SourceLocation(),
6126 SourceLocation());
6127 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6128 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006129 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006130}
6131
Richard Smithfd555f62012-02-22 02:04:18 +00006132/// Process the expression contained within a decltype. For such expressions,
6133/// certain semantic checks on temporaries are delayed until this point, and
6134/// are omitted for the 'topmost' call in the decltype expression. If the
6135/// topmost call bound a temporary, strip that temporary off the expression.
6136ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006137 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006138
6139 // C++11 [expr.call]p11:
6140 // If a function call is a prvalue of object type,
6141 // -- if the function call is either
6142 // -- the operand of a decltype-specifier, or
6143 // -- the right operand of a comma operator that is the operand of a
6144 // decltype-specifier,
6145 // a temporary object is not introduced for the prvalue.
6146
6147 // Recursively rebuild ParenExprs and comma expressions to strip out the
6148 // outermost CXXBindTemporaryExpr, if any.
6149 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6150 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6151 if (SubExpr.isInvalid())
6152 return ExprError();
6153 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006154 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006155 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006156 }
6157 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6158 if (BO->getOpcode() == BO_Comma) {
6159 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6160 if (RHS.isInvalid())
6161 return ExprError();
6162 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006163 return E;
6164 return new (Context) BinaryOperator(
6165 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6166 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00006167 }
6168 }
6169
6170 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006171 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6172 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006173 if (TopCall)
6174 E = TopCall;
6175 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006176 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006177
6178 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006179 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006180
Richard Smithf86b0ae2012-07-28 19:54:11 +00006181 // In MS mode, don't perform any extra checking of call return types within a
6182 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006183 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006184 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006185
Richard Smithfd555f62012-02-22 02:04:18 +00006186 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006187 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6188 I != N; ++I) {
6189 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006190 if (Call == TopCall)
6191 continue;
6192
David Majnemerced8bdf2015-02-25 17:36:15 +00006193 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006194 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006195 Call, Call->getDirectCallee()))
6196 return ExprError();
6197 }
6198
6199 // Now all relevant types are complete, check the destructors are accessible
6200 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006201 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6202 I != N; ++I) {
6203 CXXBindTemporaryExpr *Bind =
6204 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006205 if (Bind == TopBind)
6206 continue;
6207
6208 CXXTemporary *Temp = Bind->getTemporary();
6209
6210 CXXRecordDecl *RD =
6211 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6212 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6213 Temp->setDestructor(Destructor);
6214
Richard Smith7d847b12012-05-11 22:20:10 +00006215 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6216 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006217 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006218 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006219 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6220 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006221
6222 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006223 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006224 }
6225
6226 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006227 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006228}
6229
Richard Smith79c927b2013-11-06 19:31:51 +00006230/// Note a set of 'operator->' functions that were used for a member access.
6231static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006232 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006233 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6234 // FIXME: Make this configurable?
6235 unsigned Limit = 9;
6236 if (OperatorArrows.size() > Limit) {
6237 // Produce Limit-1 normal notes and one 'skipping' note.
6238 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6239 SkipCount = OperatorArrows.size() - (Limit - 1);
6240 }
6241
6242 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6243 if (I == SkipStart) {
6244 S.Diag(OperatorArrows[I]->getLocation(),
6245 diag::note_operator_arrows_suppressed)
6246 << SkipCount;
6247 I += SkipCount;
6248 } else {
6249 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6250 << OperatorArrows[I]->getCallResultType();
6251 ++I;
6252 }
6253 }
6254}
6255
Nico Weber964d3322015-02-16 22:35:45 +00006256ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6257 SourceLocation OpLoc,
6258 tok::TokenKind OpKind,
6259 ParsedType &ObjectType,
6260 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006261 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006262 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006263 if (Result.isInvalid()) return ExprError();
6264 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006265
John McCall526ab472011-10-25 17:37:35 +00006266 Result = CheckPlaceholderExpr(Base);
6267 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006268 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006269
John McCallb268a282010-08-23 23:25:46 +00006270 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006271 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006272 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006273 // If we have a pointer to a dependent type and are using the -> operator,
6274 // the object type is the type that the pointer points to. We might still
6275 // have enough information about that type to do something useful.
6276 if (OpKind == tok::arrow)
6277 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6278 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006279
John McCallba7bf592010-08-24 05:47:05 +00006280 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006281 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006282 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006283 }
Mike Stump11289f42009-09-09 15:08:12 +00006284
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006285 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006286 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006287 // returned, with the original second operand.
6288 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006289 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006290 bool NoArrowOperatorFound = false;
6291 bool FirstIteration = true;
6292 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006293 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006294 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006295 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006296 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006297
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006298 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006299 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6300 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006301 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006302 noteOperatorArrows(*this, OperatorArrows);
6303 Diag(OpLoc, diag::note_operator_arrow_depth)
6304 << getLangOpts().ArrowDepth;
6305 return ExprError();
6306 }
6307
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006308 Result = BuildOverloadedArrowExpr(
6309 S, Base, OpLoc,
6310 // When in a template specialization and on the first loop iteration,
6311 // potentially give the default diagnostic (with the fixit in a
6312 // separate note) instead of having the error reported back to here
6313 // and giving a diagnostic with a fixit attached to the error itself.
6314 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006315 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006316 : &NoArrowOperatorFound);
6317 if (Result.isInvalid()) {
6318 if (NoArrowOperatorFound) {
6319 if (FirstIteration) {
6320 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006321 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006322 << FixItHint::CreateReplacement(OpLoc, ".");
6323 OpKind = tok::period;
6324 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006325 }
6326 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6327 << BaseType << Base->getSourceRange();
6328 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006329 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006330 Diag(CD->getLocStart(),
6331 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006332 }
6333 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006334 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006335 }
John McCallb268a282010-08-23 23:25:46 +00006336 Base = Result.get();
6337 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006338 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006339 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006340 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006341 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006342 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6343 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006344 return ExprError();
6345 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006346 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006349 if (OpKind == tok::arrow &&
6350 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006351 BaseType = BaseType->getPointeeType();
6352 }
Mike Stump11289f42009-09-09 15:08:12 +00006353
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006354 // Objective-C properties allow "." access on Objective-C pointer types,
6355 // so adjust the base type to the object type itself.
6356 if (BaseType->isObjCObjectPointerType())
6357 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006358
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006359 // C++ [basic.lookup.classref]p2:
6360 // [...] If the type of the object expression is of pointer to scalar
6361 // type, the unqualified-id is looked up in the context of the complete
6362 // postfix-expression.
6363 //
6364 // This also indicates that we could be parsing a pseudo-destructor-name.
6365 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006366 // expressions or normal member (ivar or property) access expressions, and
6367 // it's legal for the type to be incomplete if this is a pseudo-destructor
6368 // call. We'll do more incomplete-type checks later in the lookup process,
6369 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006370 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006371 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006372 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006373 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006374 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006375 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006376 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006377 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006378 }
Mike Stump11289f42009-09-09 15:08:12 +00006379
Douglas Gregor3024f072012-04-16 07:05:22 +00006380 // The object type must be complete (or dependent), or
6381 // C++11 [expr.prim.general]p3:
6382 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006383 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006384 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006385 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006386 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006387 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006388 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006389
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006390 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006391 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006392 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006393 // type C (or of pointer to a class type C), the unqualified-id is looked
6394 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006395 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006396 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006397}
6398
Simon Pilgrim75c26882016-09-30 14:25:09 +00006399static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006400 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006401 if (Base->hasPlaceholderType()) {
6402 ExprResult result = S.CheckPlaceholderExpr(Base);
6403 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006404 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006405 }
6406 ObjectType = Base->getType();
6407
David Blaikie1d578782011-12-16 16:03:09 +00006408 // C++ [expr.pseudo]p2:
6409 // The left-hand side of the dot operator shall be of scalar type. The
6410 // left-hand side of the arrow operator shall be of pointer to scalar type.
6411 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006412 // Note that this is rather different from the normal handling for the
6413 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006414 if (OpKind == tok::arrow) {
6415 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6416 ObjectType = Ptr->getPointeeType();
6417 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006418 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006419 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6420 << ObjectType << true
6421 << FixItHint::CreateReplacement(OpLoc, ".");
6422 if (S.isSFINAEContext())
6423 return true;
6424
6425 OpKind = tok::period;
6426 }
6427 }
6428
6429 return false;
6430}
6431
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006432/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6433/// pointer objects.
6434static bool
6435canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6436 QualType DestructedType) {
6437 // If this is a record type, check if its destructor is callable.
6438 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6439 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6440 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6441 return false;
6442 }
6443
6444 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6445 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6446 DestructedType->isVectorType();
6447}
6448
John McCalldadc5752010-08-24 06:29:42 +00006449ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006450 SourceLocation OpLoc,
6451 tok::TokenKind OpKind,
6452 const CXXScopeSpec &SS,
6453 TypeSourceInfo *ScopeTypeInfo,
6454 SourceLocation CCLoc,
6455 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006456 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006457 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006458
Eli Friedman0ce4de42012-01-25 04:35:06 +00006459 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006460 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6461 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006462
Douglas Gregorc5c57342012-09-10 14:57:06 +00006463 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6464 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006465 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006466 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006467 else {
Nico Weber58829272012-01-23 05:50:57 +00006468 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6469 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006470 return ExprError();
6471 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006472 }
6473
6474 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006475 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006476 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006477 if (DestructedTypeInfo) {
6478 QualType DestructedType = DestructedTypeInfo->getType();
6479 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006480 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006481 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6482 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006483 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6484 // Foo *foo;
6485 // foo.~Foo();
6486 if (OpKind == tok::period && ObjectType->isPointerType() &&
6487 Context.hasSameUnqualifiedType(DestructedType,
6488 ObjectType->getPointeeType())) {
6489 auto Diagnostic =
6490 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6491 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006492
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006493 // Issue a fixit only when the destructor is valid.
6494 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6495 *this, DestructedType))
6496 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6497
6498 // Recover by setting the object type to the destructed type and the
6499 // operator to '->'.
6500 ObjectType = DestructedType;
6501 OpKind = tok::arrow;
6502 } else {
6503 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6504 << ObjectType << DestructedType << Base->getSourceRange()
6505 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6506
6507 // Recover by setting the destructed type to the object type.
6508 DestructedType = ObjectType;
6509 DestructedTypeInfo =
6510 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6511 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6512 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006513 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006514 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006515
John McCall31168b02011-06-15 23:02:42 +00006516 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6517 // Okay: just pretend that the user provided the correctly-qualified
6518 // type.
6519 } else {
6520 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6521 << ObjectType << DestructedType << Base->getSourceRange()
6522 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6523 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006524
John McCall31168b02011-06-15 23:02:42 +00006525 // Recover by setting the destructed type to the object type.
6526 DestructedType = ObjectType;
6527 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6528 DestructedTypeStart);
6529 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6530 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006531 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006533
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006534 // C++ [expr.pseudo]p2:
6535 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6536 // form
6537 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006539 //
6540 // shall designate the same scalar type.
6541 if (ScopeTypeInfo) {
6542 QualType ScopeType = ScopeTypeInfo->getType();
6543 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006544 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006546 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006547 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006548 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006549 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006550
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006551 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006552 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006553 }
6554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006555
John McCallb268a282010-08-23 23:25:46 +00006556 Expr *Result
6557 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6558 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006559 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006560 ScopeTypeInfo,
6561 CCLoc,
6562 TildeLoc,
6563 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564
David Majnemerced8bdf2015-02-25 17:36:15 +00006565 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006566}
6567
John McCalldadc5752010-08-24 06:29:42 +00006568ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006569 SourceLocation OpLoc,
6570 tok::TokenKind OpKind,
6571 CXXScopeSpec &SS,
6572 UnqualifiedId &FirstTypeName,
6573 SourceLocation CCLoc,
6574 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006575 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006576 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6577 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6578 "Invalid first type name in pseudo-destructor");
6579 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6580 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6581 "Invalid second type name in pseudo-destructor");
6582
Eli Friedman0ce4de42012-01-25 04:35:06 +00006583 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006584 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6585 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006586
6587 // Compute the object type that we should use for name lookup purposes. Only
6588 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006589 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006590 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006591 if (ObjectType->isRecordType())
6592 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006593 else if (ObjectType->isDependentType())
6594 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596
6597 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006598 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006599 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006600 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006601 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006602 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006604 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006605 S, &SS, true, false, ObjectTypePtrForLookup,
6606 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006608 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6609 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006611 // couldn't find anything useful in scope. Just store the identifier and
6612 // it's location, and we'll perform (qualified) name lookup again at
6613 // template instantiation time.
6614 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6615 SecondTypeName.StartLocation);
6616 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006617 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006618 diag::err_pseudo_dtor_destructor_non_type)
6619 << SecondTypeName.Identifier << ObjectType;
6620 if (isSFINAEContext())
6621 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006623 // Recover by assuming we had the right type all along.
6624 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006625 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006626 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006627 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006628 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006629 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006630 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006631 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006632 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006633 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006634 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006635 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006636 TemplateId->TemplateNameLoc,
6637 TemplateId->LAngleLoc,
6638 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006639 TemplateId->RAngleLoc,
6640 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006641 if (T.isInvalid() || !T.get()) {
6642 // Recover by assuming we had the right type all along.
6643 DestructedType = ObjectType;
6644 } else
6645 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
6648 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006649 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006650 if (!DestructedType.isNull()) {
6651 if (!DestructedTypeInfo)
6652 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006653 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006654 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006657 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006658 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006659 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006661 FirstTypeName.Identifier) {
6662 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006663 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006664 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006665 S, &SS, true, false, ObjectTypePtrForLookup,
6666 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006667 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006669 diag::err_pseudo_dtor_destructor_non_type)
6670 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006672 if (isSFINAEContext())
6673 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006674
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006675 // Just drop this type. It's unnecessary anyway.
6676 ScopeType = QualType();
6677 } else
6678 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006679 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006680 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006681 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006682 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006683 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006684 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006685 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006686 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006687 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006688 TemplateId->TemplateNameLoc,
6689 TemplateId->LAngleLoc,
6690 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006691 TemplateId->RAngleLoc,
6692 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006693 if (T.isInvalid() || !T.get()) {
6694 // Recover by dropping this type.
6695 ScopeType = QualType();
6696 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006698 }
6699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006700
Douglas Gregor90ad9222010-02-24 23:02:30 +00006701 if (!ScopeType.isNull() && !ScopeTypeInfo)
6702 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6703 FirstTypeName.StartLocation);
6704
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006705
John McCallb268a282010-08-23 23:25:46 +00006706 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006707 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006708 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006709}
6710
David Blaikie1d578782011-12-16 16:03:09 +00006711ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6712 SourceLocation OpLoc,
6713 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006714 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006715 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006716 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006717 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6718 return ExprError();
6719
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006720 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6721 false);
David Blaikie1d578782011-12-16 16:03:09 +00006722
6723 TypeLocBuilder TLB;
6724 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6725 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6726 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6727 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6728
6729 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006730 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006731 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006732}
6733
John Wiegley01296292011-04-08 18:41:53 +00006734ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006735 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006736 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006737 if (Method->getParent()->isLambda() &&
6738 Method->getConversionType()->isBlockPointerType()) {
6739 // This is a lambda coversion to block pointer; check if the argument
6740 // is a LambdaExpr.
6741 Expr *SubE = E;
6742 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6743 if (CE && CE->getCastKind() == CK_NoOp)
6744 SubE = CE->getSubExpr();
6745 SubE = SubE->IgnoreParens();
6746 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6747 SubE = BE->getSubExpr();
6748 if (isa<LambdaExpr>(SubE)) {
6749 // For the conversion to block pointer on a lambda expression, we
6750 // construct a special BlockLiteral instead; this doesn't really make
6751 // a difference in ARC, but outside of ARC the resulting block literal
6752 // follows the normal lifetime rules for block literals instead of being
6753 // autoreleased.
6754 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006755 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006756 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6757 E->getExprLoc(),
6758 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006759 PopExpressionEvaluationContext();
6760
Eli Friedman98b01ed2012-03-01 04:01:32 +00006761 if (Exp.isInvalid())
6762 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6763 return Exp;
6764 }
6765 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006766
Craig Topperc3ec1492014-05-26 06:22:03 +00006767 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006768 FoundDecl, Method);
6769 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006770 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006771
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006772 MemberExpr *ME = new (Context) MemberExpr(
6773 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6774 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006775 if (HadMultipleCandidates)
6776 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006777 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006778
Alp Toker314cc812014-01-25 16:55:45 +00006779 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006780 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6781 ResultType = ResultType.getNonLValueExprType(Context);
6782
Douglas Gregor27381f32009-11-23 12:27:39 +00006783 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006784 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006785 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006786
6787 if (CheckFunctionCall(Method, CE,
6788 Method->getType()->castAs<FunctionProtoType>()))
6789 return ExprError();
6790
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006791 return CE;
6792}
6793
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006794ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6795 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006796 // If the operand is an unresolved lookup expression, the expression is ill-
6797 // formed per [over.over]p1, because overloaded function names cannot be used
6798 // without arguments except in explicit contexts.
6799 ExprResult R = CheckPlaceholderExpr(Operand);
6800 if (R.isInvalid())
6801 return R;
6802
6803 // The operand may have been modified when checking the placeholder type.
6804 Operand = R.get();
6805
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006806 if (ActiveTemplateInstantiations.empty() &&
6807 Operand->HasSideEffects(Context, false)) {
6808 // The expression operand for noexcept is in an unevaluated expression
6809 // context, so side effects could result in unintended consequences.
6810 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6811 }
6812
Richard Smithf623c962012-04-17 00:58:00 +00006813 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006814 return new (Context)
6815 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006816}
6817
6818ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6819 Expr *Operand, SourceLocation RParen) {
6820 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006821}
6822
Eli Friedmanf798f652012-05-24 22:04:19 +00006823static bool IsSpecialDiscardedValue(Expr *E) {
6824 // In C++11, discarded-value expressions of a certain form are special,
6825 // according to [expr]p10:
6826 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6827 // expression is an lvalue of volatile-qualified type and it has
6828 // one of the following forms:
6829 E = E->IgnoreParens();
6830
Eli Friedmanc49c2262012-05-24 22:36:31 +00006831 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006832 if (isa<DeclRefExpr>(E))
6833 return true;
6834
Eli Friedmanc49c2262012-05-24 22:36:31 +00006835 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006836 if (isa<ArraySubscriptExpr>(E))
6837 return true;
6838
Eli Friedmanc49c2262012-05-24 22:36:31 +00006839 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006840 if (isa<MemberExpr>(E))
6841 return true;
6842
Eli Friedmanc49c2262012-05-24 22:36:31 +00006843 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006844 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6845 if (UO->getOpcode() == UO_Deref)
6846 return true;
6847
6848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006849 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006850 if (BO->isPtrMemOp())
6851 return true;
6852
Eli Friedmanc49c2262012-05-24 22:36:31 +00006853 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006854 if (BO->getOpcode() == BO_Comma)
6855 return IsSpecialDiscardedValue(BO->getRHS());
6856 }
6857
Eli Friedmanc49c2262012-05-24 22:36:31 +00006858 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006859 // operands are one of the above, or
6860 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6861 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6862 IsSpecialDiscardedValue(CO->getFalseExpr());
6863 // The related edge case of "*x ?: *x".
6864 if (BinaryConditionalOperator *BCO =
6865 dyn_cast<BinaryConditionalOperator>(E)) {
6866 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6867 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6868 IsSpecialDiscardedValue(BCO->getFalseExpr());
6869 }
6870
6871 // Objective-C++ extensions to the rule.
6872 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6873 return true;
6874
6875 return false;
6876}
6877
John McCall34376a62010-12-04 03:47:34 +00006878/// Perform the conversions required for an expression used in a
6879/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006880ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006881 if (E->hasPlaceholderType()) {
6882 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006883 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006884 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006885 }
6886
John McCallfee942d2010-12-02 02:07:15 +00006887 // C99 6.3.2.1:
6888 // [Except in specific positions,] an lvalue that does not have
6889 // array type is converted to the value stored in the
6890 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006891 if (E->isRValue()) {
6892 // In C, function designators (i.e. expressions of function type)
6893 // are r-values, but we still want to do function-to-pointer decay
6894 // on them. This is both technically correct and convenient for
6895 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006896 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006897 return DefaultFunctionArrayConversion(E);
6898
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006899 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006900 }
John McCallfee942d2010-12-02 02:07:15 +00006901
Eli Friedmanf798f652012-05-24 22:04:19 +00006902 if (getLangOpts().CPlusPlus) {
6903 // The C++11 standard defines the notion of a discarded-value expression;
6904 // normally, we don't need to do anything to handle it, but if it is a
6905 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6906 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006907 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006908 E->getType().isVolatileQualified() &&
6909 IsSpecialDiscardedValue(E)) {
6910 ExprResult Res = DefaultLvalueConversion(E);
6911 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006912 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006913 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006914 }
Richard Smith122f88d2016-12-06 23:52:28 +00006915
6916 // C++1z:
6917 // If the expression is a prvalue after this optional conversion, the
6918 // temporary materialization conversion is applied.
6919 //
6920 // We skip this step: IR generation is able to synthesize the storage for
6921 // itself in the aggregate case, and adding the extra node to the AST is
6922 // just clutter.
6923 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6924 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006925 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006926 }
John McCall34376a62010-12-04 03:47:34 +00006927
6928 // GCC seems to also exclude expressions of incomplete enum type.
6929 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6930 if (!T->getDecl()->isComplete()) {
6931 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006932 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006933 return E;
John McCall34376a62010-12-04 03:47:34 +00006934 }
6935 }
6936
John Wiegley01296292011-04-08 18:41:53 +00006937 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6938 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006939 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006940 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006941
John McCallca61b652010-12-04 12:29:11 +00006942 if (!E->getType()->isVoidType())
6943 RequireCompleteType(E->getExprLoc(), E->getType(),
6944 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006945 return E;
John McCall34376a62010-12-04 03:47:34 +00006946}
6947
Faisal Valia17d19f2013-11-07 05:17:06 +00006948// If we can unambiguously determine whether Var can never be used
6949// in a constant expression, return true.
6950// - if the variable and its initializer are non-dependent, then
6951// we can unambiguously check if the variable is a constant expression.
6952// - if the initializer is not value dependent - we can determine whether
6953// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006954// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006955// never be a constant expression.
6956// - FXIME: if the initializer is dependent, we can still do some analysis and
6957// identify certain cases unambiguously as non-const by using a Visitor:
6958// - such as those that involve odr-use of a ParmVarDecl, involve a new
6959// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006960static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006961 ASTContext &Context) {
6962 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006963 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006964
6965 // If there is no initializer - this can not be a constant expression.
6966 if (!Var->getAnyInitializer(DefVD)) return true;
6967 assert(DefVD);
6968 if (DefVD->isWeak()) return false;
6969 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006970
Faisal Valia17d19f2013-11-07 05:17:06 +00006971 Expr *Init = cast<Expr>(Eval->Value);
6972
6973 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006974 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6975 // of value-dependent expressions, and use it here to determine whether the
6976 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006977 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006978 }
6979
Simon Pilgrim75c26882016-09-30 14:25:09 +00006980 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006981}
6982
Simon Pilgrim75c26882016-09-30 14:25:09 +00006983/// \brief Check if the current lambda has any potential captures
6984/// that must be captured by any of its enclosing lambdas that are ready to
6985/// capture. If there is a lambda that can capture a nested
6986/// potential-capture, go ahead and do so. Also, check to see if any
6987/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006988/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006989
Faisal Valiab3d6462013-12-07 20:22:44 +00006990static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6991 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6992
Simon Pilgrim75c26882016-09-30 14:25:09 +00006993 assert(!S.isUnevaluatedContext());
6994 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00006995#ifndef NDEBUG
6996 DeclContext *DC = S.CurContext;
6997 while (DC && isa<CapturedDecl>(DC))
6998 DC = DC->getParent();
6999 assert(
7000 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007001 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007002#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007003
7004 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7005
7006 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7007 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007008
Faisal Valiab3d6462013-12-07 20:22:44 +00007009 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007010 // lambda (within a generic outer lambda), must be captured by an
7011 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007012 const unsigned NumPotentialCaptures =
7013 CurrentLSI->getNumPotentialVariableCaptures();
7014 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007015 Expr *VarExpr = nullptr;
7016 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007017 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007018 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007019 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007020 // need to check enclosing lambda's for speculative captures.
7021 // For e.g.:
7022 // Even though 'x' is not odr-used, it should be captured.
7023 // int test() {
7024 // const int x = 10;
7025 // auto L = [=](auto a) {
7026 // (void) +x + a;
7027 // };
7028 // }
7029 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007030 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007031 continue;
7032
7033 // If we have a capture-capable lambda for the variable, go ahead and
7034 // capture the variable in that lambda (and all its enclosing lambdas).
7035 if (const Optional<unsigned> Index =
7036 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7037 FunctionScopesArrayRef, Var, S)) {
7038 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7039 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7040 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007041 }
7042 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007043 VariableCanNeverBeAConstantExpression(Var, S.Context);
7044 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7045 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007046 // can not be used in a constant expression - which means
7047 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007048 // capture violation early, if the variable is un-captureable.
7049 // This is purely for diagnosing errors early. Otherwise, this
7050 // error would get diagnosed when the lambda becomes capture ready.
7051 QualType CaptureType, DeclRefType;
7052 SourceLocation ExprLoc = VarExpr->getExprLoc();
7053 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007054 /*EllipsisLoc*/ SourceLocation(),
7055 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007056 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007057 // We will never be able to capture this variable, and we need
7058 // to be able to in any and all instantiations, so diagnose it.
7059 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007060 /*EllipsisLoc*/ SourceLocation(),
7061 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007062 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007063 }
7064 }
7065 }
7066
Faisal Valiab3d6462013-12-07 20:22:44 +00007067 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007068 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007069 // If we have a capture-capable lambda for 'this', go ahead and capture
7070 // 'this' in that lambda (and all its enclosing lambdas).
7071 if (const Optional<unsigned> Index =
7072 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007073 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007074 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7075 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7076 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7077 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007078 }
7079 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007080
7081 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007082 CurrentLSI->clearPotentialCaptures();
7083}
7084
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007085static ExprResult attemptRecovery(Sema &SemaRef,
7086 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007087 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007088 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7089 Consumer.getLookupResult().getLookupKind());
7090 const CXXScopeSpec *SS = Consumer.getSS();
7091 CXXScopeSpec NewSS;
7092
7093 // Use an approprate CXXScopeSpec for building the expr.
7094 if (auto *NNS = TC.getCorrectionSpecifier())
7095 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7096 else if (SS && !TC.WillReplaceSpecifier())
7097 NewSS = *SS;
7098
Richard Smithde6d6c42015-12-29 19:43:10 +00007099 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007100 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007101 R.addDecl(ND);
7102 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007103 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007104 CXXRecordDecl *Record = nullptr;
7105 if (auto *NNS = TC.getCorrectionSpecifier())
7106 Record = NNS->getAsType()->getAsCXXRecordDecl();
7107 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007108 Record =
7109 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7110 if (Record)
7111 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007112
7113 // Detect and handle the case where the decl might be an implicit
7114 // member.
7115 bool MightBeImplicitMember;
7116 if (!Consumer.isAddressOfOperand())
7117 MightBeImplicitMember = true;
7118 else if (!NewSS.isEmpty())
7119 MightBeImplicitMember = false;
7120 else if (R.isOverloadedResult())
7121 MightBeImplicitMember = false;
7122 else if (R.isUnresolvableResult())
7123 MightBeImplicitMember = true;
7124 else
7125 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7126 isa<IndirectFieldDecl>(ND) ||
7127 isa<MSPropertyDecl>(ND);
7128
7129 if (MightBeImplicitMember)
7130 return SemaRef.BuildPossibleImplicitMemberExpr(
7131 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007132 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007133 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7134 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7135 Ivar->getIdentifier());
7136 }
7137 }
7138
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007139 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7140 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007141}
7142
Kaelyn Takata6c759512014-10-27 18:07:37 +00007143namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007144class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7145 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7146
7147public:
7148 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7149 : TypoExprs(TypoExprs) {}
7150 bool VisitTypoExpr(TypoExpr *TE) {
7151 TypoExprs.insert(TE);
7152 return true;
7153 }
7154};
7155
Kaelyn Takata6c759512014-10-27 18:07:37 +00007156class TransformTypos : public TreeTransform<TransformTypos> {
7157 typedef TreeTransform<TransformTypos> BaseTransform;
7158
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007159 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7160 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007161 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007162 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007163 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007164 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007165
7166 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7167 /// If the TypoExprs were successfully corrected, then the diagnostics should
7168 /// suggest the corrections. Otherwise the diagnostics will not suggest
7169 /// anything (having been passed an empty TypoCorrection).
7170 void EmitAllDiagnostics() {
7171 for (auto E : TypoExprs) {
7172 TypoExpr *TE = cast<TypoExpr>(E);
7173 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007174 if (State.DiagHandler) {
7175 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7176 ExprResult Replacement = TransformCache[TE];
7177
7178 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7179 // TypoCorrection, replacing the existing decls. This ensures the right
7180 // NamedDecl is used in diagnostics e.g. in the case where overload
7181 // resolution was used to select one from several possible decls that
7182 // had been stored in the TypoCorrection.
7183 if (auto *ND = getDeclFromExpr(
7184 Replacement.isInvalid() ? nullptr : Replacement.get()))
7185 TC.setCorrectionDecl(ND);
7186
7187 State.DiagHandler(TC);
7188 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007189 SemaRef.clearDelayedTypo(TE);
7190 }
7191 }
7192
7193 /// \brief If corrections for the first TypoExpr have been exhausted for a
7194 /// given combination of the other TypoExprs, retry those corrections against
7195 /// the next combination of substitutions for the other TypoExprs by advancing
7196 /// to the next potential correction of the second TypoExpr. For the second
7197 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7198 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7199 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7200 /// TransformCache). Returns true if there is still any untried combinations
7201 /// of corrections.
7202 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7203 for (auto TE : TypoExprs) {
7204 auto &State = SemaRef.getTypoExprState(TE);
7205 TransformCache.erase(TE);
7206 if (!State.Consumer->finished())
7207 return true;
7208 State.Consumer->resetCorrectionStream();
7209 }
7210 return false;
7211 }
7212
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007213 NamedDecl *getDeclFromExpr(Expr *E) {
7214 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7215 E = OverloadResolution[OE];
7216
7217 if (!E)
7218 return nullptr;
7219 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007220 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007221 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007222 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007223 // FIXME: Add any other expr types that could be be seen by the delayed typo
7224 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007225 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007226 return nullptr;
7227 }
7228
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007229 ExprResult TryTransform(Expr *E) {
7230 Sema::SFINAETrap Trap(SemaRef);
7231 ExprResult Res = TransformExpr(E);
7232 if (Trap.hasErrorOccurred() || Res.isInvalid())
7233 return ExprError();
7234
7235 return ExprFilter(Res.get());
7236 }
7237
Kaelyn Takata6c759512014-10-27 18:07:37 +00007238public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007239 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7240 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007241
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007242 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7243 MultiExprArg Args,
7244 SourceLocation RParenLoc,
7245 Expr *ExecConfig = nullptr) {
7246 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7247 RParenLoc, ExecConfig);
7248 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007249 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007250 Expr *ResultCall = Result.get();
7251 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7252 ResultCall = BE->getSubExpr();
7253 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7254 OverloadResolution[OE] = CE->getCallee();
7255 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007256 }
7257 return Result;
7258 }
7259
Kaelyn Takata6c759512014-10-27 18:07:37 +00007260 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7261
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007262 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7263
Kaelyn Takata6c759512014-10-27 18:07:37 +00007264 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007265 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007266 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007267 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007268
Kaelyn Takata6c759512014-10-27 18:07:37 +00007269 // Exit if either the transform was valid or if there were no TypoExprs
7270 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007271 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007272 !CheckAndAdvanceTypoExprCorrectionStreams())
7273 break;
7274 }
7275
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007276 // Ensure none of the TypoExprs have multiple typo correction candidates
7277 // with the same edit length that pass all the checks and filters.
7278 // TODO: Properly handle various permutations of possible corrections when
7279 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007280 // Also, disable typo correction while attempting the transform when
7281 // handling potentially ambiguous typo corrections as any new TypoExprs will
7282 // have been introduced by the application of one of the correction
7283 // candidates and add little to no value if corrected.
7284 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007285 while (!AmbiguousTypoExprs.empty()) {
7286 auto TE = AmbiguousTypoExprs.back();
7287 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007288 auto &State = SemaRef.getTypoExprState(TE);
7289 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007290 TransformCache.erase(TE);
7291 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007292 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007293 TransformCache.erase(TE);
7294 Res = ExprError();
7295 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007296 }
7297 AmbiguousTypoExprs.remove(TE);
7298 State.Consumer->restoreSavedPosition();
7299 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007300 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007301 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007302
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007303 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007304 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007305 FindTypoExprs(TypoExprs).TraverseStmt(E);
7306
Kaelyn Takata6c759512014-10-27 18:07:37 +00007307 EmitAllDiagnostics();
7308
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007309 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007310 }
7311
7312 ExprResult TransformTypoExpr(TypoExpr *E) {
7313 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7314 // cached transformation result if there is one and the TypoExpr isn't the
7315 // first one that was encountered.
7316 auto &CacheEntry = TransformCache[E];
7317 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7318 return CacheEntry;
7319 }
7320
7321 auto &State = SemaRef.getTypoExprState(E);
7322 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7323
7324 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7325 // typo correction and return it.
7326 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007327 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007328 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007329 // FIXME: If we would typo-correct to an invalid declaration, it's
7330 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007331 ExprResult NE = State.RecoveryHandler ?
7332 State.RecoveryHandler(SemaRef, E, TC) :
7333 attemptRecovery(SemaRef, *State.Consumer, TC);
7334 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007335 // Check whether there may be a second viable correction with the same
7336 // edit distance; if so, remember this TypoExpr may have an ambiguous
7337 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007338 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007339 if ((Next = State.Consumer->peekNextCorrection()) &&
7340 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7341 AmbiguousTypoExprs.insert(E);
7342 } else {
7343 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007344 }
7345 assert(!NE.isUnset() &&
7346 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007347 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007348 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007349 }
7350 return CacheEntry = ExprError();
7351 }
7352};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007353}
Faisal Valia17d19f2013-11-07 05:17:06 +00007354
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007355ExprResult
7356Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7357 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007358 // If the current evaluation context indicates there are uncorrected typos
7359 // and the current expression isn't guaranteed to not have typos, try to
7360 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007361 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007362 (E->isTypeDependent() || E->isValueDependent() ||
7363 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007364 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7365 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7366 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007367 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007368 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007369 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007370 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007371 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007372 ExprEvalContexts.back().NumTypos -= TyposResolved;
7373 return Result;
7374 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007375 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007376 }
7377 return E;
7378}
7379
Richard Smith945f8d32013-01-14 22:39:08 +00007380ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007381 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007382 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007383 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007384 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007385
7386 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007387 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007388
7389 // If we are an init-expression in a lambdas init-capture, we should not
7390 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007391 // containing full-expression is done).
7392 // template<class ... Ts> void test(Ts ... t) {
7393 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7394 // return a;
7395 // }() ...);
7396 // }
7397 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7398 // when we parse the lambda introducer, and teach capturing (but not
7399 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7400 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7401 // lambda where we've entered the introducer but not the body, or represent a
7402 // lambda where we've entered the body, depending on where the
7403 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007404 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007405 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007406 return ExprError();
7407
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007408 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007409 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007410 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007411 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007412 if (FullExpr.isInvalid())
7413 return ExprError();
7414 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007415
Richard Smith945f8d32013-01-14 22:39:08 +00007416 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007417 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007418 if (FullExpr.isInvalid())
7419 return ExprError();
7420
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007421 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007422 if (FullExpr.isInvalid())
7423 return ExprError();
7424 }
John Wiegley01296292011-04-08 18:41:53 +00007425
Kaelyn Takata49d84322014-11-11 23:26:56 +00007426 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7427 if (FullExpr.isInvalid())
7428 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007429
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007430 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007431
Simon Pilgrim75c26882016-09-30 14:25:09 +00007432 // At the end of this full expression (which could be a deeply nested
7433 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007434 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007435 // Consider the following code:
7436 // void f(int, int);
7437 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007438 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007439 // const int x = 10, y = 20;
7440 // auto L = [=](auto a) {
7441 // auto M = [=](auto b) {
7442 // f(x, b); <-- requires x to be captured by L and M
7443 // f(y, a); <-- requires y to be captured by L, but not all Ms
7444 // };
7445 // };
7446 // }
7447
Simon Pilgrim75c26882016-09-30 14:25:09 +00007448 // FIXME: Also consider what happens for something like this that involves
7449 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007450 // void f() {
7451 // const int n = 0;
7452 // auto L = [&](auto a) {
7453 // +n + ({ 0; a; });
7454 // };
7455 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007456 //
7457 // Here, we see +n, and then the full-expression 0; ends, so we don't
7458 // capture n (and instead remove it from our list of potential captures),
7459 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007460 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007461
Alexey Bataev31939e32016-11-11 12:36:20 +00007462 LambdaScopeInfo *const CurrentLSI =
7463 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007464 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007465 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007466 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007467 // By ensuring we are in the context of a lambda's call operator
7468 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007469 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007470 // PR, a proper fix would entail :
7471 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007472 // - Add to Sema an integer holding the smallest (outermost) scope
7473 // index that we are *lexically* within, and save/restore/set to
7474 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007475 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007476 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007477 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007478 DeclContext *DC = CurContext;
7479 while (DC && isa<CapturedDecl>(DC))
7480 DC = DC->getParent();
7481 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007482 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007483 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007484 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7485 *this);
John McCall5d413782010-12-06 08:20:24 +00007486 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007487}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007488
7489StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7490 if (!FullStmt) return StmtError();
7491
John McCall5d413782010-12-06 08:20:24 +00007492 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007493}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007494
Simon Pilgrim75c26882016-09-30 14:25:09 +00007495Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007496Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7497 CXXScopeSpec &SS,
7498 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007499 DeclarationName TargetName = TargetNameInfo.getName();
7500 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007501 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007502
Douglas Gregor43edb322011-10-24 22:31:10 +00007503 // If the name itself is dependent, then the result is dependent.
7504 if (TargetName.isDependentName())
7505 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007506
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007507 // Do the redeclaration lookup in the current scope.
7508 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7509 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007510 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007511 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007512
Douglas Gregor43edb322011-10-24 22:31:10 +00007513 switch (R.getResultKind()) {
7514 case LookupResult::Found:
7515 case LookupResult::FoundOverloaded:
7516 case LookupResult::FoundUnresolvedValue:
7517 case LookupResult::Ambiguous:
7518 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007519
Douglas Gregor43edb322011-10-24 22:31:10 +00007520 case LookupResult::NotFound:
7521 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007522
Douglas Gregor43edb322011-10-24 22:31:10 +00007523 case LookupResult::NotFoundInCurrentInstantiation:
7524 return IER_Dependent;
7525 }
David Blaikie8a40f702012-01-17 06:56:22 +00007526
7527 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007528}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007529
Simon Pilgrim75c26882016-09-30 14:25:09 +00007530Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007531Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7532 bool IsIfExists, CXXScopeSpec &SS,
7533 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007534 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007535
Richard Smith151c4562016-12-20 21:35:28 +00007536 // Check for an unexpanded parameter pack.
7537 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7538 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7539 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007540 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007541
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007542 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7543}