blob: 5d1001dc84d9519648d21fbbdbe068d4ad865fff [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000012///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000046/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
John McCallba7bf592010-08-24 05:47:05 +000083ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000085 SourceLocation NameLoc,
86 Scope *S, CXXScopeSpec &SS,
87 ParsedType ObjectTypePtr,
88 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000089 // Determine where to perform name lookup.
90
91 // FIXME: This area of the standard is very messy, and the current
92 // wording is rather unclear about which scopes we search for the
93 // destructor name; see core issues 399 and 555. Issue 399 in
94 // particular shows where the current description of destructor name
95 // lookup is completely out of line with existing practice, e.g.,
96 // this appears to be ill-formed:
97 //
98 // namespace N {
99 // template <typename T> struct S {
100 // ~S();
101 // };
102 // }
103 //
104 // void f(N::S<int>* s) {
105 // s->N::S<int>::~S();
106 // }
107 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000108 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000109 // For this reason, we're currently only doing the C++03 version of this
110 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000111 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000112 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000113 bool isDependent = false;
114 bool LookInScope = false;
115
Richard Smith64e033f2015-01-15 00:48:52 +0000116 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000117 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000118
Douglas Gregorfe17d252010-02-16 19:09:40 +0000119 // If we have an object type, it's because we are in a
120 // pseudo-destructor-expression or a member access expression, and
121 // we know what type we're looking for.
122 if (ObjectTypePtr)
123 SearchType = GetTypeFromParser(ObjectTypePtr);
124
125 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000126 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127
Douglas Gregor46841e12010-02-23 00:15:22 +0000128 bool AlreadySearched = false;
129 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000130 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000132 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000133 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000134 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000135 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000136 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000137 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000139 // Here, we determine whether the code below is permitted to look at the
140 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000141 DeclContext *DC = computeDeclContext(SS, EnteringContext);
142 if (DC && DC->isFileContext()) {
143 AlreadySearched = true;
144 LookupCtx = DC;
145 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000146 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000147 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000148 LookInScope = true;
149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Sebastian Redla771d222010-07-07 23:17:38 +0000151 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000152 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000153 if (AlreadySearched) {
154 // Nothing left to do.
155 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
156 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000157 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000158 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
159 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000160 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161 LookupCtx = computeDeclContext(SearchType);
162 isDependent = SearchType->isDependentType();
163 } else {
164 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000165 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000167 } else if (ObjectTypePtr) {
168 // C++ [basic.lookup.classref]p3:
169 // If the unqualified-id is ~type-name, the type-name is looked up
170 // in the context of the entire postfix-expression. If the type T
171 // of the object expression is of a class type C, the type-name is
172 // also looked up in the scope of class C. At least one of the
173 // lookups shall find a name that refers to (possibly
174 // cv-qualified) T.
175 LookupCtx = computeDeclContext(SearchType);
176 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000177 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000178 "Caller should have completed object type");
179
180 LookInScope = true;
181 } else {
182 // Perform lookup into the current scope (only).
183 LookInScope = true;
184 }
185
Craig Topperc3ec1492014-05-26 06:22:03 +0000186 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000187 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
188 for (unsigned Step = 0; Step != 2; ++Step) {
189 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000190 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000191 // we're allowed to look there).
192 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000193 if (Step == 0 && LookupCtx) {
194 if (RequireCompleteDeclContext(SS, LookupCtx))
195 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000196 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000197 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000199 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000200 continue;
John McCallcb731542017-06-11 20:33:00 +0000201 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 // FIXME: Should we be suppressing ambiguities here?
204 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000205 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
208 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000209 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210
211 if (SearchType.isNull() || SearchType->isDependentType() ||
212 Context.hasSameUnqualifiedType(T, SearchType)) {
213 // We found our type!
214
Richard Smithc278c002014-01-22 00:30:17 +0000215 return CreateParsedType(T,
216 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000218
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000219 if (!SearchType.isNull())
220 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000221 }
222
223 // If the name that we found is a class template name, and it is
224 // the same name as the template name in the last part of the
225 // nested-name-specifier (if present) or the object type, then
226 // this is the destructor for that class.
227 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000228 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000229 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
230 QualType MemberOfType;
231 if (SS.isSet()) {
232 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
233 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
235 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000236 }
237 }
238 if (MemberOfType.isNull())
239 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregorfe17d252010-02-16 19:09:40 +0000241 if (MemberOfType.isNull())
242 continue;
243
244 // We're referring into a class template specialization. If the
245 // class template we found is the same as the template being
246 // specialized, we found what we are looking for.
247 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
248 if (ClassTemplateSpecializationDecl *Spec
249 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
250 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
251 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000252 return CreateParsedType(
253 MemberOfType,
254 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000255 }
256
257 continue;
258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259
Douglas Gregorfe17d252010-02-16 19:09:40 +0000260 // We're referring to an unresolved class template
261 // specialization. Determine whether we class template we found
262 // is the same as the template being specialized or, if we don't
263 // know which template is being specialized, that it at least
264 // has the same name.
265 if (const TemplateSpecializationType *SpecType
266 = MemberOfType->getAs<TemplateSpecializationType>()) {
267 TemplateName SpecName = SpecType->getTemplateName();
268
269 // The class template we found is the same template being
270 // specialized.
271 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
272 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000273 return CreateParsedType(
274 MemberOfType,
275 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000276
277 continue;
278 }
279
280 // The class template we found has the same name as the
281 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000283 = SpecName.getAsDependentTemplateName()) {
284 if (DepTemplate->isIdentifier() &&
285 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000286 return CreateParsedType(
287 MemberOfType,
288 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000289
290 continue;
291 }
292 }
293 }
294 }
295
296 if (isDependent) {
297 // We didn't find our type, but that's okay: it's dependent
298 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000299
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000300 // FIXME: What if we have no nested-name-specifier?
301 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
302 SS.getWithLocInContext(Context),
303 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000304 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000305 }
306
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000307 if (NonMatchingTypeDecl) {
308 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
309 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
310 << T << SearchType;
311 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
312 << T;
313 } else if (ObjectTypePtr)
314 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000315 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000316 else {
317 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
318 diag::err_destructor_class_name);
319 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000320 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000321 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
322 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
323 Class->getNameAsString());
324 }
325 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000326
David Blaikieefdccaa2016-01-15 23:43:34 +0000327 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000328}
329
Richard Smithef2cd8f2017-02-08 20:39:08 +0000330ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
331 ParsedType ObjectType) {
332 if (DS.getTypeSpecType() == DeclSpec::TST_error)
333 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000334
Richard Smithef2cd8f2017-02-08 20:39:08 +0000335 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
336 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
337 return nullptr;
338 }
339
340 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
341 "unexpected type in getDestructorType");
342 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
343
344 // If we know the type of the object, check that the correct destructor
345 // type was named now; we can give better diagnostics this way.
346 QualType SearchType = GetTypeFromParser(ObjectType);
347 if (!SearchType.isNull() && !SearchType->isDependentType() &&
348 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000349 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000351 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000352 }
353
354 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000355}
356
Richard Smithd091dc12013-12-05 00:58:33 +0000357bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
358 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000359 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000360
361 if (!SS.isValid())
362 return false;
363
364 switch (SS.getScopeRep()->getKind()) {
365 case NestedNameSpecifier::Identifier:
366 case NestedNameSpecifier::TypeSpec:
367 case NestedNameSpecifier::TypeSpecWithTemplate:
368 // Per C++11 [over.literal]p2, literal operators can only be declared at
369 // namespace scope. Therefore, this unqualified-id cannot name anything.
370 // Reject it early, because we have no AST representation for this in the
371 // case where the scope is dependent.
372 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
373 << SS.getScopeRep();
374 return true;
375
376 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000377 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000378 case NestedNameSpecifier::Namespace:
379 case NestedNameSpecifier::NamespaceAlias:
380 return false;
381 }
382
383 llvm_unreachable("unknown nested name specifier kind");
384}
385
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000387ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000388 SourceLocation TypeidLoc,
389 TypeSourceInfo *Operand,
390 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000391 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000393 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000395 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000396 Qualifiers Quals;
397 QualType T
398 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
399 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000400 if (T->getAs<RecordType>() &&
401 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
402 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000403
David Majnemer6f3150a2014-11-21 21:09:12 +0000404 if (T->isVariablyModifiedType())
405 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
406
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000407 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
408 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000409}
410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000411/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000412ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000416 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000417 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000418 if (E->getType()->isPlaceholderType()) {
419 ExprResult result = CheckPlaceholderExpr(E);
420 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000421 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000422 }
423
Douglas Gregor9da64192010-04-26 22:37:10 +0000424 QualType T = E->getType();
425 if (const RecordType *RecordT = T->getAs<RecordType>()) {
426 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
427 // C++ [expr.typeid]p3:
428 // [...] If the type of the expression is a class type, the class
429 // shall be completely-defined.
430 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
431 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000434 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // polymorphic class type [...] [the] expression is an unevaluated
436 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000437 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000438 // The subexpression is potentially evaluated; switch the context
439 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000440 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000441 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000442 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000443
444 // We require a vtable to query the type at run time.
445 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000446 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000447 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 // C++ [expr.typeid]p4:
451 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452 // cv-qualified type, the result of the typeid expression refers to a
453 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000454 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000455 Qualifiers Quals;
456 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
457 if (!Context.hasSameType(T, UnqualT)) {
458 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000459 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000460 }
461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
David Majnemer6f3150a2014-11-21 21:09:12 +0000463 if (E->getType()->isVariablyModifiedType())
464 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
465 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000466 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000467 E->HasSideEffects(Context, WasEvaluated)) {
468 // The expression operand for typeid is in an unevaluated expression
469 // context, so side effects could result in unintended consequences.
470 Diag(E->getExprLoc(), WasEvaluated
471 ? diag::warn_side_effects_typeid
472 : diag::warn_side_effects_unevaluated_context);
473 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000474
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000475 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
476 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000477}
478
479/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000480ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000481Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
482 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000483 // OpenCL C++ 1.0 s2.9: typeid is not supported.
484 if (getLangOpts().OpenCLCPlusPlus) {
485 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
486 << "typeid");
487 }
488
Douglas Gregor9da64192010-04-26 22:37:10 +0000489 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000490 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000491 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000492
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000493 if (!CXXTypeInfoDecl) {
494 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
495 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
496 LookupQualifiedName(R, getStdNamespace());
497 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000498 // Microsoft's typeinfo doesn't have type_info in std but in the global
499 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000500 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000501 LookupQualifiedName(R, Context.getTranslationUnitDecl());
502 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
503 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000504 if (!CXXTypeInfoDecl)
505 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507
Nico Weber1b7f39d2012-05-20 01:27:21 +0000508 if (!getLangOpts().RTTI) {
509 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
510 }
511
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000512 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000513
Douglas Gregor9da64192010-04-26 22:37:10 +0000514 if (isType) {
515 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000516 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000517 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
518 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000519 if (T.isNull())
520 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521
Douglas Gregor9da64192010-04-26 22:37:10 +0000522 if (!TInfo)
523 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000524
Douglas Gregor9da64192010-04-26 22:37:10 +0000525 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000528 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000529 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000530}
531
David Majnemer1dbc7a72016-03-27 04:46:07 +0000532/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
533/// a single GUID.
534static void
535getUuidAttrOfType(Sema &SemaRef, QualType QT,
536 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
537 // Optionally remove one level of pointer, reference or array indirection.
538 const Type *Ty = QT.getTypePtr();
539 if (QT->isPointerType() || QT->isReferenceType())
540 Ty = QT->getPointeeType().getTypePtr();
541 else if (QT->isArrayType())
542 Ty = Ty->getBaseElementTypeUnsafe();
543
Reid Klecknere516eab2016-12-13 18:58:09 +0000544 const auto *TD = Ty->getAsTagDecl();
545 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000546 return;
547
Reid Klecknere516eab2016-12-13 18:58:09 +0000548 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000549 UuidAttrs.insert(Uuid);
550 return;
551 }
552
553 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000554 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000555 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
556 for (const TemplateArgument &TA : TAL.asArray()) {
557 const UuidAttr *UuidForTA = nullptr;
558 if (TA.getKind() == TemplateArgument::Type)
559 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
560 else if (TA.getKind() == TemplateArgument::Declaration)
561 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
562
563 if (UuidForTA)
564 UuidAttrs.insert(UuidForTA);
565 }
566 }
567}
568
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000569/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000570ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
571 SourceLocation TypeidLoc,
572 TypeSourceInfo *Operand,
573 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000574 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000575 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000576 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
577 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
578 if (UuidAttrs.empty())
579 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
580 if (UuidAttrs.size() > 1)
581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000582 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
David Majnemer2041b462016-03-28 03:19:50 +0000585 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000586 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000587}
588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000589/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000590ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
591 SourceLocation TypeidLoc,
592 Expr *E,
593 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000594 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000595 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000596 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
597 UuidStr = "00000000-0000-0000-0000-000000000000";
598 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000599 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
600 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
601 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000602 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000603 if (UuidAttrs.size() > 1)
604 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000605 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000606 }
Francois Pichetb7577652010-12-27 01:32:00 +0000607 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000608
David Majnemer2041b462016-03-28 03:19:50 +0000609 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000610 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000611}
612
613/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
614ExprResult
615Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
616 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000618 if (!MSVCGuidDecl) {
619 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
620 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
621 LookupQualifiedName(R, Context.getTranslationUnitDecl());
622 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
623 if (!MSVCGuidDecl)
624 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625 }
626
Francois Pichet9f4f2072010-09-08 12:20:18 +0000627 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
Francois Pichet9f4f2072010-09-08 12:20:18 +0000629 if (isType) {
630 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000631 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000632 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
633 &TInfo);
634 if (T.isNull())
635 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
Francois Pichet9f4f2072010-09-08 12:20:18 +0000637 if (!TInfo)
638 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
639
640 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
641 }
642
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000644 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
645}
646
Steve Naroff66356bd2007-09-16 14:56:35 +0000647/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000648ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000649Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000650 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000651 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000652 return new (Context)
653 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000654}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000655
Sebastian Redl576fd422009-05-10 18:38:11 +0000656/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000657ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000658Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000659 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000660}
661
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000662/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000663ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000664Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
665 bool IsThrownVarInScope = false;
666 if (Ex) {
667 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000668 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000669 // copy/move construction of a class object [...]
670 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000671 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000672 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000673 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000674 // innermost enclosing try-block (if there is one), the copy/move
675 // operation from the operand to the exception object (15.1) can be
676 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000677 // exception object
678 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
679 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
680 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
681 for( ; S; S = S->getParent()) {
682 if (S->isDeclScope(Var)) {
683 IsThrownVarInScope = true;
684 break;
685 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000686
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000687 if (S->getFlags() &
688 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
689 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
690 Scope::TryScope))
691 break;
692 }
693 }
694 }
695 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000696
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000697 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
698}
699
Simon Pilgrim75c26882016-09-30 14:25:09 +0000700ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000701 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000702 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000703 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +0000704 !getSourceManager().isInSystemHeader(OpLoc) &&
705 (!getLangOpts().OpenMPIsDevice ||
706 !getLangOpts().OpenMPHostCXXExceptions ||
707 isInOpenMPTargetExecutionDirective() ||
708 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000709 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000710
Justin Lebar2a8db342016-09-28 22:45:54 +0000711 // Exceptions aren't allowed in CUDA device code.
712 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000713 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
714 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000715
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000716 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
717 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
718
John Wiegley01296292011-04-08 18:41:53 +0000719 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000720 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
721 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000722 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000723
724 // Initialize the exception result. This implicitly weeds out
725 // abstract types or types with inaccessible copy constructors.
726
727 // C++0x [class.copymove]p31:
728 // When certain criteria are met, an implementation is allowed to omit the
729 // copy/move construction of a class object [...]
730 //
731 // - in a throw-expression, when the operand is the name of a
732 // non-volatile automatic object (other than a function or
733 // catch-clause
734 // parameter) whose scope does not extend beyond the end of the
735 // innermost enclosing try-block (if there is one), the copy/move
736 // operation from the operand to the exception object (15.1) can be
737 // omitted by constructing the automatic object directly into the
738 // exception object
739 const VarDecl *NRVOVariable = nullptr;
740 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000741 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000742
743 InitializedEntity Entity = InitializedEntity::InitializeException(
744 OpLoc, ExceptionObjectTy,
745 /*NRVO=*/NRVOVariable != nullptr);
746 ExprResult Res = PerformMoveOrCopyInitialization(
747 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
748 if (Res.isInvalid())
749 return ExprError();
750 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000751 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000752
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000753 return new (Context)
754 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000755}
756
David Majnemere7a818f2015-03-06 18:53:55 +0000757static void
758collectPublicBases(CXXRecordDecl *RD,
759 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
760 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
761 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
762 bool ParentIsPublic) {
763 for (const CXXBaseSpecifier &BS : RD->bases()) {
764 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
765 bool NewSubobject;
766 // Virtual bases constitute the same subobject. Non-virtual bases are
767 // always distinct subobjects.
768 if (BS.isVirtual())
769 NewSubobject = VBases.insert(BaseDecl).second;
770 else
771 NewSubobject = true;
772
773 if (NewSubobject)
774 ++SubobjectsSeen[BaseDecl];
775
776 // Only add subobjects which have public access throughout the entire chain.
777 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
778 if (PublicPath)
779 PublicSubobjectsSeen.insert(BaseDecl);
780
781 // Recurse on to each base subobject.
782 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
783 PublicPath);
784 }
785}
786
787static void getUnambiguousPublicSubobjects(
788 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
789 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
790 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
791 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
792 SubobjectsSeen[RD] = 1;
793 PublicSubobjectsSeen.insert(RD);
794 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
795 /*ParentIsPublic=*/true);
796
797 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
798 // Skip ambiguous objects.
799 if (SubobjectsSeen[PublicSubobject] > 1)
800 continue;
801
802 Objects.push_back(PublicSubobject);
803 }
804}
805
Sebastian Redl4de47b42009-04-27 20:27:31 +0000806/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000807bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
808 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000809 // If the type of the exception would be an incomplete type or a pointer
810 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000811 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000812 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000813 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000814 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000815 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000816 }
817 if (!isPointer || !Ty->isVoidType()) {
818 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000819 isPointer ? diag::err_throw_incomplete_ptr
820 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000821 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000822 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000823
David Majnemerd09a51c2015-03-03 01:50:05 +0000824 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000825 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000826 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000827 }
828
Eli Friedman91a3d272010-06-03 20:39:03 +0000829 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000830 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
831 if (!RD)
832 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000833
Douglas Gregor88d292c2010-05-13 16:44:06 +0000834 // If we are throwing a polymorphic class type or pointer thereof,
835 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000836 MarkVTableUsed(ThrowLoc, RD);
837
Eli Friedman36ebbec2010-10-12 20:32:36 +0000838 // If a pointer is thrown, the referenced object will not be destroyed.
839 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000840 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000841
Richard Smitheec915d62012-02-18 04:13:32 +0000842 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000843 if (!RD->hasIrrelevantDestructor()) {
844 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
845 MarkFunctionReferenced(E->getExprLoc(), Destructor);
846 CheckDestructorAccess(E->getExprLoc(), Destructor,
847 PDiag(diag::err_access_dtor_exception) << Ty);
848 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000849 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000850 }
851 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000852
David Majnemerdfa6d202015-03-11 18:36:39 +0000853 // The MSVC ABI creates a list of all types which can catch the exception
854 // object. This list also references the appropriate copy constructor to call
855 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000856 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000857 // We are only interested in the public, unambiguous bases contained within
858 // the exception object. Bases which are ambiguous or otherwise
859 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000860 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
861 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000862
David Majnemere7a818f2015-03-06 18:53:55 +0000863 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000864 // Attempt to lookup the copy constructor. Various pieces of machinery
865 // will spring into action, like template instantiation, which means this
866 // cannot be a simple walk of the class's decls. Instead, we must perform
867 // lookup and overload resolution.
868 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
869 if (!CD)
870 continue;
871
872 // Mark the constructor referenced as it is used by this throw expression.
873 MarkFunctionReferenced(E->getExprLoc(), CD);
874
875 // Skip this copy constructor if it is trivial, we don't need to record it
876 // in the catchable type data.
877 if (CD->isTrivial())
878 continue;
879
880 // The copy constructor is non-trivial, create a mapping from this class
881 // type to this constructor.
882 // N.B. The selection of copy constructor is not sensitive to this
883 // particular throw-site. Lookup will be performed at the catch-site to
884 // ensure that the copy constructor is, in fact, accessible (via
885 // friendship or any other means).
886 Context.addCopyConstructorForExceptionObject(Subobject, CD);
887
888 // We don't keep the instantiated default argument expressions around so
889 // we must rebuild them here.
890 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000891 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
892 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000893 }
894 }
895 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000896
David Majnemerba3e5ec2015-03-13 18:26:17 +0000897 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000898}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000899
Faisal Vali67b04462016-06-11 16:41:54 +0000900static QualType adjustCVQualifiersForCXXThisWithinLambda(
901 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
902 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
903
904 QualType ClassType = ThisTy->getPointeeType();
905 LambdaScopeInfo *CurLSI = nullptr;
906 DeclContext *CurDC = CurSemaContext;
907
908 // Iterate through the stack of lambdas starting from the innermost lambda to
909 // the outermost lambda, checking if '*this' is ever captured by copy - since
910 // that could change the cv-qualifiers of the '*this' object.
911 // The object referred to by '*this' starts out with the cv-qualifiers of its
912 // member function. We then start with the innermost lambda and iterate
913 // outward checking to see if any lambda performs a by-copy capture of '*this'
914 // - and if so, any nested lambda must respect the 'constness' of that
915 // capturing lamdbda's call operator.
916 //
917
Faisal Vali999f27e2017-05-02 20:56:34 +0000918 // Since the FunctionScopeInfo stack is representative of the lexical
919 // nesting of the lambda expressions during initial parsing (and is the best
920 // place for querying information about captures about lambdas that are
921 // partially processed) and perhaps during instantiation of function templates
922 // that contain lambda expressions that need to be transformed BUT not
923 // necessarily during instantiation of a nested generic lambda's function call
924 // operator (which might even be instantiated at the end of the TU) - at which
925 // time the DeclContext tree is mature enough to query capture information
926 // reliably - we use a two pronged approach to walk through all the lexically
927 // enclosing lambda expressions:
928 //
929 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
930 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
931 // enclosed by the call-operator of the LSI below it on the stack (while
932 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
933 // the stack represents the innermost lambda.
934 //
935 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
936 // represents a lambda's call operator. If it does, we must be instantiating
937 // a generic lambda's call operator (represented by the Current LSI, and
938 // should be the only scenario where an inconsistency between the LSI and the
939 // DeclContext should occur), so climb out the DeclContexts if they
940 // represent lambdas, while querying the corresponding closure types
941 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000942
Faisal Vali999f27e2017-05-02 20:56:34 +0000943 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000944 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000945 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
946 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
947 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000948 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
949 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000950
951 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000952 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000953
Faisal Vali67b04462016-06-11 16:41:54 +0000954 auto C = CurLSI->getCXXThisCapture();
955
956 if (C.isCopyCapture()) {
957 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
958 if (CurLSI->CallOperator->isConst())
959 ClassType.addConst();
960 return ASTCtx.getPointerType(ClassType);
961 }
962 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000963
964 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
965 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000966 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +0000967 assert(CurLSI && "While computing 'this' capture-type for a generic "
968 "lambda, we must have a corresponding LambdaScopeInfo");
969 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
970 "While computing 'this' capture-type for a generic lambda, when we "
971 "run out of enclosing LSI's, yet the enclosing DC is a "
972 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
973 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +0000974 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000975
Faisal Vali67b04462016-06-11 16:41:54 +0000976 auto IsThisCaptured =
977 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
978 IsConst = false;
979 IsByCopy = false;
980 for (auto &&C : Closure->captures()) {
981 if (C.capturesThis()) {
982 if (C.getCaptureKind() == LCK_StarThis)
983 IsByCopy = true;
984 if (Closure->getLambdaCallOperator()->isConst())
985 IsConst = true;
986 return true;
987 }
988 }
989 return false;
990 };
991
992 bool IsByCopyCapture = false;
993 bool IsConstCapture = false;
994 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
995 while (Closure &&
996 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
997 if (IsByCopyCapture) {
998 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
999 if (IsConstCapture)
1000 ClassType.addConst();
1001 return ASTCtx.getPointerType(ClassType);
1002 }
1003 Closure = isLambdaCallOperator(Closure->getParent())
1004 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1005 : nullptr;
1006 }
1007 }
1008 return ASTCtx.getPointerType(ClassType);
1009}
1010
Eli Friedman73a04092012-01-07 04:59:52 +00001011QualType Sema::getCurrentThisType() {
1012 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001013 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001014
Richard Smith938f40b2011-06-11 17:19:42 +00001015 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1016 if (method && method->isInstance())
1017 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001018 }
Faisal Validc6b5962016-03-21 09:25:37 +00001019
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001020 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001021 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001022
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001023 assert(isa<CXXRecordDecl>(DC) &&
1024 "Trying to get 'this' type from static method?");
1025
1026 // This is a lambda call operator that is being instantiated as a default
1027 // initializer. DC must point to the enclosing class type, so we can recover
1028 // the 'this' type from it.
1029
1030 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1031 // There are no cv-qualifiers for 'this' within default initializers,
1032 // per [expr.prim.general]p4.
1033 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001034 }
Faisal Vali67b04462016-06-11 16:41:54 +00001035
1036 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1037 // might need to be adjusted if the lambda or any of its enclosing lambda's
1038 // captures '*this' by copy.
1039 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1040 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1041 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001042 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001043}
1044
Simon Pilgrim75c26882016-09-30 14:25:09 +00001045Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001046 Decl *ContextDecl,
1047 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001048 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001049 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1050{
1051 if (!Enabled || !ContextDecl)
1052 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001053
1054 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001055 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1056 Record = Template->getTemplatedDecl();
1057 else
1058 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001059
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001060 // We care only for CVR qualifiers here, so cut everything else.
1061 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001062 S.CXXThisTypeOverride
1063 = S.Context.getPointerType(
1064 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001065
Douglas Gregor3024f072012-04-16 07:05:22 +00001066 this->Enabled = true;
1067}
1068
1069
1070Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1071 if (Enabled) {
1072 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1073 }
1074}
1075
Faisal Validc6b5962016-03-21 09:25:37 +00001076static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1077 QualType ThisTy, SourceLocation Loc,
1078 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001079
Faisal Vali67b04462016-06-11 16:41:54 +00001080 QualType AdjustedThisTy = ThisTy;
1081 // The type of the corresponding data member (not a 'this' pointer if 'by
1082 // copy').
1083 QualType CaptureThisFieldTy = ThisTy;
1084 if (ByCopy) {
1085 // If we are capturing the object referred to by '*this' by copy, ignore any
1086 // cv qualifiers inherited from the type of the member function for the type
1087 // of the closure-type's corresponding data member and any use of 'this'.
1088 CaptureThisFieldTy = ThisTy->getPointeeType();
1089 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1090 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1091 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001092
Faisal Vali67b04462016-06-11 16:41:54 +00001093 FieldDecl *Field = FieldDecl::Create(
1094 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1095 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1096 ICIS_NoInit);
1097
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001098 Field->setImplicit(true);
1099 Field->setAccess(AS_private);
1100 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001101 Expr *This =
1102 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001103 if (ByCopy) {
1104 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1105 UO_Deref,
1106 This).get();
1107 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001108 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001109 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1110 InitializationSequence Init(S, Entity, InitKind, StarThis);
1111 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1112 if (ER.isInvalid()) return nullptr;
1113 return ER.get();
1114 }
1115 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001116}
1117
Simon Pilgrim75c26882016-09-30 14:25:09 +00001118bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001119 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1120 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001121 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001122 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001123 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001124
Faisal Validc6b5962016-03-21 09:25:37 +00001125 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001126
Reid Kleckner87a31802018-03-12 21:43:02 +00001127 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1128 ? *FunctionScopeIndexToStopAt
1129 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001130
Simon Pilgrim75c26882016-09-30 14:25:09 +00001131 // Check that we can capture the *enclosing object* (referred to by '*this')
1132 // by the capturing-entity/closure (lambda/block/etc) at
1133 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1134
1135 // Note: The *enclosing object* can only be captured by-value by a
1136 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001137 // [*this] { ... }.
1138 // Every other capture of the *enclosing object* results in its by-reference
1139 // capture.
1140
1141 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1142 // stack), we can capture the *enclosing object* only if:
1143 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1144 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001145 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001146 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001147 // -- or, there is some enclosing closure 'E' that has already captured the
1148 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001149 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001150 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001151 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001152
1153
Faisal Validc6b5962016-03-21 09:25:37 +00001154 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001155 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001156 if (CapturingScopeInfo *CSI =
1157 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1158 if (CSI->CXXThisCaptureIndex != 0) {
1159 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001160 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001161 break;
1162 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001163 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1164 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1165 // This context can't implicitly capture 'this'; fail out.
1166 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001167 Diag(Loc, diag::err_this_capture)
1168 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001169 return true;
1170 }
Eli Friedman20139d32012-01-11 02:36:31 +00001171 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001172 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001173 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001174 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001175 (Explicit && idx == MaxFunctionScopesIndex)) {
1176 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1177 // iteration through can be an explicit capture, all enclosing closures,
1178 // if any, must perform implicit captures.
1179
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001180 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001181 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001182 continue;
1183 }
Eli Friedman20139d32012-01-11 02:36:31 +00001184 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001185 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001186 Diag(Loc, diag::err_this_capture)
1187 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001188 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001189 }
Eli Friedman73a04092012-01-07 04:59:52 +00001190 break;
1191 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001192 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001193
1194 // If we got here, then the closure at MaxFunctionScopesIndex on the
1195 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1196 // (including implicit by-reference captures in any enclosing closures).
1197
1198 // In the loop below, respect the ByCopy flag only for the closure requesting
1199 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001200 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001201 // implicitly capturing the *enclosing object* by reference (see loop
1202 // above)).
1203 assert((!ByCopy ||
1204 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1205 "Only a lambda can capture the enclosing object (referred to by "
1206 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001207 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1208 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001209 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001210 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1211 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001212 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001213 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001214
Faisal Validc6b5962016-03-21 09:25:37 +00001215 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1216 // For lambda expressions, build a field and an initializing expression,
1217 // and capture the *enclosing object* by copy only if this is the first
1218 // iteration.
1219 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1220 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001221
Faisal Validc6b5962016-03-21 09:25:37 +00001222 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001223 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001224 ThisExpr =
1225 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1226 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001227
Faisal Validc6b5962016-03-21 09:25:37 +00001228 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001229 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001230 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001231 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001232}
1233
Richard Smith938f40b2011-06-11 17:19:42 +00001234ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001235 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1236 /// is a non-lvalue expression whose value is the address of the object for
1237 /// which the function is called.
1238
Douglas Gregor09deffa2011-10-18 16:47:30 +00001239 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001240 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001241
Eli Friedman73a04092012-01-07 04:59:52 +00001242 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001243 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001244}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001245
Douglas Gregor3024f072012-04-16 07:05:22 +00001246bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1247 // If we're outside the body of a member function, then we'll have a specified
1248 // type for 'this'.
1249 if (CXXThisTypeOverride.isNull())
1250 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001251
Douglas Gregor3024f072012-04-16 07:05:22 +00001252 // Determine whether we're looking into a class that's currently being
1253 // defined.
1254 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1255 return Class && Class->isBeingDefined();
1256}
1257
Vedant Kumara14a1f92018-01-17 18:53:51 +00001258/// Parse construction of a specified type.
1259/// Can be interpreted either as function-style casting ("int(x)")
1260/// or class type construction ("ClassType(x,y,z)")
1261/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001262ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001263Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001264 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001265 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001266 SourceLocation RParenOrBraceLoc,
1267 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001268 if (!TypeRep)
1269 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
John McCall97513962010-01-15 18:39:57 +00001271 TypeSourceInfo *TInfo;
1272 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1273 if (!TInfo)
1274 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001275
Vedant Kumara14a1f92018-01-17 18:53:51 +00001276 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1277 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001278 // Avoid creating a non-type-dependent expression that contains typos.
1279 // Non-type-dependent expressions are liable to be discarded without
1280 // checking for embedded typos.
1281 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1282 !Result.get()->isTypeDependent())
1283 Result = CorrectDelayedTyposInExpr(Result.get());
1284 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001285}
1286
Douglas Gregor2b88c112010-09-08 00:15:04 +00001287ExprResult
1288Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001289 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001290 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001291 SourceLocation RParenOrBraceLoc,
1292 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001293 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001294 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001295
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001296 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001297 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1298 // directly. We work around this by dropping the locations of the braces.
1299 SourceRange Locs = ListInitialization
1300 ? SourceRange()
1301 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1302 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1303 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001304 }
1305
Richard Smith600b5262017-01-26 20:40:47 +00001306 assert((!ListInitialization ||
1307 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1308 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001309 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001310
Richard Smith60437622017-02-09 19:17:44 +00001311 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1312 InitializationKind Kind =
1313 Exprs.size()
1314 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001315 ? InitializationKind::CreateDirectList(
1316 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1317 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1318 RParenOrBraceLoc)
1319 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1320 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001321
1322 // C++1z [expr.type.conv]p1:
1323 // If the type is a placeholder for a deduced class type, [...perform class
1324 // template argument deduction...]
1325 DeducedType *Deduced = Ty->getContainedDeducedType();
1326 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1327 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1328 Kind, Exprs);
1329 if (Ty.isNull())
1330 return ExprError();
1331 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1332 }
1333
Douglas Gregordd04d332009-01-16 18:33:17 +00001334 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001335 // If the expression list is a parenthesized single expression, the type
1336 // conversion expression is equivalent (in definedness, and if defined in
1337 // meaning) to the corresponding cast expression.
1338 if (Exprs.size() == 1 && !ListInitialization &&
1339 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001340 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001341 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1342 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001343 }
1344
Richard Smith49a6b6e2017-03-24 01:14:25 +00001345 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001346 QualType ElemTy = Ty;
1347 if (Ty->isArrayType()) {
1348 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001349 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1350 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001351 ElemTy = Context.getBaseElementType(Ty);
1352 }
1353
Richard Smith49a6b6e2017-03-24 01:14:25 +00001354 // There doesn't seem to be an explicit rule against this but sanity demands
1355 // we only construct objects with object types.
1356 if (Ty->isFunctionType())
1357 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1358 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001359
Richard Smith49a6b6e2017-03-24 01:14:25 +00001360 // C++17 [expr.type.conv]p2:
1361 // If the type is cv void and the initializer is (), the expression is a
1362 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001363 if (!Ty->isVoidType() &&
1364 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001365 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001366 return ExprError();
1367
Richard Smith49a6b6e2017-03-24 01:14:25 +00001368 // Otherwise, the expression is a prvalue of the specified type whose
1369 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001370 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1371 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001372
Richard Smith49a6b6e2017-03-24 01:14:25 +00001373 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001374 return Result;
1375
1376 Expr *Inner = Result.get();
1377 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1378 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001379 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1380 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001381 // If we created a CXXTemporaryObjectExpr, that node also represents the
1382 // functional cast. Otherwise, create an explicit cast to represent
1383 // the syntactic form of a functional-style cast that was used here.
1384 //
1385 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1386 // would give a more consistent AST representation than using a
1387 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1388 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001389 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001390 SourceRange Locs = ListInitialization
1391 ? SourceRange()
1392 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001393 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001394 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1395 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001396 }
1397
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001398 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001399}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001400
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001401/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001402/// deallocation function.
1403static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001404 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1405 return Method->isUsualDeallocationFunction();
1406
1407 if (FD->getOverloadedOperator() != OO_Delete &&
1408 FD->getOverloadedOperator() != OO_Array_Delete)
1409 return false;
1410
1411 unsigned UsualParams = 1;
1412
1413 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1414 S.Context.hasSameUnqualifiedType(
1415 FD->getParamDecl(UsualParams)->getType(),
1416 S.Context.getSizeType()))
1417 ++UsualParams;
1418
1419 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1420 S.Context.hasSameUnqualifiedType(
1421 FD->getParamDecl(UsualParams)->getType(),
1422 S.Context.getTypeDeclType(S.getStdAlignValT())))
1423 ++UsualParams;
1424
1425 return UsualParams == FD->getNumParams();
1426}
1427
1428namespace {
1429 struct UsualDeallocFnInfo {
1430 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001431 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001432 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001433 Destroying(false), HasSizeT(false), HasAlignValT(false),
1434 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001435 // A function template declaration is never a usual deallocation function.
1436 if (!FD)
1437 return;
Richard Smith5b349582017-10-13 01:55:36 +00001438 unsigned NumBaseParams = 1;
1439 if (FD->isDestroyingOperatorDelete()) {
1440 Destroying = true;
1441 ++NumBaseParams;
1442 }
1443 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001444 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001445 else if (FD->getNumParams() == NumBaseParams + 1) {
1446 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001447 HasAlignValT = !HasSizeT;
1448 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001449
1450 // In CUDA, determine how much we'd like / dislike to call this.
1451 if (S.getLangOpts().CUDA)
1452 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1453 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001454 }
1455
Eric Fiselierfa752f22018-03-21 19:19:48 +00001456 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001457
Richard Smithf75dcbe2016-10-11 00:21:10 +00001458 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1459 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001460 // C++ P0722:
1461 // A destroying operator delete is preferred over a non-destroying
1462 // operator delete.
1463 if (Destroying != Other.Destroying)
1464 return Destroying;
1465
Richard Smithf75dcbe2016-10-11 00:21:10 +00001466 // C++17 [expr.delete]p10:
1467 // If the type has new-extended alignment, a function with a parameter
1468 // of type std::align_val_t is preferred; otherwise a function without
1469 // such a parameter is preferred
1470 if (HasAlignValT != Other.HasAlignValT)
1471 return HasAlignValT == WantAlign;
1472
1473 if (HasSizeT != Other.HasSizeT)
1474 return HasSizeT == WantSize;
1475
1476 // Use CUDA call preference as a tiebreaker.
1477 return CUDAPref > Other.CUDAPref;
1478 }
1479
Richard Smithb2f0f052016-10-10 18:54:32 +00001480 DeclAccessPair Found;
1481 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001482 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001483 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001484 };
1485}
1486
1487/// Determine whether a type has new-extended alignment. This may be called when
1488/// the type is incomplete (for a delete-expression with an incomplete pointee
1489/// type), in which case it will conservatively return false if the alignment is
1490/// not known.
1491static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1492 return S.getLangOpts().AlignedAllocation &&
1493 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1494 S.getASTContext().getTargetInfo().getNewAlign();
1495}
1496
1497/// Select the correct "usual" deallocation function to use from a selection of
1498/// deallocation functions (either global or class-scope).
1499static UsualDeallocFnInfo resolveDeallocationOverload(
1500 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1501 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1502 UsualDeallocFnInfo Best;
1503
Richard Smithb2f0f052016-10-10 18:54:32 +00001504 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001505 UsualDeallocFnInfo Info(S, I.getPair());
1506 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1507 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001508 continue;
1509
1510 if (!Best) {
1511 Best = Info;
1512 if (BestFns)
1513 BestFns->push_back(Info);
1514 continue;
1515 }
1516
Richard Smithf75dcbe2016-10-11 00:21:10 +00001517 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001518 continue;
1519
1520 // If more than one preferred function is found, all non-preferred
1521 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001522 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001523 BestFns->clear();
1524
1525 Best = Info;
1526 if (BestFns)
1527 BestFns->push_back(Info);
1528 }
1529
1530 return Best;
1531}
1532
1533/// Determine whether a given type is a class for which 'delete[]' would call
1534/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1535/// we need to store the array size (even if the type is
1536/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001537static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1538 QualType allocType) {
1539 const RecordType *record =
1540 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1541 if (!record) return false;
1542
1543 // Try to find an operator delete[] in class scope.
1544
1545 DeclarationName deleteName =
1546 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1547 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1548 S.LookupQualifiedName(ops, record->getDecl());
1549
1550 // We're just doing this for information.
1551 ops.suppressDiagnostics();
1552
1553 // Very likely: there's no operator delete[].
1554 if (ops.empty()) return false;
1555
1556 // If it's ambiguous, it should be illegal to call operator delete[]
1557 // on this thing, so it doesn't matter if we allocate extra space or not.
1558 if (ops.isAmbiguous()) return false;
1559
Richard Smithb2f0f052016-10-10 18:54:32 +00001560 // C++17 [expr.delete]p10:
1561 // If the deallocation functions have class scope, the one without a
1562 // parameter of type std::size_t is selected.
1563 auto Best = resolveDeallocationOverload(
1564 S, ops, /*WantSize*/false,
1565 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1566 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001567}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001568
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001569/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001570///
Sebastian Redld74dd492012-02-12 18:41:05 +00001571/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001572/// @code new (memory) int[size][4] @endcode
1573/// or
1574/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001575///
1576/// \param StartLoc The first location of the expression.
1577/// \param UseGlobal True if 'new' was prefixed with '::'.
1578/// \param PlacementLParen Opening paren of the placement arguments.
1579/// \param PlacementArgs Placement new arguments.
1580/// \param PlacementRParen Closing paren of the placement arguments.
1581/// \param TypeIdParens If the type is in parens, the source range.
1582/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001583/// \param Initializer The initializing expression or initializer-list, or null
1584/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001585ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001586Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001587 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001588 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001589 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001590 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001591 // If the specified type is an array, unwrap it and save the expression.
1592 if (D.getNumTypeObjects() > 0 &&
1593 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001594 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001595 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001596 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1597 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001598 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001599 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1600 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001601 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001602 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1603 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001604
Sebastian Redl351bb782008-12-02 14:43:59 +00001605 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001606 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001607 }
1608
Douglas Gregor73341c42009-09-11 00:18:58 +00001609 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001610 if (ArraySize) {
1611 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001612 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1613 break;
1614
1615 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1616 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001617 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001618 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001619 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1620 // shall be a converted constant expression (5.19) of type std::size_t
1621 // and shall evaluate to a strictly positive value.
1622 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1623 assert(IntWidth && "Builtin type of size 0?");
1624 llvm::APSInt Value(IntWidth);
1625 Array.NumElts
1626 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1627 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001628 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001629 } else {
1630 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001631 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001632 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001633 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001634 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001635 if (!Array.NumElts)
1636 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001637 }
1638 }
1639 }
1640 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001641
Craig Topperc3ec1492014-05-26 06:22:03 +00001642 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001643 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001644 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001645 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646
Sebastian Redl6047f072012-02-16 12:22:20 +00001647 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001648 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001649 DirectInitRange = List->getSourceRange();
1650
David Blaikie7b97aef2012-11-07 00:12:38 +00001651 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001652 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001653 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001654 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001655 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001656 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001657 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001658 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001659 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001660 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001661}
1662
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001663static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1664 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001665 if (!Init)
1666 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001667 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1668 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001669 if (isa<ImplicitValueInitExpr>(Init))
1670 return true;
1671 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1672 return !CCE->isListInitialization() &&
1673 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001674 else if (Style == CXXNewExpr::ListInit) {
1675 assert(isa<InitListExpr>(Init) &&
1676 "Shouldn't create list CXXConstructExprs for arrays.");
1677 return true;
1678 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001679 return false;
1680}
1681
Akira Hatanakacae83f72017-06-29 18:48:40 +00001682// Emit a diagnostic if an aligned allocation/deallocation function that is not
1683// implemented in the standard library is selected.
1684static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1685 SourceLocation Loc, bool IsDelete,
1686 Sema &S) {
1687 if (!S.getLangOpts().AlignedAllocationUnavailable)
1688 return;
1689
1690 // Return if there is a definition.
1691 if (FD.isDefined())
1692 return;
1693
1694 bool IsAligned = false;
1695 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001696 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1697 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1698 S.getASTContext().getTargetInfo().getPlatformName());
1699
Akira Hatanakacae83f72017-06-29 18:48:40 +00001700 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001701 << IsDelete << FD.getType().getAsString() << OSName
1702 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001703 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1704 }
1705}
1706
John McCalldadc5752010-08-24 06:29:42 +00001707ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001708Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001709 SourceLocation PlacementLParen,
1710 MultiExprArg PlacementArgs,
1711 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001712 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001713 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001714 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001715 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001716 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001717 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001718 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001719 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001720
Sebastian Redl6047f072012-02-16 12:22:20 +00001721 CXXNewExpr::InitializationStyle initStyle;
1722 if (DirectInitRange.isValid()) {
1723 assert(Initializer && "Have parens but no initializer.");
1724 initStyle = CXXNewExpr::CallInit;
1725 } else if (Initializer && isa<InitListExpr>(Initializer))
1726 initStyle = CXXNewExpr::ListInit;
1727 else {
1728 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1729 isa<CXXConstructExpr>(Initializer)) &&
1730 "Initializer expression that cannot have been implicitly created.");
1731 initStyle = CXXNewExpr::NoInit;
1732 }
1733
1734 Expr **Inits = &Initializer;
1735 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001736 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1737 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1738 Inits = List->getExprs();
1739 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001740 }
1741
Richard Smith60437622017-02-09 19:17:44 +00001742 // C++11 [expr.new]p15:
1743 // A new-expression that creates an object of type T initializes that
1744 // object as follows:
1745 InitializationKind Kind
1746 // - If the new-initializer is omitted, the object is default-
1747 // initialized (8.5); if no initialization is performed,
1748 // the object has indeterminate value
1749 = initStyle == CXXNewExpr::NoInit
1750 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1751 // - Otherwise, the new-initializer is interpreted according to the
1752 // initialization rules of 8.5 for direct-initialization.
1753 : initStyle == CXXNewExpr::ListInit
Vedant Kumara14a1f92018-01-17 18:53:51 +00001754 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1755 Initializer->getLocStart(),
1756 Initializer->getLocEnd())
Richard Smith60437622017-02-09 19:17:44 +00001757 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1758 DirectInitRange.getBegin(),
1759 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001760
Richard Smith60437622017-02-09 19:17:44 +00001761 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1762 auto *Deduced = AllocType->getContainedDeducedType();
1763 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1764 if (ArraySize)
1765 return ExprError(Diag(ArraySize->getExprLoc(),
1766 diag::err_deduced_class_template_compound_type)
1767 << /*array*/ 2 << ArraySize->getSourceRange());
1768
1769 InitializedEntity Entity
1770 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1771 AllocType = DeduceTemplateSpecializationFromInitializer(
1772 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1773 if (AllocType.isNull())
1774 return ExprError();
1775 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001776 bool Braced = (initStyle == CXXNewExpr::ListInit);
1777 if (NumInits == 1) {
1778 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1779 Inits = p->getInits();
1780 NumInits = p->getNumInits();
1781 Braced = true;
1782 }
1783 }
1784
Sebastian Redl6047f072012-02-16 12:22:20 +00001785 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001786 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1787 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001788 if (NumInits > 1) {
1789 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001790 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001791 diag::err_auto_new_ctor_multiple_expressions)
1792 << AllocType << TypeRange);
1793 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001794 if (Braced && !getLangOpts().CPlusPlus17)
1795 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1796 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001797 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001798 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001799 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001800 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001801 << AllocType << Deduce->getType()
1802 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001803 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001804 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001805 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001806 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001807
Douglas Gregorcda95f42010-05-16 16:01:03 +00001808 // Per C++0x [expr.new]p5, the type being constructed may be a
1809 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001810 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001811 if (const ConstantArrayType *Array
1812 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001813 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1814 Context.getSizeType(),
1815 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001816 AllocType = Array->getElementType();
1817 }
1818 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001819
Douglas Gregor3999e152010-10-06 16:00:31 +00001820 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1821 return ExprError();
1822
Craig Topperc3ec1492014-05-26 06:22:03 +00001823 if (initStyle == CXXNewExpr::ListInit &&
1824 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001825 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1826 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001827 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001828 }
1829
Simon Pilgrim75c26882016-09-30 14:25:09 +00001830 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001831 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001832 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1833 AllocType->isObjCLifetimeType()) {
1834 AllocType = Context.getLifetimeQualifiedType(AllocType,
1835 AllocType->getObjCARCImplicitLifetime());
1836 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001837
John McCall31168b02011-06-15 23:02:42 +00001838 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001839
John McCall5e77d762013-04-16 07:28:30 +00001840 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1841 ExprResult result = CheckPlaceholderExpr(ArraySize);
1842 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001843 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001844 }
Richard Smith8dd34252012-02-04 07:07:42 +00001845 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1846 // integral or enumeration type with a non-negative value."
1847 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1848 // enumeration type, or a class type for which a single non-explicit
1849 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001850 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001851 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001852 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001853 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001854 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001855 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001856 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1857
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001858 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1859 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001860
Simon Pilgrim75c26882016-09-30 14:25:09 +00001861 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001862 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001863 // Diagnose the compatibility of this conversion.
1864 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1865 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001866 } else {
1867 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1868 protected:
1869 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001870
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001871 public:
1872 SizeConvertDiagnoser(Expr *ArraySize)
1873 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1874 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001875
1876 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1877 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001878 return S.Diag(Loc, diag::err_array_size_not_integral)
1879 << S.getLangOpts().CPlusPlus11 << T;
1880 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001881
1882 SemaDiagnosticBuilder diagnoseIncomplete(
1883 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001884 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1885 << T << ArraySize->getSourceRange();
1886 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001887
1888 SemaDiagnosticBuilder diagnoseExplicitConv(
1889 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001890 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1891 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001892
1893 SemaDiagnosticBuilder noteExplicitConv(
1894 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001895 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1896 << ConvTy->isEnumeralType() << ConvTy;
1897 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001898
1899 SemaDiagnosticBuilder diagnoseAmbiguous(
1900 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001901 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1902 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001903
1904 SemaDiagnosticBuilder noteAmbiguous(
1905 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001906 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1907 << ConvTy->isEnumeralType() << ConvTy;
1908 }
Richard Smithccc11812013-05-21 19:05:48 +00001909
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001910 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1911 QualType T,
1912 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001913 return S.Diag(Loc,
1914 S.getLangOpts().CPlusPlus11
1915 ? diag::warn_cxx98_compat_array_size_conversion
1916 : diag::ext_array_size_conversion)
1917 << T << ConvTy->isEnumeralType() << ConvTy;
1918 }
1919 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001920
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001921 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1922 SizeDiagnoser);
1923 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001924 if (ConvertedSize.isInvalid())
1925 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001927 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001928 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001929
Douglas Gregor0bf31402010-10-08 23:50:27 +00001930 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001931 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001933 // C++98 [expr.new]p7:
1934 // The expression in a direct-new-declarator shall have integral type
1935 // with a non-negative value.
1936 //
Richard Smith0511d232016-10-05 22:41:02 +00001937 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1938 // per CWG1464. Otherwise, if it's not a constant, we must have an
1939 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001940 if (!ArraySize->isValueDependent()) {
1941 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001942 // We've already performed any required implicit conversion to integer or
1943 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001944 // FIXME: Per CWG1464, we are required to check the value prior to
1945 // converting to size_t. This will never find a negative array size in
1946 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001947 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001948 if (Value.isSigned() && Value.isNegative()) {
1949 return ExprError(Diag(ArraySize->getLocStart(),
1950 diag::err_typecheck_negative_array_size)
1951 << ArraySize->getSourceRange());
1952 }
1953
1954 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001955 unsigned ActiveSizeBits =
1956 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001957 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1958 return ExprError(Diag(ArraySize->getLocStart(),
1959 diag::err_array_too_large)
1960 << Value.toString(10)
1961 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001962 }
Richard Smith0511d232016-10-05 22:41:02 +00001963
1964 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001965 } else if (TypeIdParens.isValid()) {
1966 // Can't have dynamic array size when the type-id is in parentheses.
1967 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1968 << ArraySize->getSourceRange()
1969 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1970 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971
Douglas Gregorf2753b32010-07-13 15:54:32 +00001972 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001973 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
John McCall036f2f62011-05-15 07:14:44 +00001976 // Note that we do *not* convert the argument in any way. It can
1977 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001978 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001979
Craig Topperc3ec1492014-05-26 06:22:03 +00001980 FunctionDecl *OperatorNew = nullptr;
1981 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001982 unsigned Alignment =
1983 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1984 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1985 bool PassAlignment = getLangOpts().AlignedAllocation &&
1986 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Brian Gesiakcb024022018-04-01 22:59:22 +00001988 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001989 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001990 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001991 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001992 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00001993 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00001994 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001995 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001996
1997 // If this is an array allocation, compute whether the usual array
1998 // deallocation function for the type has a size_t parameter.
1999 bool UsualArrayDeleteWantsSize = false;
2000 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002001 UsualArrayDeleteWantsSize =
2002 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002003
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002004 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002005 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002007 OperatorNew->getType()->getAs<FunctionProtoType>();
2008 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2009 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002010
Richard Smithd6f9e732014-05-13 19:56:21 +00002011 // We've already converted the placement args, just fill in any default
2012 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002013 // argument. Skip the second parameter too if we're passing in the
2014 // alignment; we've already filled it in.
2015 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2016 PassAlignment ? 2 : 1, PlacementArgs,
2017 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002018 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002019
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002020 if (!AllPlaceArgs.empty())
2021 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002022
Richard Smithd6f9e732014-05-13 19:56:21 +00002023 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002024 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002025
2026 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027
Richard Smithb2f0f052016-10-10 18:54:32 +00002028 // Warn if the type is over-aligned and is being allocated by (unaligned)
2029 // global operator new.
2030 if (PlacementArgs.empty() && !PassAlignment &&
2031 (OperatorNew->isImplicit() ||
2032 (OperatorNew->getLocStart().isValid() &&
2033 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2034 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002035 Diag(StartLoc, diag::warn_overaligned_type)
2036 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002037 << unsigned(Alignment / Context.getCharWidth())
2038 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002039 }
2040 }
2041
Sebastian Redl6047f072012-02-16 12:22:20 +00002042 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002043 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2044 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002045 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2046 SourceRange InitRange(Inits[0]->getLocStart(),
2047 Inits[NumInits - 1]->getLocEnd());
2048 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2049 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002050 }
2051
Richard Smithdd2ca572012-11-26 08:32:48 +00002052 // If we can perform the initialization, and we've not already done so,
2053 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002054 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002055 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002056 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002057 // The type we initialize is the complete type, including the array bound.
2058 QualType InitType;
2059 if (KnownArraySize)
2060 InitType = Context.getConstantArrayType(
2061 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2062 *KnownArraySize),
2063 ArrayType::Normal, 0);
2064 else if (ArraySize)
2065 InitType =
2066 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2067 else
2068 InitType = AllocType;
2069
Douglas Gregor85dabae2009-12-16 01:38:02 +00002070 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002071 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002072 InitializationSequence InitSeq(*this, Entity, Kind,
2073 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002075 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002076 if (FullInit.isInvalid())
2077 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Sebastian Redl6047f072012-02-16 12:22:20 +00002079 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2080 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002081 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002082 if (CXXBindTemporaryExpr *Binder =
2083 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002084 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002086 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002088
Douglas Gregor6642ca22010-02-26 05:06:18 +00002089 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002090 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002091 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2092 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002093 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002094 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002095 }
2096 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002097 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2098 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002099 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002100 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002101 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002102
John McCall928a2572011-07-13 20:12:57 +00002103 // C++0x [expr.new]p17:
2104 // If the new expression creates an array of objects of class type,
2105 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002106 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2107 if (ArraySize && !BaseAllocType->isDependentType()) {
2108 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2109 if (CXXDestructorDecl *dtor = LookupDestructor(
2110 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2111 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002112 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002113 PDiag(diag::err_access_dtor)
2114 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002115 if (DiagnoseUseOfDecl(dtor, StartLoc))
2116 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002117 }
John McCall928a2572011-07-13 20:12:57 +00002118 }
2119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002120
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002121 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002122 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002123 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2124 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2125 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002126}
2127
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002128/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002129/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002130bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002131 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002132 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2133 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002134 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002135 return Diag(Loc, diag::err_bad_new_type)
2136 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002137 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002138 return Diag(Loc, diag::err_bad_new_type)
2139 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002140 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002141 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002142 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002143 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002144 diag::err_allocation_of_abstract_type))
2145 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002146 else if (AllocType->isVariablyModifiedType())
2147 return Diag(Loc, diag::err_variably_modified_new_type)
2148 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002149 else if (AllocType.getAddressSpace() != LangAS::Default &&
2150 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002151 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002152 << AllocType.getUnqualifiedType()
2153 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002154 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002155 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2156 QualType BaseAllocType = Context.getBaseElementType(AT);
2157 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2158 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002159 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002160 << BaseAllocType;
2161 }
2162 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002163
Sebastian Redlbd150f42008-11-21 19:14:01 +00002164 return false;
2165}
2166
Brian Gesiak87412d92018-02-15 20:09:25 +00002167static bool resolveAllocationOverload(
2168 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2169 bool &PassAlignment, FunctionDecl *&Operator,
2170 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002171 OverloadCandidateSet Candidates(R.getNameLoc(),
2172 OverloadCandidateSet::CSK_Normal);
2173 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2174 Alloc != AllocEnd; ++Alloc) {
2175 // Even member operator new/delete are implicitly treated as
2176 // static, so don't use AddMemberCandidate.
2177 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2178
2179 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2180 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2181 /*ExplicitTemplateArgs=*/nullptr, Args,
2182 Candidates,
2183 /*SuppressUserConversions=*/false);
2184 continue;
2185 }
2186
2187 FunctionDecl *Fn = cast<FunctionDecl>(D);
2188 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2189 /*SuppressUserConversions=*/false);
2190 }
2191
2192 // Do the resolution.
2193 OverloadCandidateSet::iterator Best;
2194 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2195 case OR_Success: {
2196 // Got one!
2197 FunctionDecl *FnDecl = Best->Function;
2198 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2199 Best->FoundDecl) == Sema::AR_inaccessible)
2200 return true;
2201
2202 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002203 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002204 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002205
Richard Smithb2f0f052016-10-10 18:54:32 +00002206 case OR_No_Viable_Function:
2207 // C++17 [expr.new]p13:
2208 // If no matching function is found and the allocated object type has
2209 // new-extended alignment, the alignment argument is removed from the
2210 // argument list, and overload resolution is performed again.
2211 if (PassAlignment) {
2212 PassAlignment = false;
2213 AlignArg = Args[1];
2214 Args.erase(Args.begin() + 1);
2215 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002216 Operator, &Candidates, AlignArg,
2217 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002218 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002219
Richard Smithb2f0f052016-10-10 18:54:32 +00002220 // MSVC will fall back on trying to find a matching global operator new
2221 // if operator new[] cannot be found. Also, MSVC will leak by not
2222 // generating a call to operator delete or operator delete[], but we
2223 // will not replicate that bug.
2224 // FIXME: Find out how this interacts with the std::align_val_t fallback
2225 // once MSVC implements it.
2226 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2227 S.Context.getLangOpts().MSVCCompat) {
2228 R.clear();
2229 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2230 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2231 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2232 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002233 Operator, /*Candidates=*/nullptr,
2234 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002235 }
Richard Smith1cdec012013-09-29 04:40:38 +00002236
Brian Gesiak87412d92018-02-15 20:09:25 +00002237 if (Diagnose) {
2238 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2239 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002240
Brian Gesiak87412d92018-02-15 20:09:25 +00002241 // If we have aligned candidates, only note the align_val_t candidates
2242 // from AlignedCandidates and the non-align_val_t candidates from
2243 // Candidates.
2244 if (AlignedCandidates) {
2245 auto IsAligned = [](OverloadCandidate &C) {
2246 return C.Function->getNumParams() > 1 &&
2247 C.Function->getParamDecl(1)->getType()->isAlignValT();
2248 };
2249 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002250
Brian Gesiak87412d92018-02-15 20:09:25 +00002251 // This was an overaligned allocation, so list the aligned candidates
2252 // first.
2253 Args.insert(Args.begin() + 1, AlignArg);
2254 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2255 R.getNameLoc(), IsAligned);
2256 Args.erase(Args.begin() + 1);
2257 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2258 IsUnaligned);
2259 } else {
2260 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2261 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002262 }
Richard Smith1cdec012013-09-29 04:40:38 +00002263 return true;
2264
Richard Smithb2f0f052016-10-10 18:54:32 +00002265 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002266 if (Diagnose) {
2267 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2268 << R.getLookupName() << Range;
2269 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2270 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002271 return true;
2272
2273 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002274 if (Diagnose) {
2275 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2276 << Best->Function->isDeleted() << R.getLookupName()
2277 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2278 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2279 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002280 return true;
2281 }
2282 }
2283 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002284}
2285
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002286bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002287 AllocationFunctionScope NewScope,
2288 AllocationFunctionScope DeleteScope,
2289 QualType AllocType, bool IsArray,
2290 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002291 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002292 FunctionDecl *&OperatorDelete,
2293 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002294 // --- Choosing an allocation function ---
2295 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002296 // 1) If looking in AFS_Global scope for allocation functions, only look in
2297 // the global scope. Else, if AFS_Class, only look in the scope of the
2298 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002299 // 2) If an array size is given, look for operator new[], else look for
2300 // operator new.
2301 // 3) The first argument is always size_t. Append the arguments from the
2302 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002303
Richard Smithb2f0f052016-10-10 18:54:32 +00002304 SmallVector<Expr*, 8> AllocArgs;
2305 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2306
2307 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002308 // FIXME: Should the Sema create the expression and embed it in the syntax
2309 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002310 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002311 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002312 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002313 Context.getSizeType(),
2314 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002315 AllocArgs.push_back(&Size);
2316
2317 QualType AlignValT = Context.VoidTy;
2318 if (PassAlignment) {
2319 DeclareGlobalNewDelete();
2320 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2321 }
2322 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2323 if (PassAlignment)
2324 AllocArgs.push_back(&Align);
2325
2326 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002327
Douglas Gregor6642ca22010-02-26 05:06:18 +00002328 // C++ [expr.new]p8:
2329 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002330 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002331 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002332 // type, the allocation function's name is operator new[] and the
2333 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002334 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002335 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002336
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002337 QualType AllocElemType = Context.getBaseElementType(AllocType);
2338
Richard Smithb2f0f052016-10-10 18:54:32 +00002339 // Find the allocation function.
2340 {
2341 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2342
2343 // C++1z [expr.new]p9:
2344 // If the new-expression begins with a unary :: operator, the allocation
2345 // function's name is looked up in the global scope. Otherwise, if the
2346 // allocated type is a class type T or array thereof, the allocation
2347 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002348 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002349 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2350
2351 // We can see ambiguity here if the allocation function is found in
2352 // multiple base classes.
2353 if (R.isAmbiguous())
2354 return true;
2355
2356 // If this lookup fails to find the name, or if the allocated type is not
2357 // a class type, the allocation function's name is looked up in the
2358 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002359 if (R.empty()) {
2360 if (NewScope == AFS_Class)
2361 return true;
2362
Richard Smithb2f0f052016-10-10 18:54:32 +00002363 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002364 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002365
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002366 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2367 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2368 return true;
2369 }
2370
Richard Smithb2f0f052016-10-10 18:54:32 +00002371 assert(!R.empty() && "implicitly declared allocation functions not found");
2372 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2373
2374 // We do our own custom access checks below.
2375 R.suppressDiagnostics();
2376
2377 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002378 OperatorNew, /*Candidates=*/nullptr,
2379 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002380 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002381 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002382
Richard Smithb2f0f052016-10-10 18:54:32 +00002383 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002384 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002385 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002386 return false;
2387 }
2388
Richard Smithb2f0f052016-10-10 18:54:32 +00002389 // Note, the name of OperatorNew might have been changed from array to
2390 // non-array by resolveAllocationOverload.
2391 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2392 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2393 ? OO_Array_Delete
2394 : OO_Delete);
2395
Douglas Gregor6642ca22010-02-26 05:06:18 +00002396 // C++ [expr.new]p19:
2397 //
2398 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002399 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002400 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002401 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002402 // the scope of T. If this lookup fails to find the name, or if
2403 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002404 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002405 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002406 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002407 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002408 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002409 LookupQualifiedName(FoundDelete, RD);
2410 }
John McCallfb6f5262010-03-18 08:19:33 +00002411 if (FoundDelete.isAmbiguous())
2412 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002413
Richard Smithb2f0f052016-10-10 18:54:32 +00002414 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002415 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002416 if (DeleteScope == AFS_Class)
2417 return true;
2418
Douglas Gregor6642ca22010-02-26 05:06:18 +00002419 DeclareGlobalNewDelete();
2420 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2421 }
2422
2423 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002424
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002425 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002426
John McCalld3be2c82010-09-14 21:34:24 +00002427 // Whether we're looking for a placement operator delete is dictated
2428 // by whether we selected a placement operator new, not by whether
2429 // we had explicit placement arguments. This matters for things like
2430 // struct A { void *operator new(size_t, int = 0); ... };
2431 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002432 //
2433 // We don't have any definition for what a "placement allocation function"
2434 // is, but we assume it's any allocation function whose
2435 // parameter-declaration-clause is anything other than (size_t).
2436 //
2437 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2438 // This affects whether an exception from the constructor of an overaligned
2439 // type uses the sized or non-sized form of aligned operator delete.
2440 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2441 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002442
2443 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002444 // C++ [expr.new]p20:
2445 // A declaration of a placement deallocation function matches the
2446 // declaration of a placement allocation function if it has the
2447 // same number of parameters and, after parameter transformations
2448 // (8.3.5), all parameter types except the first are
2449 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002451 // To perform this comparison, we compute the function type that
2452 // the deallocation function should have, and use that type both
2453 // for template argument deduction and for comparison purposes.
2454 QualType ExpectedFunctionType;
2455 {
2456 const FunctionProtoType *Proto
2457 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002458
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002459 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002461 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2462 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002463
John McCalldb40c7f2010-12-14 08:05:40 +00002464 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002465 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002466 EPI.Variadic = Proto->isVariadic();
2467
Douglas Gregor6642ca22010-02-26 05:06:18 +00002468 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002469 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002470 }
2471
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002472 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002473 DEnd = FoundDelete.end();
2474 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002475 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002476 if (FunctionTemplateDecl *FnTmpl =
2477 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002478 // Perform template argument deduction to try to match the
2479 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002480 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002481 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2482 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002483 continue;
2484 } else
2485 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2486
Richard Smithbaa47832016-12-01 02:11:49 +00002487 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2488 ExpectedFunctionType,
2489 /*AdjustExcpetionSpec*/true),
2490 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002491 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002492 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002493
Richard Smithb2f0f052016-10-10 18:54:32 +00002494 if (getLangOpts().CUDA)
2495 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2496 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002497 // C++1y [expr.new]p22:
2498 // For a non-placement allocation function, the normal deallocation
2499 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002500 //
2501 // Per [expr.delete]p10, this lookup prefers a member operator delete
2502 // without a size_t argument, but prefers a non-member operator delete
2503 // with a size_t where possible (which it always is in this case).
2504 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2505 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2506 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2507 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2508 &BestDeallocFns);
2509 if (Selected)
2510 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2511 else {
2512 // If we failed to select an operator, all remaining functions are viable
2513 // but ambiguous.
2514 for (auto Fn : BestDeallocFns)
2515 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002516 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002517 }
2518
2519 // C++ [expr.new]p20:
2520 // [...] If the lookup finds a single matching deallocation
2521 // function, that function will be called; otherwise, no
2522 // deallocation function will be called.
2523 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002524 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002525
Richard Smithb2f0f052016-10-10 18:54:32 +00002526 // C++1z [expr.new]p23:
2527 // If the lookup finds a usual deallocation function (3.7.4.2)
2528 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002529 // as a placement deallocation function, would have been
2530 // selected as a match for the allocation function, the program
2531 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002532 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002533 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002534 UsualDeallocFnInfo Info(*this,
2535 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002536 // Core issue, per mail to core reflector, 2016-10-09:
2537 // If this is a member operator delete, and there is a corresponding
2538 // non-sized member operator delete, this isn't /really/ a sized
2539 // deallocation function, it just happens to have a size_t parameter.
2540 bool IsSizedDelete = Info.HasSizeT;
2541 if (IsSizedDelete && !FoundGlobalDelete) {
2542 auto NonSizedDelete =
2543 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2544 /*WantAlign*/Info.HasAlignValT);
2545 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2546 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2547 IsSizedDelete = false;
2548 }
2549
2550 if (IsSizedDelete) {
2551 SourceRange R = PlaceArgs.empty()
2552 ? SourceRange()
2553 : SourceRange(PlaceArgs.front()->getLocStart(),
2554 PlaceArgs.back()->getLocEnd());
2555 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2556 if (!OperatorDelete->isImplicit())
2557 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2558 << DeleteName;
2559 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002560 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002561
2562 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2563 Matches[0].first);
2564 } else if (!Matches.empty()) {
2565 // We found multiple suitable operators. Per [expr.new]p20, that means we
2566 // call no 'operator delete' function, but we should at least warn the user.
2567 // FIXME: Suppress this warning if the construction cannot throw.
2568 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2569 << DeleteName << AllocElemType;
2570
2571 for (auto &Match : Matches)
2572 Diag(Match.second->getLocation(),
2573 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002574 }
2575
Sebastian Redlfaf68082008-12-03 20:26:15 +00002576 return false;
2577}
2578
2579/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2580/// delete. These are:
2581/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002582/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002583/// void* operator new(std::size_t) throw(std::bad_alloc);
2584/// void* operator new[](std::size_t) throw(std::bad_alloc);
2585/// void operator delete(void *) throw();
2586/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002587/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002588/// void* operator new(std::size_t);
2589/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002590/// void operator delete(void *) noexcept;
2591/// void operator delete[](void *) noexcept;
2592/// // C++1y:
2593/// void* operator new(std::size_t);
2594/// void* operator new[](std::size_t);
2595/// void operator delete(void *) noexcept;
2596/// void operator delete[](void *) noexcept;
2597/// void operator delete(void *, std::size_t) noexcept;
2598/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002599/// @endcode
2600/// Note that the placement and nothrow forms of new are *not* implicitly
2601/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002602void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002603 if (GlobalNewDeleteDeclared)
2604 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002605
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002606 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2607 // are not supported.
2608 if (getLangOpts().OpenCLCPlusPlus)
2609 return;
2610
Douglas Gregor87f54062009-09-15 22:30:29 +00002611 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612 // [...] The following allocation and deallocation functions (18.4) are
2613 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002614 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615 //
Sebastian Redl37588092011-03-14 18:08:30 +00002616 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002617 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618 // void* operator new[](std::size_t) throw(std::bad_alloc);
2619 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002620 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002621 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002622 // void* operator new(std::size_t);
2623 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002624 // void operator delete(void*) noexcept;
2625 // void operator delete[](void*) noexcept;
2626 // C++1y:
2627 // void* operator new(std::size_t);
2628 // void* operator new[](std::size_t);
2629 // void operator delete(void*) noexcept;
2630 // void operator delete[](void*) noexcept;
2631 // void operator delete(void*, std::size_t) noexcept;
2632 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002633 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002635 // new, operator new[], operator delete, operator delete[].
2636 //
2637 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2638 // "std" or "bad_alloc" as necessary to form the exception specification.
2639 // However, we do not make these implicit declarations visible to name
2640 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002641 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002642 // The "std::bad_alloc" class has not yet been declared, so build it
2643 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002644 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2645 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002646 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002647 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002648 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002649 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002650 }
Richard Smith59139022016-09-30 22:41:36 +00002651 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002652 // The "std::align_val_t" enum class has not yet been declared, so build it
2653 // implicitly.
2654 auto *AlignValT = EnumDecl::Create(
2655 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2656 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2657 AlignValT->setIntegerType(Context.getSizeType());
2658 AlignValT->setPromotionType(Context.getSizeType());
2659 AlignValT->setImplicit(true);
2660 StdAlignValT = AlignValT;
2661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662
Sebastian Redlfaf68082008-12-03 20:26:15 +00002663 GlobalNewDeleteDeclared = true;
2664
2665 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2666 QualType SizeT = Context.getSizeType();
2667
Richard Smith96269c52016-09-29 22:49:46 +00002668 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2669 QualType Return, QualType Param) {
2670 llvm::SmallVector<QualType, 3> Params;
2671 Params.push_back(Param);
2672
2673 // Create up to four variants of the function (sized/aligned).
2674 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2675 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002676 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002677
2678 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2679 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2680 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002681 if (Sized)
2682 Params.push_back(SizeT);
2683
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002684 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002685 if (Aligned)
2686 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2687
2688 DeclareGlobalAllocationFunction(
2689 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2690
2691 if (Aligned)
2692 Params.pop_back();
2693 }
2694 }
2695 };
2696
2697 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2698 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2699 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2700 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002701}
2702
2703/// DeclareGlobalAllocationFunction - Declares a single implicit global
2704/// allocation function if it doesn't already exist.
2705void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002706 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002707 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002708 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2709
2710 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002711 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2712 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2713 Alloc != AllocEnd; ++Alloc) {
2714 // Only look at non-template functions, as it is the predefined,
2715 // non-templated allocation function we are trying to declare here.
2716 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002717 if (Func->getNumParams() == Params.size()) {
2718 llvm::SmallVector<QualType, 3> FuncParams;
2719 for (auto *P : Func->parameters())
2720 FuncParams.push_back(
2721 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2722 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002723 // Make the function visible to name lookup, even if we found it in
2724 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002725 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002726 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002727 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002728 }
Chandler Carruth93538422010-02-03 11:02:14 +00002729 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002730 }
2731 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002732
Richard Smithc015bc22014-02-07 22:39:53 +00002733 FunctionProtoType::ExtProtoInfo EPI;
2734
Richard Smithf8b417c2014-02-08 00:42:45 +00002735 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002736 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002737 = (Name.getCXXOverloadedOperator() == OO_New ||
2738 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002739 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002740 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002741 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002742 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002743 EPI.ExceptionSpec.Type = EST_Dynamic;
2744 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002745 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002746 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002747 EPI.ExceptionSpec =
2748 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002750
Artem Belevich07db5cf2016-10-21 20:34:05 +00002751 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2752 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2753 FunctionDecl *Alloc = FunctionDecl::Create(
2754 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2755 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2756 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002757 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002758 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002759
Artem Belevich07db5cf2016-10-21 20:34:05 +00002760 // Implicit sized deallocation functions always have default visibility.
2761 Alloc->addAttr(
2762 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002763
Artem Belevich07db5cf2016-10-21 20:34:05 +00002764 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2765 for (QualType T : Params) {
2766 ParamDecls.push_back(ParmVarDecl::Create(
2767 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2768 /*TInfo=*/nullptr, SC_None, nullptr));
2769 ParamDecls.back()->setImplicit();
2770 }
2771 Alloc->setParams(ParamDecls);
2772 if (ExtraAttr)
2773 Alloc->addAttr(ExtraAttr);
2774 Context.getTranslationUnitDecl()->addDecl(Alloc);
2775 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2776 };
2777
2778 if (!LangOpts.CUDA)
2779 CreateAllocationFunctionDecl(nullptr);
2780 else {
2781 // Host and device get their own declaration so each can be
2782 // defined or re-declared independently.
2783 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2784 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002785 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002786}
2787
Richard Smith1cdec012013-09-29 04:40:38 +00002788FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2789 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002790 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002791 DeclarationName Name) {
2792 DeclareGlobalNewDelete();
2793
2794 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2795 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2796
Richard Smithb2f0f052016-10-10 18:54:32 +00002797 // FIXME: It's possible for this to result in ambiguity, through a
2798 // user-declared variadic operator delete or the enable_if attribute. We
2799 // should probably not consider those cases to be usual deallocation
2800 // functions. But for now we just make an arbitrary choice in that case.
2801 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2802 Overaligned);
2803 assert(Result.FD && "operator delete missing from global scope?");
2804 return Result.FD;
2805}
Richard Smith1cdec012013-09-29 04:40:38 +00002806
Richard Smithb2f0f052016-10-10 18:54:32 +00002807FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2808 CXXRecordDecl *RD) {
2809 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002810
Richard Smithb2f0f052016-10-10 18:54:32 +00002811 FunctionDecl *OperatorDelete = nullptr;
2812 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2813 return nullptr;
2814 if (OperatorDelete)
2815 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002816
Richard Smithb2f0f052016-10-10 18:54:32 +00002817 // If there's no class-specific operator delete, look up the global
2818 // non-array delete.
2819 return FindUsualDeallocationFunction(
2820 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2821 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002822}
2823
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002824bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2825 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002826 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002827 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002828 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002829 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830
John McCall27b18f82009-11-17 02:14:36 +00002831 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002832 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002833
Chandler Carruthb6f99172010-06-28 00:30:51 +00002834 Found.suppressDiagnostics();
2835
Richard Smithb2f0f052016-10-10 18:54:32 +00002836 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002837
Richard Smithb2f0f052016-10-10 18:54:32 +00002838 // C++17 [expr.delete]p10:
2839 // If the deallocation functions have class scope, the one without a
2840 // parameter of type std::size_t is selected.
2841 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2842 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2843 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002844
Richard Smithb2f0f052016-10-10 18:54:32 +00002845 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002846 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002847 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002848
Richard Smithb2f0f052016-10-10 18:54:32 +00002849 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002850 if (Operator->isDeleted()) {
2851 if (Diagnose) {
2852 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002853 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002854 }
2855 return true;
2856 }
2857
Richard Smith921bd202012-02-26 09:11:52 +00002858 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002859 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002860 return true;
2861
John McCall66a87592010-08-04 00:31:26 +00002862 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002863 }
John McCall66a87592010-08-04 00:31:26 +00002864
Richard Smithb2f0f052016-10-10 18:54:32 +00002865 // We found multiple suitable operators; complain about the ambiguity.
2866 // FIXME: The standard doesn't say to do this; it appears that the intent
2867 // is that this should never happen.
2868 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002869 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002870 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2871 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002872 for (auto &Match : Matches)
2873 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002874 }
John McCall66a87592010-08-04 00:31:26 +00002875 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002876 }
2877
2878 // We did find operator delete/operator delete[] declarations, but
2879 // none of them were suitable.
2880 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002881 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002882 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2883 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884
Richard Smithb2f0f052016-10-10 18:54:32 +00002885 for (NamedDecl *D : Found)
2886 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002887 diag::note_member_declared_here) << Name;
2888 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002889 return true;
2890 }
2891
Craig Topperc3ec1492014-05-26 06:22:03 +00002892 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002893 return false;
2894}
2895
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002896namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002897/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002898/// initializing deletee have the same array form.
2899class MismatchingNewDeleteDetector {
2900public:
2901 enum MismatchResult {
2902 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2903 NoMismatch,
2904 /// Indicates that variable is initialized with mismatching form of \a new.
2905 VarInitMismatches,
2906 /// Indicates that member is initialized with mismatching form of \a new.
2907 MemberInitMismatches,
2908 /// Indicates that 1 or more constructors' definitions could not been
2909 /// analyzed, and they will be checked again at the end of translation unit.
2910 AnalyzeLater
2911 };
2912
2913 /// \param EndOfTU True, if this is the final analysis at the end of
2914 /// translation unit. False, if this is the initial analysis at the point
2915 /// delete-expression was encountered.
2916 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002917 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002918 HasUndefinedConstructors(false) {}
2919
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002920 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002921 /// matching form of new-expression.
2922 ///
2923 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2924 /// point where delete-expression is encountered, then a warning will be
2925 /// issued immediately. If return value is \c AnalyzeLater at the point where
2926 /// delete-expression is seen, then member will be analyzed at the end of
2927 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2928 /// couldn't be analyzed. If at least one constructor initializes the member
2929 /// with matching type of new, the return value is \c NoMismatch.
2930 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002931 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002932 /// \param Field Class member to analyze.
2933 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2934 /// for deleting the \p Field.
2935 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002936 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002937 /// List of mismatching new-expressions used for initialization of the pointee
2938 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2939 /// Indicates whether delete-expression was in array form.
2940 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002941
2942private:
2943 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002944 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002945 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002946 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002947 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002948 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002949 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002950 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002951 /// \c new either by the member initializer or in-class initialization.
2952 ///
2953 /// If bodies of all constructors are not visible at the end of translation
2954 /// unit or at least one constructor initializes member with the matching
2955 /// form of \c new, mismatch cannot be proven, and this function will return
2956 /// \c NoMismatch.
2957 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002958 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002959 /// \c new.
2960 ///
2961 /// If variable is initialized with matching form of \c new or variable is not
2962 /// initialized with a \c new expression, this function will return true.
2963 /// If variable is initialized with mismatching form of \c new, returns false.
2964 /// \param D Variable to analyze.
2965 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002966 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002967 /// form of \c new.
2968 ///
2969 /// Returns true, if member is initialized with matching form of \c new in
2970 /// member initializer list. Returns false, if member is initialized with the
2971 /// matching form of \c new in this constructor's initializer or given
2972 /// constructor isn't defined at the point where delete-expression is seen, or
2973 /// member isn't initialized by the constructor.
2974 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002975 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002976 /// \c new in member initializer list.
2977 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2978 /// Checks whether member is initialized with mismatching form of \c new by
2979 /// in-class initializer.
2980 MismatchResult analyzeInClassInitializer();
2981};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002982}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002983
2984MismatchingNewDeleteDetector::MismatchResult
2985MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2986 NewExprs.clear();
2987 assert(DE && "Expected delete-expression");
2988 IsArrayForm = DE->isArrayForm();
2989 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2990 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2991 return analyzeMemberExpr(ME);
2992 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2993 if (!hasMatchingVarInit(D))
2994 return VarInitMismatches;
2995 }
2996 return NoMismatch;
2997}
2998
2999const CXXNewExpr *
3000MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3001 assert(E != nullptr && "Expected a valid initializer expression");
3002 E = E->IgnoreParenImpCasts();
3003 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3004 if (ILE->getNumInits() == 1)
3005 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3006 }
3007
3008 return dyn_cast_or_null<const CXXNewExpr>(E);
3009}
3010
3011bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3012 const CXXCtorInitializer *CI) {
3013 const CXXNewExpr *NE = nullptr;
3014 if (Field == CI->getMember() &&
3015 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3016 if (NE->isArray() == IsArrayForm)
3017 return true;
3018 else
3019 NewExprs.push_back(NE);
3020 }
3021 return false;
3022}
3023
3024bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3025 const CXXConstructorDecl *CD) {
3026 if (CD->isImplicit())
3027 return false;
3028 const FunctionDecl *Definition = CD;
3029 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3030 HasUndefinedConstructors = true;
3031 return EndOfTU;
3032 }
3033 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3034 if (hasMatchingNewInCtorInit(CI))
3035 return true;
3036 }
3037 return false;
3038}
3039
3040MismatchingNewDeleteDetector::MismatchResult
3041MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3042 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003043 const Expr *InitExpr = Field->getInClassInitializer();
3044 if (!InitExpr)
3045 return EndOfTU ? NoMismatch : AnalyzeLater;
3046 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003047 if (NE->isArray() != IsArrayForm) {
3048 NewExprs.push_back(NE);
3049 return MemberInitMismatches;
3050 }
3051 }
3052 return NoMismatch;
3053}
3054
3055MismatchingNewDeleteDetector::MismatchResult
3056MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3057 bool DeleteWasArrayForm) {
3058 assert(Field != nullptr && "Analysis requires a valid class member.");
3059 this->Field = Field;
3060 IsArrayForm = DeleteWasArrayForm;
3061 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3062 for (const auto *CD : RD->ctors()) {
3063 if (hasMatchingNewInCtor(CD))
3064 return NoMismatch;
3065 }
3066 if (HasUndefinedConstructors)
3067 return EndOfTU ? NoMismatch : AnalyzeLater;
3068 if (!NewExprs.empty())
3069 return MemberInitMismatches;
3070 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3071 : NoMismatch;
3072}
3073
3074MismatchingNewDeleteDetector::MismatchResult
3075MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3076 assert(ME != nullptr && "Expected a member expression");
3077 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3078 return analyzeField(F, IsArrayForm);
3079 return NoMismatch;
3080}
3081
3082bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3083 const CXXNewExpr *NE = nullptr;
3084 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3085 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3086 NE->isArray() != IsArrayForm) {
3087 NewExprs.push_back(NE);
3088 }
3089 }
3090 return NewExprs.empty();
3091}
3092
3093static void
3094DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3095 const MismatchingNewDeleteDetector &Detector) {
3096 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3097 FixItHint H;
3098 if (!Detector.IsArrayForm)
3099 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3100 else {
3101 SourceLocation RSquare = Lexer::findLocationAfterToken(
3102 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3103 SemaRef.getLangOpts(), true);
3104 if (RSquare.isValid())
3105 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3106 }
3107 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3108 << Detector.IsArrayForm << H;
3109
3110 for (const auto *NE : Detector.NewExprs)
3111 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3112 << Detector.IsArrayForm;
3113}
3114
3115void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3116 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3117 return;
3118 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3119 switch (Detector.analyzeDeleteExpr(DE)) {
3120 case MismatchingNewDeleteDetector::VarInitMismatches:
3121 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3122 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3123 break;
3124 }
3125 case MismatchingNewDeleteDetector::AnalyzeLater: {
3126 DeleteExprs[Detector.Field].push_back(
3127 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3128 break;
3129 }
3130 case MismatchingNewDeleteDetector::NoMismatch:
3131 break;
3132 }
3133}
3134
3135void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3136 bool DeleteWasArrayForm) {
3137 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3138 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3139 case MismatchingNewDeleteDetector::VarInitMismatches:
3140 llvm_unreachable("This analysis should have been done for class members.");
3141 case MismatchingNewDeleteDetector::AnalyzeLater:
3142 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3143 "translation unit.");
3144 case MismatchingNewDeleteDetector::MemberInitMismatches:
3145 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3146 break;
3147 case MismatchingNewDeleteDetector::NoMismatch:
3148 break;
3149 }
3150}
3151
Sebastian Redlbd150f42008-11-21 19:14:01 +00003152/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3153/// @code ::delete ptr; @endcode
3154/// or
3155/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003156ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003157Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003158 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003159 // C++ [expr.delete]p1:
3160 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003161 // non-explicit conversion function to a pointer type. The result has type
3162 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003163 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003164 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3165
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003166 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003167 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003168 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003169 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003170
John Wiegley01296292011-04-08 18:41:53 +00003171 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003172 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003173 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003174 if (Ex.isInvalid())
3175 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003176
John Wiegley01296292011-04-08 18:41:53 +00003177 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003178
Richard Smithccc11812013-05-21 19:05:48 +00003179 class DeleteConverter : public ContextualImplicitConverter {
3180 public:
3181 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182
Craig Toppere14c0f82014-03-12 04:55:44 +00003183 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003184 // FIXME: If we have an operator T* and an operator void*, we must pick
3185 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003186 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003187 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003188 return true;
3189 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003190 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003191
Richard Smithccc11812013-05-21 19:05:48 +00003192 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003193 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003194 return S.Diag(Loc, diag::err_delete_operand) << T;
3195 }
3196
3197 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003198 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003199 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3200 }
3201
3202 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003203 QualType T,
3204 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003205 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3206 }
3207
3208 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003209 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003210 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3211 << ConvTy;
3212 }
3213
3214 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003215 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003216 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3217 }
3218
3219 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003220 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003221 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3222 << ConvTy;
3223 }
3224
3225 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003226 QualType T,
3227 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003228 llvm_unreachable("conversion functions are permitted");
3229 }
3230 } Converter;
3231
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003232 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003233 if (Ex.isInvalid())
3234 return ExprError();
3235 Type = Ex.get()->getType();
3236 if (!Converter.match(Type))
3237 // FIXME: PerformContextualImplicitConversion should return ExprError
3238 // itself in this case.
3239 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003240
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003241 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003242 QualType PointeeElem = Context.getBaseElementType(Pointee);
3243
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003244 if (Pointee.getAddressSpace() != LangAS::Default &&
3245 !getLangOpts().OpenCLCPlusPlus)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003246 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003247 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003248 << Pointee.getUnqualifiedType()
3249 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003250
Craig Topperc3ec1492014-05-26 06:22:03 +00003251 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003252 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003254 // effectively bans deletion of "void*". However, most compilers support
3255 // this, so we treat it as a warning unless we're in a SFINAE context.
3256 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003257 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003258 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003259 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003260 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003261 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003262 // FIXME: This can result in errors if the definition was imported from a
3263 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003264 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003265 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003266 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3267 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3268 }
3269 }
3270
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003271 if (Pointee->isArrayType() && !ArrayForm) {
3272 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003273 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003274 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003275 ArrayForm = true;
3276 }
3277
Anders Carlssona471db02009-08-16 20:29:29 +00003278 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3279 ArrayForm ? OO_Array_Delete : OO_Delete);
3280
Eli Friedmanae4280f2011-07-26 22:25:31 +00003281 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003283 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3284 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003285 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286
John McCall284c48f2011-01-27 09:37:56 +00003287 // If we're allocating an array of records, check whether the
3288 // usual operator delete[] has a size_t parameter.
3289 if (ArrayForm) {
3290 // If the user specifically asked to use the global allocator,
3291 // we'll need to do the lookup into the class.
3292 if (UseGlobal)
3293 UsualArrayDeleteWantsSize =
3294 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3295
3296 // Otherwise, the usual operator delete[] should be the
3297 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003298 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003299 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003300 UsualDeallocFnInfo(*this,
3301 DeclAccessPair::make(OperatorDelete, AS_public))
3302 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003303 }
3304
Richard Smitheec915d62012-02-18 04:13:32 +00003305 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003306 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003307 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003308 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003309 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3310 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003311 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003312
Nico Weber5a9259c2016-01-15 21:45:31 +00003313 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3314 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3315 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3316 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318
Richard Smithb2f0f052016-10-10 18:54:32 +00003319 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003320 if (getLangOpts().OpenCLCPlusPlus) {
3321 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3322 return ExprError();
3323 }
3324
Richard Smithb2f0f052016-10-10 18:54:32 +00003325 bool IsComplete = isCompleteType(StartLoc, Pointee);
3326 bool CanProvideSize =
3327 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3328 Pointee.isDestructedType());
3329 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3330
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003331 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003332 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3333 Overaligned, DeleteName);
3334 }
Mike Stump11289f42009-09-09 15:08:12 +00003335
Eli Friedmanfa0df832012-02-02 03:46:19 +00003336 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003337
Richard Smith5b349582017-10-13 01:55:36 +00003338 // Check access and ambiguity of destructor if we're going to call it.
3339 // Note that this is required even for a virtual delete.
3340 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003341 if (PointeeRD) {
3342 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003343 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3344 PDiag(diag::err_access_dtor) << PointeeElem);
3345 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003346 }
3347 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003348
3349 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3350 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003351
3352 // Convert the operand to the type of the first parameter of operator
3353 // delete. This is only necessary if we selected a destroying operator
3354 // delete that we are going to call (non-virtually); converting to void*
3355 // is trivial and left to AST consumers to handle.
3356 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3357 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003358 Qualifiers Qs = Pointee.getQualifiers();
3359 if (Qs.hasCVRQualifiers()) {
3360 // Qualifiers are irrelevant to this conversion; we're only looking
3361 // for access and ambiguity.
3362 Qs.removeCVRQualifiers();
3363 QualType Unqual = Context.getPointerType(
3364 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3365 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3366 }
Richard Smith5b349582017-10-13 01:55:36 +00003367 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3368 if (Ex.isInvalid())
3369 return ExprError();
3370 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003371 }
3372
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003373 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003374 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3375 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003376 AnalyzeDeleteExprMismatch(Result);
3377 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003378}
3379
Eric Fiselierfa752f22018-03-21 19:19:48 +00003380static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3381 bool IsDelete,
3382 FunctionDecl *&Operator) {
3383
3384 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3385 IsDelete ? OO_Delete : OO_New);
3386
3387 LookupResult R(S, NewName, TheCall->getLocStart(), Sema::LookupOrdinaryName);
3388 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3389 assert(!R.empty() && "implicitly declared allocation functions not found");
3390 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3391
3392 // We do our own custom access checks below.
3393 R.suppressDiagnostics();
3394
3395 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3396 OverloadCandidateSet Candidates(R.getNameLoc(),
3397 OverloadCandidateSet::CSK_Normal);
3398 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3399 FnOvl != FnOvlEnd; ++FnOvl) {
3400 // Even member operator new/delete are implicitly treated as
3401 // static, so don't use AddMemberCandidate.
3402 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3403
3404 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3405 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3406 /*ExplicitTemplateArgs=*/nullptr, Args,
3407 Candidates,
3408 /*SuppressUserConversions=*/false);
3409 continue;
3410 }
3411
3412 FunctionDecl *Fn = cast<FunctionDecl>(D);
3413 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3414 /*SuppressUserConversions=*/false);
3415 }
3416
3417 SourceRange Range = TheCall->getSourceRange();
3418
3419 // Do the resolution.
3420 OverloadCandidateSet::iterator Best;
3421 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3422 case OR_Success: {
3423 // Got one!
3424 FunctionDecl *FnDecl = Best->Function;
3425 assert(R.getNamingClass() == nullptr &&
3426 "class members should not be considered");
3427
3428 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3429 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3430 << (IsDelete ? 1 : 0) << Range;
3431 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3432 << R.getLookupName() << FnDecl->getSourceRange();
3433 return true;
3434 }
3435
3436 Operator = FnDecl;
3437 return false;
3438 }
3439
3440 case OR_No_Viable_Function:
3441 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3442 << R.getLookupName() << Range;
3443 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3444 return true;
3445
3446 case OR_Ambiguous:
3447 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3448 << R.getLookupName() << Range;
3449 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3450 return true;
3451
3452 case OR_Deleted: {
3453 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3454 << Best->Function->isDeleted() << R.getLookupName()
3455 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3456 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3457 return true;
3458 }
3459 }
3460 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3461}
3462
3463ExprResult
3464Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3465 bool IsDelete) {
3466 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3467 if (!getLangOpts().CPlusPlus) {
3468 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3469 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3470 << "C++";
3471 return ExprError();
3472 }
3473 // CodeGen assumes it can find the global new and delete to call,
3474 // so ensure that they are declared.
3475 DeclareGlobalNewDelete();
3476
3477 FunctionDecl *OperatorNewOrDelete = nullptr;
3478 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3479 OperatorNewOrDelete))
3480 return ExprError();
3481 assert(OperatorNewOrDelete && "should be found");
3482
3483 TheCall->setType(OperatorNewOrDelete->getReturnType());
3484 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3485 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3486 InitializedEntity Entity =
3487 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3488 ExprResult Arg = PerformCopyInitialization(
3489 Entity, TheCall->getArg(i)->getLocStart(), TheCall->getArg(i));
3490 if (Arg.isInvalid())
3491 return ExprError();
3492 TheCall->setArg(i, Arg.get());
3493 }
3494 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3495 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3496 "Callee expected to be implicit cast to a builtin function pointer");
3497 Callee->setType(OperatorNewOrDelete->getType());
3498
3499 return TheCallResult;
3500}
3501
Nico Weber5a9259c2016-01-15 21:45:31 +00003502void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3503 bool IsDelete, bool CallCanBeVirtual,
3504 bool WarnOnNonAbstractTypes,
3505 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003506 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003507 return;
3508
3509 // C++ [expr.delete]p3:
3510 // In the first alternative (delete object), if the static type of the
3511 // object to be deleted is different from its dynamic type, the static
3512 // type shall be a base class of the dynamic type of the object to be
3513 // deleted and the static type shall have a virtual destructor or the
3514 // behavior is undefined.
3515 //
3516 const CXXRecordDecl *PointeeRD = dtor->getParent();
3517 // Note: a final class cannot be derived from, no issue there
3518 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3519 return;
3520
Nico Weberbf2260c2017-08-31 06:17:08 +00003521 // If the superclass is in a system header, there's nothing that can be done.
3522 // The `delete` (where we emit the warning) can be in a system header,
3523 // what matters for this warning is where the deleted type is defined.
3524 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3525 return;
3526
Nico Weber5a9259c2016-01-15 21:45:31 +00003527 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3528 if (PointeeRD->isAbstract()) {
3529 // If the class is abstract, we warn by default, because we're
3530 // sure the code has undefined behavior.
3531 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3532 << ClassType;
3533 } else if (WarnOnNonAbstractTypes) {
3534 // Otherwise, if this is not an array delete, it's a bit suspect,
3535 // but not necessarily wrong.
3536 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3537 << ClassType;
3538 }
3539 if (!IsDelete) {
3540 std::string TypeStr;
3541 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3542 Diag(DtorLoc, diag::note_delete_non_virtual)
3543 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3544 }
3545}
3546
Richard Smith03a4aa32016-06-23 19:02:52 +00003547Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3548 SourceLocation StmtLoc,
3549 ConditionKind CK) {
3550 ExprResult E =
3551 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3552 if (E.isInvalid())
3553 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003554 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3555 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003556}
3557
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003558/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003559/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003560ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003561 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003562 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003563 if (ConditionVar->isInvalidDecl())
3564 return ExprError();
3565
Douglas Gregor633caca2009-11-23 23:44:04 +00003566 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567
Douglas Gregor633caca2009-11-23 23:44:04 +00003568 // C++ [stmt.select]p2:
3569 // The declarator shall not specify a function or an array.
3570 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003572 diag::err_invalid_use_of_function_type)
3573 << ConditionVar->getSourceRange());
3574 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003576 diag::err_invalid_use_of_array_type)
3577 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003578
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003579 ExprResult Condition = DeclRefExpr::Create(
3580 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3581 /*enclosing*/ false, ConditionVar->getLocation(),
3582 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003583
Eli Friedmanfa0df832012-02-02 03:46:19 +00003584 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003585
Richard Smith03a4aa32016-06-23 19:02:52 +00003586 switch (CK) {
3587 case ConditionKind::Boolean:
3588 return CheckBooleanCondition(StmtLoc, Condition.get());
3589
Richard Smithb130fe72016-06-23 19:16:49 +00003590 case ConditionKind::ConstexprIf:
3591 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3592
Richard Smith03a4aa32016-06-23 19:02:52 +00003593 case ConditionKind::Switch:
3594 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Richard Smith03a4aa32016-06-23 19:02:52 +00003597 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003598}
3599
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003600/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003601ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003602 // C++ 6.4p4:
3603 // The value of a condition that is an initialized declaration in a statement
3604 // other than a switch statement is the value of the declared variable
3605 // implicitly converted to type bool. If that conversion is ill-formed, the
3606 // program is ill-formed.
3607 // The value of a condition that is an expression is the value of the
3608 // expression, implicitly converted to bool.
3609 //
Richard Smithb130fe72016-06-23 19:16:49 +00003610 // FIXME: Return this value to the caller so they don't need to recompute it.
3611 llvm::APSInt Value(/*BitWidth*/1);
3612 return (IsConstexpr && !CondExpr->isValueDependent())
3613 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3614 CCEK_ConstexprIf)
3615 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003616}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003617
3618/// Helper function to determine whether this is the (deprecated) C++
3619/// conversion from a string literal to a pointer to non-const char or
3620/// non-const wchar_t (for narrow and wide string literals,
3621/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003622bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003623Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3624 // Look inside the implicit cast, if it exists.
3625 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3626 From = Cast->getSubExpr();
3627
3628 // A string literal (2.13.4) that is not a wide string literal can
3629 // be converted to an rvalue of type "pointer to char"; a wide
3630 // string literal can be converted to an rvalue of type "pointer
3631 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003632 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003633 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003634 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003635 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003636 // This conversion is considered only when there is an
3637 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003638 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3639 switch (StrLit->getKind()) {
3640 case StringLiteral::UTF8:
3641 case StringLiteral::UTF16:
3642 case StringLiteral::UTF32:
3643 // We don't allow UTF literals to be implicitly converted
3644 break;
3645 case StringLiteral::Ascii:
3646 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3647 ToPointeeType->getKind() == BuiltinType::Char_S);
3648 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003649 return Context.typesAreCompatible(Context.getWideCharType(),
3650 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003651 }
3652 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003653 }
3654
3655 return false;
3656}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003657
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003659 SourceLocation CastLoc,
3660 QualType Ty,
3661 CastKind Kind,
3662 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003663 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003664 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003665 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003666 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003667 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003668 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003669 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003670 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Richard Smith72d74052013-07-20 19:41:36 +00003672 if (S.RequireNonAbstractType(CastLoc, Ty,
3673 diag::err_allocation_of_abstract_type))
3674 return ExprError();
3675
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003676 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003677 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Richard Smith5179eb72016-06-28 19:03:57 +00003679 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3680 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003681 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003682 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003683
Richard Smithf8adcdc2014-07-17 05:12:35 +00003684 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003685 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003686 ConstructorArgs, HadMultipleCandidates,
3687 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3688 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003689 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003690 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003692 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
John McCalle3027922010-08-25 11:45:40 +00003695 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003696 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
Richard Smithd3f2d322015-02-24 21:16:19 +00003698 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003699 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003700 return ExprError();
3701
Douglas Gregora4253922010-04-16 22:17:36 +00003702 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003703 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3704 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003705 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003706 if (Result.isInvalid())
3707 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003708 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003709 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3710 CK_UserDefinedConversion, Result.get(),
3711 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003712
Douglas Gregor668443e2011-01-20 00:18:04 +00003713 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003714 }
3715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716}
Douglas Gregora4253922010-04-16 22:17:36 +00003717
Douglas Gregor5fb53972009-01-14 15:45:31 +00003718/// PerformImplicitConversion - Perform an implicit conversion of the
3719/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003720/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003721/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003722/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003723ExprResult
3724Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003725 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003726 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003727 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003728 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003729 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003730 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3731 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003732 if (Res.isInvalid())
3733 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003734 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003735 break;
John Wiegley01296292011-04-08 18:41:53 +00003736 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003737
Anders Carlsson110b07b2009-09-15 06:28:28 +00003738 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003740 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003741 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003742 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003743 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003744 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003745 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Anders Carlsson110b07b2009-09-15 06:28:28 +00003747 // If the user-defined conversion is specified by a conversion function,
3748 // the initial standard conversion sequence converts the source type to
3749 // the implicit object parameter of the conversion function.
3750 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003751 } else {
3752 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003753 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003754 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003755 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003757 // initial standard conversion sequence converts the source type to
3758 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003759 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 }
Richard Smith72d74052013-07-20 19:41:36 +00003762 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003763 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003764 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003765 PerformImplicitConversion(From, BeforeToType,
3766 ICS.UserDefined.Before, AA_Converting,
3767 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003768 if (Res.isInvalid())
3769 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003770 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
3773 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003774 = BuildCXXCastArgument(*this,
3775 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003776 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003777 CastKind, cast<CXXMethodDecl>(FD),
3778 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003779 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003780 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003781
3782 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003783 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003784
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003785 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003786
Richard Smith507840d2011-11-29 22:48:16 +00003787 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3788 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003789 }
John McCall0d1da222010-01-12 00:44:57 +00003790
3791 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003792 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003793 PDiag(diag::err_typecheck_ambiguous_condition)
3794 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003795 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796
Douglas Gregor39c16d42008-10-24 04:54:22 +00003797 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003798 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003799
3800 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003801 bool Diagnosed =
3802 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3803 From->getType(), From, Action);
3804 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003805 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003806 }
3807
3808 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003809 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003810}
3811
Richard Smith507840d2011-11-29 22:48:16 +00003812/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003813/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003814/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003815/// expression. Flavor is the context in which we're performing this
3816/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003817ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003818Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003819 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003820 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003821 CheckedConversionKind CCK) {
3822 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003823
Mike Stump87c57ac2009-05-16 07:39:55 +00003824 // Overall FIXME: we are recomputing too many types here and doing far too
3825 // much extra work. What this means is that we need to keep track of more
3826 // information that is computed when we try the implicit conversion initially,
3827 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003828 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003829
Douglas Gregor2fe98832008-11-03 19:09:14 +00003830 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003831 // FIXME: When can ToType be a reference type?
3832 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003833 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003834 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003835 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003836 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003837 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003838 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003839 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003840 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3841 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003842 ConstructorArgs, /*HadMultipleCandidates*/ false,
3843 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3844 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003845 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003846 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003847 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3848 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003849 From, /*HadMultipleCandidates*/ false,
3850 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3851 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003852 }
3853
Douglas Gregor980fb162010-04-29 18:24:40 +00003854 // Resolve overloaded function references.
3855 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3856 DeclAccessPair Found;
3857 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3858 true, Found);
3859 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003860 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003861
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003862 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003863 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864
Douglas Gregor980fb162010-04-29 18:24:40 +00003865 From = FixOverloadedFunctionReference(From, Found, Fn);
3866 FromType = From->getType();
3867 }
3868
Richard Smitha23ab512013-05-23 00:30:41 +00003869 // If we're converting to an atomic type, first convert to the corresponding
3870 // non-atomic type.
3871 QualType ToAtomicType;
3872 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3873 ToAtomicType = ToType;
3874 ToType = ToAtomic->getValueType();
3875 }
3876
George Burgess IV8d141e02015-12-14 22:00:49 +00003877 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003878 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003879 switch (SCS.First) {
3880 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003881 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3882 FromType = FromAtomic->getValueType().getUnqualifiedType();
3883 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3884 From, /*BasePath=*/nullptr, VK_RValue);
3885 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003886 break;
3887
Eli Friedman946b7b52012-01-24 22:51:26 +00003888 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003889 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003890 ExprResult FromRes = DefaultLvalueConversion(From);
3891 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003892 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003893 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003894 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003895 }
John McCall34376a62010-12-04 03:47:34 +00003896
Douglas Gregor39c16d42008-10-24 04:54:22 +00003897 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003898 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003899 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003900 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003901 break;
3902
3903 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003904 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003905 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003906 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003907 break;
3908
3909 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003910 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003911 }
3912
Richard Smith507840d2011-11-29 22:48:16 +00003913 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003914 switch (SCS.Second) {
3915 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003916 // C++ [except.spec]p5:
3917 // [For] assignment to and initialization of pointers to functions,
3918 // pointers to member functions, and references to functions: the
3919 // target entity shall allow at least the exceptions allowed by the
3920 // source value in the assignment or initialization.
3921 switch (Action) {
3922 case AA_Assigning:
3923 case AA_Initializing:
3924 // Note, function argument passing and returning are initialization.
3925 case AA_Passing:
3926 case AA_Returning:
3927 case AA_Sending:
3928 case AA_Passing_CFAudited:
3929 if (CheckExceptionSpecCompatibility(From, ToType))
3930 return ExprError();
3931 break;
3932
3933 case AA_Casting:
3934 case AA_Converting:
3935 // Casts and implicit conversions are not initialization, so are not
3936 // checked for exception specification mismatches.
3937 break;
3938 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003939 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003940 break;
3941
3942 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003943 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003944 if (ToType->isBooleanType()) {
3945 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3946 SCS.Second == ICK_Integral_Promotion &&
3947 "only enums with fixed underlying type can promote to bool");
3948 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003949 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003950 } else {
3951 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003952 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003953 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003954 break;
3955
3956 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003957 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003958 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003959 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003960 break;
3961
3962 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003963 case ICK_Complex_Conversion: {
3964 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3965 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3966 CastKind CK;
3967 if (FromEl->isRealFloatingType()) {
3968 if (ToEl->isRealFloatingType())
3969 CK = CK_FloatingComplexCast;
3970 else
3971 CK = CK_FloatingComplexToIntegralComplex;
3972 } else if (ToEl->isRealFloatingType()) {
3973 CK = CK_IntegralComplexToFloatingComplex;
3974 } else {
3975 CK = CK_IntegralComplexCast;
3976 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003977 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003978 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003979 break;
John McCall8cb679e2010-11-15 09:13:47 +00003980 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003981
Douglas Gregor39c16d42008-10-24 04:54:22 +00003982 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003983 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003984 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003985 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003986 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003987 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003988 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003989 break;
3990
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003991 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003992 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003993 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003994 break;
3995
John McCall31168b02011-06-15 23:02:42 +00003996 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003997 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003998 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003999 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004000 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004001 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004002 diag::ext_typecheck_convert_incompatible_pointer)
4003 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00004004 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004005 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004006 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004007 diag::ext_typecheck_convert_incompatible_pointer)
4008 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00004009 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00004010
Douglas Gregor33823722011-06-11 01:09:30 +00004011 if (From->getType()->isObjCObjectPointerType() &&
4012 ToType->isObjCObjectPointerType())
4013 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004014 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4015 !CheckObjCARCUnavailableWeakConversion(ToType,
4016 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004017 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00004018 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00004019 diag::err_arc_weak_unavailable_assign);
4020 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004021 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00004022 diag::err_arc_convesion_of_weak_unavailable)
4023 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00004024 << From->getSourceRange();
4025 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004026
Richard Smith354abec2017-12-08 23:29:59 +00004027 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004028 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004029 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004030 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004031
4032 // Make sure we extend blocks if necessary.
4033 // FIXME: doing this here is really ugly.
4034 if (Kind == CK_BlockPointerToObjCPointerCast) {
4035 ExprResult E = From;
4036 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004037 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004038 }
Brian Kelley11352a82017-03-29 18:09:02 +00004039 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4040 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004041 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004042 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004043 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004046 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004047 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004048 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004049 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004050 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004051 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004052 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004053
4054 // We may not have been able to figure out what this member pointer resolved
4055 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004056 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004057 (void)isCompleteType(From->getExprLoc(), From->getType());
4058 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004059 }
David Majnemerd96b9972014-08-08 00:10:39 +00004060
Richard Smith507840d2011-11-29 22:48:16 +00004061 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004062 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004063 break;
4064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004066 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004067 // Perform half-to-boolean conversion via float.
4068 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004069 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004070 FromType = Context.FloatTy;
4071 }
4072
Richard Smith507840d2011-11-29 22:48:16 +00004073 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004074 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004075 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004076 break;
4077
Douglas Gregor88d292c2010-05-13 16:44:06 +00004078 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004079 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004081 ToType.getNonReferenceType(),
4082 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004084 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00004085 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004086 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004087
Richard Smith507840d2011-11-29 22:48:16 +00004088 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4089 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004090 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004091 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004092 }
4093
Douglas Gregor46188682010-05-18 22:42:18 +00004094 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004095 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004096 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004097 break;
4098
George Burgess IVdf1ed002016-01-13 01:52:39 +00004099 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004100 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004101 Expr *Elem = prepareVectorSplat(ToType, From).get();
4102 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4103 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004104 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106
Douglas Gregor46188682010-05-18 22:42:18 +00004107 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004108 // Case 1. x -> _Complex y
4109 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4110 QualType ElType = ToComplex->getElementType();
4111 bool isFloatingComplex = ElType->isRealFloatingType();
4112
4113 // x -> y
4114 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4115 // do nothing
4116 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004117 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004118 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004119 } else {
4120 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004121 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004122 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004123 }
4124 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004125 From = ImpCastExprToType(From, ToType,
4126 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004127 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004128
4129 // Case 2. _Complex x -> y
4130 } else {
4131 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4132 assert(FromComplex);
4133
4134 QualType ElType = FromComplex->getElementType();
4135 bool isFloatingComplex = ElType->isRealFloatingType();
4136
4137 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004138 From = ImpCastExprToType(From, ElType,
4139 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004140 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004141 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004142
4143 // x -> y
4144 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4145 // do nothing
4146 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004147 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004148 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004149 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004150 } else {
4151 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004152 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004153 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004154 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004155 }
4156 }
Douglas Gregor46188682010-05-18 22:42:18 +00004157 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004158
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004159 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004160 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004161 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004162 break;
4163 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004164
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004165 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004166 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004167 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004168 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4169 if (FromRes.isInvalid())
4170 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004171 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004172 assert ((ConvTy == Sema::Compatible) &&
4173 "Improper transparent union conversion");
4174 (void)ConvTy;
4175 break;
4176 }
4177
Guy Benyei259f9f42013-02-07 16:05:33 +00004178 case ICK_Zero_Event_Conversion:
4179 From = ImpCastExprToType(From, ToType,
4180 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004181 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004182 break;
4183
Egor Churaev89831422016-12-23 14:55:49 +00004184 case ICK_Zero_Queue_Conversion:
4185 From = ImpCastExprToType(From, ToType,
4186 CK_ZeroToOCLQueue,
4187 From->getValueKind()).get();
4188 break;
4189
Douglas Gregor46188682010-05-18 22:42:18 +00004190 case ICK_Lvalue_To_Rvalue:
4191 case ICK_Array_To_Pointer:
4192 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004193 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004194 case ICK_Qualification:
4195 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004196 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004197 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004198 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004199 }
4200
4201 switch (SCS.Third) {
4202 case ICK_Identity:
4203 // Nothing to do.
4204 break;
4205
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004206 case ICK_Function_Conversion:
4207 // If both sides are functions (or pointers/references to them), there could
4208 // be incompatible exception declarations.
4209 if (CheckExceptionSpecCompatibility(From, ToType))
4210 return ExprError();
4211
4212 From = ImpCastExprToType(From, ToType, CK_NoOp,
4213 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4214 break;
4215
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004216 case ICK_Qualification: {
4217 // The qualification keeps the category of the inner expression, unless the
4218 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004219 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004220 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004221 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004222 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004223
Douglas Gregore981bb02011-03-14 16:13:32 +00004224 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004225 !getLangOpts().WritableStrings) {
4226 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4227 ? diag::ext_deprecated_string_literal_conversion
4228 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004229 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004230 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004231
Douglas Gregor39c16d42008-10-24 04:54:22 +00004232 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004233 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004234
Douglas Gregor39c16d42008-10-24 04:54:22 +00004235 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004236 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004237 }
4238
Douglas Gregor298f43d2012-04-12 20:42:30 +00004239 // If this conversion sequence involved a scalar -> atomic conversion, perform
4240 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004241 if (!ToAtomicType.isNull()) {
4242 assert(Context.hasSameType(
4243 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4244 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004245 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004246 }
4247
George Burgess IV8d141e02015-12-14 22:00:49 +00004248 // If this conversion sequence succeeded and involved implicitly converting a
4249 // _Nullable type to a _Nonnull one, complain.
4250 if (CCK == CCK_ImplicitConversion)
4251 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4252 From->getLocStart());
4253
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004254 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004255}
4256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004257/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004258///
4259/// If the particular type trait requires a complete type, tries to complete
4260/// it. If completing the type fails, a diagnostic is emitted and false
4261/// returned. If completing the type succeeds or no completion was required,
4262/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004263static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004264 SourceLocation Loc,
4265 QualType ArgTy) {
4266 // C++0x [meta.unary.prop]p3:
4267 // For all of the class templates X declared in this Clause, instantiating
4268 // that template with a template argument that is a class template
4269 // specialization may result in the implicit instantiation of the template
4270 // argument if and only if the semantics of X require that the argument
4271 // must be a complete type.
4272 // We apply this rule to all the type trait expressions used to implement
4273 // these class templates. We also try to follow any GCC documented behavior
4274 // in these expressions to ensure portability of standard libraries.
4275 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004276 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004277 // is_complete_type somewhat obviously cannot require a complete type.
4278 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004279 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004280
4281 // These traits are modeled on the type predicates in C++0x
4282 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4283 // requiring a complete type, as whether or not they return true cannot be
4284 // impacted by the completeness of the type.
4285 case UTT_IsVoid:
4286 case UTT_IsIntegral:
4287 case UTT_IsFloatingPoint:
4288 case UTT_IsArray:
4289 case UTT_IsPointer:
4290 case UTT_IsLvalueReference:
4291 case UTT_IsRvalueReference:
4292 case UTT_IsMemberFunctionPointer:
4293 case UTT_IsMemberObjectPointer:
4294 case UTT_IsEnum:
4295 case UTT_IsUnion:
4296 case UTT_IsClass:
4297 case UTT_IsFunction:
4298 case UTT_IsReference:
4299 case UTT_IsArithmetic:
4300 case UTT_IsFundamental:
4301 case UTT_IsObject:
4302 case UTT_IsScalar:
4303 case UTT_IsCompound:
4304 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004305 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004306
4307 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4308 // which requires some of its traits to have the complete type. However,
4309 // the completeness of the type cannot impact these traits' semantics, and
4310 // so they don't require it. This matches the comments on these traits in
4311 // Table 49.
4312 case UTT_IsConst:
4313 case UTT_IsVolatile:
4314 case UTT_IsSigned:
4315 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004316
4317 // This type trait always returns false, checking the type is moot.
4318 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004319 return true;
4320
David Majnemer213bea32015-11-16 06:58:51 +00004321 // C++14 [meta.unary.prop]:
4322 // If T is a non-union class type, T shall be a complete type.
4323 case UTT_IsEmpty:
4324 case UTT_IsPolymorphic:
4325 case UTT_IsAbstract:
4326 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4327 if (!RD->isUnion())
4328 return !S.RequireCompleteType(
4329 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4330 return true;
4331
4332 // C++14 [meta.unary.prop]:
4333 // If T is a class type, T shall be a complete type.
4334 case UTT_IsFinal:
4335 case UTT_IsSealed:
4336 if (ArgTy->getAsCXXRecordDecl())
4337 return !S.RequireCompleteType(
4338 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4339 return true;
4340
Richard Smithf03e9082017-06-01 00:28:16 +00004341 // C++1z [meta.unary.prop]:
4342 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004343 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004344 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004345 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004346 case UTT_IsStandardLayout:
4347 case UTT_IsPOD:
4348 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004349 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4350 // or an array of unknown bound. But GCC actually imposes the same constraints
4351 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004352 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004353 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004354 case UTT_HasNothrowConstructor:
4355 case UTT_HasNothrowCopy:
4356 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004357 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004358 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004359 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004360 case UTT_HasTrivialCopy:
4361 case UTT_HasTrivialDestructor:
4362 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004363 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4364 LLVM_FALLTHROUGH;
4365
4366 // C++1z [meta.unary.prop]:
4367 // T shall be a complete type, cv void, or an array of unknown bound.
4368 case UTT_IsDestructible:
4369 case UTT_IsNothrowDestructible:
4370 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004371 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004372 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004373 return true;
4374
4375 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004376 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004377 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004378}
4379
Joao Matosc9523d42013-03-27 01:34:16 +00004380static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4381 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004382 bool (CXXRecordDecl::*HasTrivial)() const,
4383 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004384 bool (CXXMethodDecl::*IsDesiredOp)() const)
4385{
4386 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4387 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4388 return true;
4389
4390 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4391 DeclarationNameInfo NameInfo(Name, KeyLoc);
4392 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4393 if (Self.LookupQualifiedName(Res, RD)) {
4394 bool FoundOperator = false;
4395 Res.suppressDiagnostics();
4396 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4397 Op != OpEnd; ++Op) {
4398 if (isa<FunctionTemplateDecl>(*Op))
4399 continue;
4400
4401 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4402 if((Operator->*IsDesiredOp)()) {
4403 FoundOperator = true;
4404 const FunctionProtoType *CPT =
4405 Operator->getType()->getAs<FunctionProtoType>();
4406 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004407 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004408 return false;
4409 }
4410 }
4411 return FoundOperator;
4412 }
4413 return false;
4414}
4415
Alp Toker95e7ff22014-01-01 05:57:51 +00004416static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004417 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004418 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004419
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004420 ASTContext &C = Self.Context;
4421 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004422 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004423 // Type trait expressions corresponding to the primary type category
4424 // predicates in C++0x [meta.unary.cat].
4425 case UTT_IsVoid:
4426 return T->isVoidType();
4427 case UTT_IsIntegral:
4428 return T->isIntegralType(C);
4429 case UTT_IsFloatingPoint:
4430 return T->isFloatingType();
4431 case UTT_IsArray:
4432 return T->isArrayType();
4433 case UTT_IsPointer:
4434 return T->isPointerType();
4435 case UTT_IsLvalueReference:
4436 return T->isLValueReferenceType();
4437 case UTT_IsRvalueReference:
4438 return T->isRValueReferenceType();
4439 case UTT_IsMemberFunctionPointer:
4440 return T->isMemberFunctionPointerType();
4441 case UTT_IsMemberObjectPointer:
4442 return T->isMemberDataPointerType();
4443 case UTT_IsEnum:
4444 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004445 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004446 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004447 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004448 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004449 case UTT_IsFunction:
4450 return T->isFunctionType();
4451
4452 // Type trait expressions which correspond to the convenient composition
4453 // predicates in C++0x [meta.unary.comp].
4454 case UTT_IsReference:
4455 return T->isReferenceType();
4456 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004457 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004458 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004459 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004460 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004461 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004462 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004463 // Note: semantic analysis depends on Objective-C lifetime types to be
4464 // considered scalar types. However, such types do not actually behave
4465 // like scalar types at run time (since they may require retain/release
4466 // operations), so we report them as non-scalar.
4467 if (T->isObjCLifetimeType()) {
4468 switch (T.getObjCLifetime()) {
4469 case Qualifiers::OCL_None:
4470 case Qualifiers::OCL_ExplicitNone:
4471 return true;
4472
4473 case Qualifiers::OCL_Strong:
4474 case Qualifiers::OCL_Weak:
4475 case Qualifiers::OCL_Autoreleasing:
4476 return false;
4477 }
4478 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004479
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004480 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004481 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004482 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004483 case UTT_IsMemberPointer:
4484 return T->isMemberPointerType();
4485
4486 // Type trait expressions which correspond to the type property predicates
4487 // in C++0x [meta.unary.prop].
4488 case UTT_IsConst:
4489 return T.isConstQualified();
4490 case UTT_IsVolatile:
4491 return T.isVolatileQualified();
4492 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004493 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004494 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004495 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004496 case UTT_IsStandardLayout:
4497 return T->isStandardLayoutType();
4498 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004499 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004500 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004501 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004502 case UTT_IsEmpty:
4503 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4504 return !RD->isUnion() && RD->isEmpty();
4505 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004506 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004507 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004508 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004509 return false;
4510 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004511 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004512 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004513 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004514 case UTT_IsAggregate:
4515 // Report vector extensions and complex types as aggregates because they
4516 // support aggregate initialization. GCC mirrors this behavior for vectors
4517 // but not _Complex.
4518 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4519 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004520 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4521 // even then only when it is used with the 'interface struct ...' syntax
4522 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004523 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004524 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004525 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004526 case UTT_IsSealed:
4527 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004528 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004529 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004530 case UTT_IsSigned:
4531 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004532 case UTT_IsUnsigned:
4533 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004534
4535 // Type trait expressions which query classes regarding their construction,
4536 // destruction, and copying. Rather than being based directly on the
4537 // related type predicates in the standard, they are specified by both
4538 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4539 // specifications.
4540 //
4541 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4542 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004543 //
4544 // Note that these builtins do not behave as documented in g++: if a class
4545 // has both a trivial and a non-trivial special member of a particular kind,
4546 // they return false! For now, we emulate this behavior.
4547 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4548 // does not correctly compute triviality in the presence of multiple special
4549 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004550 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004551 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4552 // If __is_pod (type) is true then the trait is true, else if type is
4553 // a cv class or union type (or array thereof) with a trivial default
4554 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004555 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004556 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004557 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4558 return RD->hasTrivialDefaultConstructor() &&
4559 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004560 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004561 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004562 // This trait is implemented by MSVC 2012 and needed to parse the
4563 // standard library headers. Specifically this is used as the logic
4564 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004565 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004566 return true;
4567 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4568 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4569 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004570 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004571 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4572 // If __is_pod (type) is true or type is a reference type then
4573 // the trait is true, else if type is a cv class or union type
4574 // with a trivial copy constructor ([class.copy]) then the trait
4575 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004576 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004577 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004578 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4579 return RD->hasTrivialCopyConstructor() &&
4580 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004581 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004582 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004583 // This trait is implemented by MSVC 2012 and needed to parse the
4584 // standard library headers. Specifically it is used as the logic
4585 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004586 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004587 return true;
4588 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4589 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4590 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004591 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004592 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4593 // If type is const qualified or is a reference type then the
4594 // trait is false. Otherwise if __is_pod (type) is true then the
4595 // trait is true, else if type is a cv class or union type with
4596 // a trivial copy assignment ([class.copy]) then the trait is
4597 // true, else it is false.
4598 // Note: the const and reference restrictions are interesting,
4599 // given that const and reference members don't prevent a class
4600 // from having a trivial copy assignment operator (but do cause
4601 // errors if the copy assignment operator is actually used, q.v.
4602 // [class.copy]p12).
4603
Richard Smith92f241f2012-12-08 02:53:02 +00004604 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004605 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004606 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004607 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004608 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4609 return RD->hasTrivialCopyAssignment() &&
4610 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004611 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004612 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004613 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004614 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004615 // C++14 [meta.unary.prop]:
4616 // For reference types, is_destructible<T>::value is true.
4617 if (T->isReferenceType())
4618 return true;
4619
4620 // Objective-C++ ARC: autorelease types don't require destruction.
4621 if (T->isObjCLifetimeType() &&
4622 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4623 return true;
4624
4625 // C++14 [meta.unary.prop]:
4626 // For incomplete types and function types, is_destructible<T>::value is
4627 // false.
4628 if (T->isIncompleteType() || T->isFunctionType())
4629 return false;
4630
Richard Smithf03e9082017-06-01 00:28:16 +00004631 // A type that requires destruction (via a non-trivial destructor or ARC
4632 // lifetime semantics) is not trivially-destructible.
4633 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4634 return false;
4635
David Majnemerac73de92015-08-11 03:03:28 +00004636 // C++14 [meta.unary.prop]:
4637 // For object types and given U equal to remove_all_extents_t<T>, if the
4638 // expression std::declval<U&>().~U() is well-formed when treated as an
4639 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4640 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4641 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4642 if (!Destructor)
4643 return false;
4644 // C++14 [dcl.fct.def.delete]p2:
4645 // A program that refers to a deleted function implicitly or
4646 // explicitly, other than to declare it, is ill-formed.
4647 if (Destructor->isDeleted())
4648 return false;
4649 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4650 return false;
4651 if (UTT == UTT_IsNothrowDestructible) {
4652 const FunctionProtoType *CPT =
4653 Destructor->getType()->getAs<FunctionProtoType>();
4654 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004655 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004656 return false;
4657 }
4658 }
4659 return true;
4660
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004661 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004662 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004663 // If __is_pod (type) is true or type is a reference type
4664 // then the trait is true, else if type is a cv class or union
4665 // type (or array thereof) with a trivial destructor
4666 // ([class.dtor]) then the trait is true, else it is
4667 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004668 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004669 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004670
John McCall31168b02011-06-15 23:02:42 +00004671 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004672 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004673 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4674 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004675
Richard Smith92f241f2012-12-08 02:53:02 +00004676 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4677 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004678 return false;
4679 // TODO: Propagate nothrowness for implicitly declared special members.
4680 case UTT_HasNothrowAssign:
4681 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4682 // If type is const qualified or is a reference type then the
4683 // trait is false. Otherwise if __has_trivial_assign (type)
4684 // is true then the trait is true, else if type is a cv class
4685 // or union type with copy assignment operators that are known
4686 // not to throw an exception then the trait is true, else it is
4687 // false.
4688 if (C.getBaseElementType(T).isConstQualified())
4689 return false;
4690 if (T->isReferenceType())
4691 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004692 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004693 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004694
Joao Matosc9523d42013-03-27 01:34:16 +00004695 if (const RecordType *RT = T->getAs<RecordType>())
4696 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4697 &CXXRecordDecl::hasTrivialCopyAssignment,
4698 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4699 &CXXMethodDecl::isCopyAssignmentOperator);
4700 return false;
4701 case UTT_HasNothrowMoveAssign:
4702 // This trait is implemented by MSVC 2012 and needed to parse the
4703 // standard library headers. Specifically this is used as the logic
4704 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004705 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004706 return true;
4707
4708 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4709 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4710 &CXXRecordDecl::hasTrivialMoveAssignment,
4711 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4712 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004713 return false;
4714 case UTT_HasNothrowCopy:
4715 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4716 // If __has_trivial_copy (type) is true then the trait is true, else
4717 // if type is a cv class or union type with copy constructors that are
4718 // known not to throw an exception then the trait is true, else it is
4719 // false.
John McCall31168b02011-06-15 23:02:42 +00004720 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004721 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004722 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4723 if (RD->hasTrivialCopyConstructor() &&
4724 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004725 return true;
4726
4727 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004728 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004729 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004730 // A template constructor is never a copy constructor.
4731 // FIXME: However, it may actually be selected at the actual overload
4732 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004733 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004734 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004735 // UsingDecl itself is not a constructor
4736 if (isa<UsingDecl>(ND))
4737 continue;
4738 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004739 if (Constructor->isCopyConstructor(FoundTQs)) {
4740 FoundConstructor = true;
4741 const FunctionProtoType *CPT
4742 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004743 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4744 if (!CPT)
4745 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004746 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004747 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004748 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004749 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004750 }
4751 }
4752
Richard Smith938f40b2011-06-11 17:19:42 +00004753 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004754 }
4755 return false;
4756 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004757 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004758 // If __has_trivial_constructor (type) is true then the trait is
4759 // true, else if type is a cv class or union type (or array
4760 // thereof) with a default constructor that is known not to
4761 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004762 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004763 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004764 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4765 if (RD->hasTrivialDefaultConstructor() &&
4766 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004767 return true;
4768
Alp Tokerb4bca412014-01-20 00:23:47 +00004769 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004770 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004771 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004772 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004773 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004774 // UsingDecl itself is not a constructor
4775 if (isa<UsingDecl>(ND))
4776 continue;
4777 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004778 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004779 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004780 const FunctionProtoType *CPT
4781 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004782 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4783 if (!CPT)
4784 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004785 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004786 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004787 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004788 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004789 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004790 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004791 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004792 }
4793 return false;
4794 case UTT_HasVirtualDestructor:
4795 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4796 // If type is a class type with a virtual destructor ([class.dtor])
4797 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004798 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004799 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004800 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004801 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004802
4803 // These type trait expressions are modeled on the specifications for the
4804 // Embarcadero C++0x type trait functions:
4805 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4806 case UTT_IsCompleteType:
4807 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4808 // Returns True if and only if T is a complete type at the point of the
4809 // function call.
4810 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004811 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004812 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004813 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004814}
Sebastian Redl5822f082009-02-07 20:10:22 +00004815
Alp Tokercbb90342013-12-13 20:49:58 +00004816static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4817 QualType RhsT, SourceLocation KeyLoc);
4818
Douglas Gregor29c42f22012-02-24 07:38:34 +00004819static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4820 ArrayRef<TypeSourceInfo *> Args,
4821 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004822 if (Kind <= UTT_Last)
4823 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4824
Eric Fiselier1af6c112018-01-12 00:09:37 +00004825 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4826 // traits to avoid duplication.
4827 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004828 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4829 Args[1]->getType(), RParenLoc);
4830
Douglas Gregor29c42f22012-02-24 07:38:34 +00004831 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004832 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004833 case clang::TT_IsConstructible:
4834 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004835 case clang::TT_IsTriviallyConstructible: {
4836 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004837 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004838 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004839 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004840 // definition for is_constructible, as defined below, is known to call
4841 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004842 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004843 // The predicate condition for a template specialization
4844 // is_constructible<T, Args...> shall be satisfied if and only if the
4845 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004846 // variable t:
4847 //
4848 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004849 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004850
4851 // Precondition: T and all types in the parameter pack Args shall be
4852 // complete types, (possibly cv-qualified) void, or arrays of
4853 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004854 for (const auto *TSI : Args) {
4855 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004856 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004857 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004858
Simon Pilgrim75c26882016-09-30 14:25:09 +00004859 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004860 diag::err_incomplete_type_used_in_type_trait_expr))
4861 return false;
4862 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004863
David Majnemer9658ecc2015-11-13 05:32:43 +00004864 // Make sure the first argument is not incomplete nor a function type.
4865 QualType T = Args[0]->getType();
4866 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004867 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004868
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004869 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004870 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004871 if (RD && RD->isAbstract())
4872 return false;
4873
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004874 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4875 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004876 ArgExprs.reserve(Args.size() - 1);
4877 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004878 QualType ArgTy = Args[I]->getType();
4879 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4880 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004881 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004882 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4883 ArgTy.getNonLValueExprType(S.Context),
4884 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004885 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004886 for (Expr &E : OpaqueArgExprs)
4887 ArgExprs.push_back(&E);
4888
Simon Pilgrim75c26882016-09-30 14:25:09 +00004889 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004890 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004891 EnterExpressionEvaluationContext Unevaluated(
4892 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004893 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4894 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4895 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4896 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4897 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004898 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004899 if (Init.Failed())
4900 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004901
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004902 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004903 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4904 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004905
Alp Toker73287bf2014-01-20 00:24:09 +00004906 if (Kind == clang::TT_IsConstructible)
4907 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004908
Eric Fiselier1af6c112018-01-12 00:09:37 +00004909 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4910 if (!T->isReferenceType())
4911 return false;
4912
4913 return !Init.isDirectReferenceBinding();
4914 }
4915
Alp Toker73287bf2014-01-20 00:24:09 +00004916 if (Kind == clang::TT_IsNothrowConstructible)
4917 return S.canThrow(Result.get()) == CT_Cannot;
4918
4919 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004920 // Under Objective-C ARC and Weak, if the destination has non-trivial
4921 // Objective-C lifetime, this is a non-trivial construction.
4922 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004923 return false;
4924
4925 // The initialization succeeded; now make sure there are no non-trivial
4926 // calls.
4927 return !Result.get()->hasNonTrivialCall(S.Context);
4928 }
4929
4930 llvm_unreachable("unhandled type trait");
4931 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004932 }
Alp Tokercbb90342013-12-13 20:49:58 +00004933 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004934 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004935
Douglas Gregor29c42f22012-02-24 07:38:34 +00004936 return false;
4937}
4938
Simon Pilgrim75c26882016-09-30 14:25:09 +00004939ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4940 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004941 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004942 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004943
Alp Toker95e7ff22014-01-01 05:57:51 +00004944 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4945 *this, Kind, KWLoc, Args[0]->getType()))
4946 return ExprError();
4947
Douglas Gregor29c42f22012-02-24 07:38:34 +00004948 bool Dependent = false;
4949 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4950 if (Args[I]->getType()->isDependentType()) {
4951 Dependent = true;
4952 break;
4953 }
4954 }
Alp Tokercbb90342013-12-13 20:49:58 +00004955
4956 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004957 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004958 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4959
4960 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4961 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004962}
4963
Alp Toker88f64e62013-12-13 21:19:30 +00004964ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4965 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004966 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004967 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004968 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004969
Douglas Gregor29c42f22012-02-24 07:38:34 +00004970 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4971 TypeSourceInfo *TInfo;
4972 QualType T = GetTypeFromParser(Args[I], &TInfo);
4973 if (!TInfo)
4974 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004975
4976 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004977 }
Alp Tokercbb90342013-12-13 20:49:58 +00004978
Douglas Gregor29c42f22012-02-24 07:38:34 +00004979 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4980}
4981
Alp Tokercbb90342013-12-13 20:49:58 +00004982static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4983 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004984 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4985 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004986
4987 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004988 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004989 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004990 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004991 // Base and Derived are not unions and name the same class type without
4992 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004993
John McCall388ef532011-01-28 22:02:36 +00004994 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004995 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004996 if (!rhsRecord || !lhsRecord) {
4997 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4998 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4999 if (!LHSObjTy || !RHSObjTy)
5000 return false;
5001
5002 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5003 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5004 if (!BaseInterface || !DerivedInterface)
5005 return false;
5006
5007 if (Self.RequireCompleteType(
5008 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5009 return false;
5010
5011 return BaseInterface->isSuperClassOf(DerivedInterface);
5012 }
John McCall388ef532011-01-28 22:02:36 +00005013
5014 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5015 == (lhsRecord == rhsRecord));
5016
5017 if (lhsRecord == rhsRecord)
5018 return !lhsRecord->getDecl()->isUnion();
5019
5020 // C++0x [meta.rel]p2:
5021 // If Base and Derived are class types and are different types
5022 // (ignoring possible cv-qualifiers) then Derived shall be a
5023 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005024 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005025 diag::err_incomplete_type_used_in_type_trait_expr))
5026 return false;
5027
5028 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5029 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5030 }
John Wiegley65497cc2011-04-27 23:09:49 +00005031 case BTT_IsSame:
5032 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005033 case BTT_TypeCompatible: {
5034 // GCC ignores cv-qualifiers on arrays for this builtin.
5035 Qualifiers LhsQuals, RhsQuals;
5036 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5037 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5038 return Self.Context.typesAreCompatible(Lhs, Rhs);
5039 }
John Wiegley65497cc2011-04-27 23:09:49 +00005040 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005041 case BTT_IsConvertibleTo: {
5042 // C++0x [meta.rel]p4:
5043 // Given the following function prototype:
5044 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005045 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005046 // typename add_rvalue_reference<T>::type create();
5047 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005048 // the predicate condition for a template specialization
5049 // is_convertible<From, To> shall be satisfied if and only if
5050 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005051 // well-formed, including any implicit conversions to the return
5052 // type of the function:
5053 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005054 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005055 // return create<From>();
5056 // }
5057 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005058 // Access checking is performed as if in a context unrelated to To and
5059 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005060 // of the return-statement (including conversions to the return type)
5061 // is considered.
5062 //
5063 // We model the initialization as a copy-initialization of a temporary
5064 // of the appropriate type, which for this expression is identical to the
5065 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005066
5067 // Functions aren't allowed to return function or array types.
5068 if (RhsT->isFunctionType() || RhsT->isArrayType())
5069 return false;
5070
5071 // A return statement in a void function must have void type.
5072 if (RhsT->isVoidType())
5073 return LhsT->isVoidType();
5074
5075 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005076 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005077 return false;
5078
5079 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005080 if (LhsT->isObjectType() || LhsT->isFunctionType())
5081 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005082
5083 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005084 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005085 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005086 Expr::getValueKindForType(LhsT));
5087 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005088 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005089 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005090
5091 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005092 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005093 EnterExpressionEvaluationContext Unevaluated(
5094 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005095 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5096 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005097 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005098 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005099 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005100
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005101 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005102 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5103 }
Alp Toker73287bf2014-01-20 00:24:09 +00005104
David Majnemerb3d96882016-05-23 17:21:55 +00005105 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005106 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005107 case BTT_IsTriviallyAssignable: {
5108 // C++11 [meta.unary.prop]p3:
5109 // is_trivially_assignable is defined as:
5110 // is_assignable<T, U>::value is true and the assignment, as defined by
5111 // is_assignable, is known to call no operation that is not trivial
5112 //
5113 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005114 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005115 // treated as an unevaluated operand (Clause 5).
5116 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005117 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005118 // void, or arrays of unknown bound.
5119 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005120 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005121 diag::err_incomplete_type_used_in_type_trait_expr))
5122 return false;
5123 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005124 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005125 diag::err_incomplete_type_used_in_type_trait_expr))
5126 return false;
5127
5128 // cv void is never assignable.
5129 if (LhsT->isVoidType() || RhsT->isVoidType())
5130 return false;
5131
Simon Pilgrim75c26882016-09-30 14:25:09 +00005132 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005133 // declval<U>().
5134 if (LhsT->isObjectType() || LhsT->isFunctionType())
5135 LhsT = Self.Context.getRValueReferenceType(LhsT);
5136 if (RhsT->isObjectType() || RhsT->isFunctionType())
5137 RhsT = Self.Context.getRValueReferenceType(RhsT);
5138 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5139 Expr::getValueKindForType(LhsT));
5140 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5141 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005142
5143 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005144 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005145 EnterExpressionEvaluationContext Unevaluated(
5146 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005147 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005148 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005149 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5150 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005151 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5152 return false;
5153
David Majnemerb3d96882016-05-23 17:21:55 +00005154 if (BTT == BTT_IsAssignable)
5155 return true;
5156
Alp Toker73287bf2014-01-20 00:24:09 +00005157 if (BTT == BTT_IsNothrowAssignable)
5158 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005159
Alp Toker73287bf2014-01-20 00:24:09 +00005160 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005161 // Under Objective-C ARC and Weak, if the destination has non-trivial
5162 // Objective-C lifetime, this is a non-trivial assignment.
5163 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005164 return false;
5165
5166 return !Result.get()->hasNonTrivialCall(Self.Context);
5167 }
5168
5169 llvm_unreachable("unhandled type trait");
5170 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005171 }
Alp Tokercbb90342013-12-13 20:49:58 +00005172 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005173 }
5174 llvm_unreachable("Unknown type trait or not implemented");
5175}
5176
John Wiegley6242b6a2011-04-28 00:16:57 +00005177ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5178 SourceLocation KWLoc,
5179 ParsedType Ty,
5180 Expr* DimExpr,
5181 SourceLocation RParen) {
5182 TypeSourceInfo *TSInfo;
5183 QualType T = GetTypeFromParser(Ty, &TSInfo);
5184 if (!TSInfo)
5185 TSInfo = Context.getTrivialTypeSourceInfo(T);
5186
5187 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5188}
5189
5190static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5191 QualType T, Expr *DimExpr,
5192 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005193 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005194
5195 switch(ATT) {
5196 case ATT_ArrayRank:
5197 if (T->isArrayType()) {
5198 unsigned Dim = 0;
5199 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5200 ++Dim;
5201 T = AT->getElementType();
5202 }
5203 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005204 }
John Wiegleyd3522222011-04-28 02:06:46 +00005205 return 0;
5206
John Wiegley6242b6a2011-04-28 00:16:57 +00005207 case ATT_ArrayExtent: {
5208 llvm::APSInt Value;
5209 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005210 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005211 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005212 false).isInvalid())
5213 return 0;
5214 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005215 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5216 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005217 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005218 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005219 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005220
5221 if (T->isArrayType()) {
5222 unsigned D = 0;
5223 bool Matched = false;
5224 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5225 if (Dim == D) {
5226 Matched = true;
5227 break;
5228 }
5229 ++D;
5230 T = AT->getElementType();
5231 }
5232
John Wiegleyd3522222011-04-28 02:06:46 +00005233 if (Matched && T->isArrayType()) {
5234 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5235 return CAT->getSize().getLimitedValue();
5236 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005237 }
John Wiegleyd3522222011-04-28 02:06:46 +00005238 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005239 }
5240 }
5241 llvm_unreachable("Unknown type trait or not implemented");
5242}
5243
5244ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5245 SourceLocation KWLoc,
5246 TypeSourceInfo *TSInfo,
5247 Expr* DimExpr,
5248 SourceLocation RParen) {
5249 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005250
Chandler Carruthc5276e52011-05-01 08:48:21 +00005251 // FIXME: This should likely be tracked as an APInt to remove any host
5252 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005253 uint64_t Value = 0;
5254 if (!T->isDependentType())
5255 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5256
Chandler Carruthc5276e52011-05-01 08:48:21 +00005257 // While the specification for these traits from the Embarcadero C++
5258 // compiler's documentation says the return type is 'unsigned int', Clang
5259 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5260 // compiler, there is no difference. On several other platforms this is an
5261 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005262 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5263 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005264}
5265
John Wiegleyf9f65842011-04-25 06:54:41 +00005266ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005267 SourceLocation KWLoc,
5268 Expr *Queried,
5269 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005270 // If error parsing the expression, ignore.
5271 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005272 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005273
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005274 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005275
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005276 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005277}
5278
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005279static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5280 switch (ET) {
5281 case ET_IsLValueExpr: return E->isLValue();
5282 case ET_IsRValueExpr: return E->isRValue();
5283 }
5284 llvm_unreachable("Expression trait not covered by switch");
5285}
5286
John Wiegleyf9f65842011-04-25 06:54:41 +00005287ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005288 SourceLocation KWLoc,
5289 Expr *Queried,
5290 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005291 if (Queried->isTypeDependent()) {
5292 // Delay type-checking for type-dependent expressions.
5293 } else if (Queried->getType()->isPlaceholderType()) {
5294 ExprResult PE = CheckPlaceholderExpr(Queried);
5295 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005296 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005297 }
5298
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005299 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005300
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005301 return new (Context)
5302 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005303}
5304
Richard Trieu82402a02011-09-15 21:56:47 +00005305QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005306 ExprValueKind &VK,
5307 SourceLocation Loc,
5308 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005309 assert(!LHS.get()->getType()->isPlaceholderType() &&
5310 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005311 "placeholders should have been weeded out by now");
5312
Richard Smith4baaa5a2016-12-03 01:14:32 +00005313 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5314 // temporary materialization conversion otherwise.
5315 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005316 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005317 else if (LHS.get()->isRValue())
5318 LHS = TemporaryMaterializationConversion(LHS.get());
5319 if (LHS.isInvalid())
5320 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005321
5322 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005323 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005324 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005325
Sebastian Redl5822f082009-02-07 20:10:22 +00005326 const char *OpSpelling = isIndirect ? "->*" : ".*";
5327 // C++ 5.5p2
5328 // The binary operator .* [p3: ->*] binds its second operand, which shall
5329 // be of type "pointer to member of T" (where T is a completely-defined
5330 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005331 QualType RHSType = RHS.get()->getType();
5332 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005333 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005334 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005335 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005336 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005337 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005338
Sebastian Redl5822f082009-02-07 20:10:22 +00005339 QualType Class(MemPtr->getClass(), 0);
5340
Douglas Gregord07ba342010-10-13 20:41:14 +00005341 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5342 // member pointer points must be completely-defined. However, there is no
5343 // reason for this semantic distinction, and the rule is not enforced by
5344 // other compilers. Therefore, we do not check this property, as it is
5345 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005346
Sebastian Redl5822f082009-02-07 20:10:22 +00005347 // C++ 5.5p2
5348 // [...] to its first operand, which shall be of class T or of a class of
5349 // which T is an unambiguous and accessible base class. [p3: a pointer to
5350 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005351 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005352 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005353 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5354 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005355 else {
5356 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005357 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005358 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005359 return QualType();
5360 }
5361 }
5362
Richard Trieu82402a02011-09-15 21:56:47 +00005363 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005364 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005365 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5366 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005367 return QualType();
5368 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005369
Richard Smith0f59cb32015-12-18 21:45:41 +00005370 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005371 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005372 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005373 return QualType();
5374 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005375
5376 CXXCastPath BasePath;
5377 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5378 SourceRange(LHS.get()->getLocStart(),
5379 RHS.get()->getLocEnd()),
5380 &BasePath))
5381 return QualType();
5382
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005383 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005384 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5385 if (isIndirect)
5386 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005387 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005388 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005389 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005390 }
5391
Richard Trieu82402a02011-09-15 21:56:47 +00005392 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005393 // Diagnose use of pointer-to-member type which when used as
5394 // the functional cast in a pointer-to-member expression.
5395 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5396 return QualType();
5397 }
John McCall7decc9e2010-11-18 06:31:45 +00005398
Sebastian Redl5822f082009-02-07 20:10:22 +00005399 // C++ 5.5p2
5400 // The result is an object or a function of the type specified by the
5401 // second operand.
5402 // The cv qualifiers are the union of those in the pointer and the left side,
5403 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005404 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005405 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005406
Douglas Gregor1d042092011-01-26 16:40:18 +00005407 // C++0x [expr.mptr.oper]p6:
5408 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409 // ill-formed if the second operand is a pointer to member function with
5410 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5411 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005412 // is a pointer to member function with ref-qualifier &&.
5413 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5414 switch (Proto->getRefQualifier()) {
5415 case RQ_None:
5416 // Do nothing
5417 break;
5418
5419 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005420 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5421 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5422 if (Proto->isConst())
5423 Diag(Loc, getLangOpts().CPlusPlus2a
5424 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5425 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5426 else
5427 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5428 << RHSType << 1 << LHS.get()->getSourceRange();
5429 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005430 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005431
Douglas Gregor1d042092011-01-26 16:40:18 +00005432 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005433 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005434 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005435 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005436 break;
5437 }
5438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005439
John McCall7decc9e2010-11-18 06:31:45 +00005440 // C++ [expr.mptr.oper]p6:
5441 // The result of a .* expression whose second operand is a pointer
5442 // to a data member is of the same value category as its
5443 // first operand. The result of a .* expression whose second
5444 // operand is a pointer to a member function is a prvalue. The
5445 // result of an ->* expression is an lvalue if its second operand
5446 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005447 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005448 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005449 return Context.BoundMemberTy;
5450 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005451 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005452 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005453 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005454 }
John McCall7decc9e2010-11-18 06:31:45 +00005455
Sebastian Redl5822f082009-02-07 20:10:22 +00005456 return Result;
5457}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005458
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005459/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005460///
5461/// This is part of the parameter validation for the ? operator. If either
5462/// value operand is a class type, the two operands are attempted to be
5463/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005464/// It returns true if the program is ill-formed and has already been diagnosed
5465/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005466static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5467 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005468 bool &HaveConversion,
5469 QualType &ToType) {
5470 HaveConversion = false;
5471 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472
5473 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005474 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005475 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005476 // The process for determining whether an operand expression E1 of type T1
5477 // can be converted to match an operand expression E2 of type T2 is defined
5478 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005479 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5480 // implicitly converted to type "lvalue reference to T2", subject to the
5481 // constraint that in the conversion the reference must bind directly to
5482 // an lvalue.
5483 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005484 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005485 // the constraint that the reference must bind directly.
5486 if (To->isLValue() || To->isXValue()) {
5487 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5488 : Self.Context.getRValueReferenceType(ToType);
5489
Douglas Gregor838fcc32010-03-26 20:14:36 +00005490 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005492 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005493 if (InitSeq.isDirectReferenceBinding()) {
5494 ToType = T;
5495 HaveConversion = true;
5496 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005498
Douglas Gregor838fcc32010-03-26 20:14:36 +00005499 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005500 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005501 }
John McCall65eb8792010-02-25 01:37:24 +00005502
Sebastian Redl1a99f442009-04-16 17:51:27 +00005503 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5504 // -- if E1 and E2 have class type, and the underlying class types are
5505 // the same or one is a base class of the other:
5506 QualType FTy = From->getType();
5507 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005508 const RecordType *FRec = FTy->getAs<RecordType>();
5509 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005511 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5512 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5513 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005514 // E1 can be converted to match E2 if the class of T2 is the
5515 // same type as, or a base class of, the class of T1, and
5516 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005517 if (FRec == TRec || FDerivedFromT) {
5518 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005519 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005520 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005521 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005522 HaveConversion = true;
5523 return false;
5524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525
Douglas Gregor838fcc32010-03-26 20:14:36 +00005526 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005527 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005528 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Douglas Gregor838fcc32010-03-26 20:14:36 +00005531 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533
Douglas Gregor838fcc32010-03-26 20:14:36 +00005534 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5535 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005536 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005537 // an rvalue).
5538 //
5539 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5540 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005541 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542
Douglas Gregor838fcc32010-03-26 20:14:36 +00005543 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005544 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005545 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005546 ToType = TTy;
5547 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005548 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005549
Sebastian Redl1a99f442009-04-16 17:51:27 +00005550 return false;
5551}
5552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005553/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005554///
5555/// This is part of the parameter validation for the ? operator. If either
5556/// value operand is a class type, overload resolution is used to find a
5557/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005558static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005559 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005560 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005561 OverloadCandidateSet CandidateSet(QuestionLoc,
5562 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005563 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005564 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005565
5566 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005567 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005568 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005569 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005570 ExprResult LHSRes = Self.PerformImplicitConversion(
5571 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5572 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005573 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005574 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005575 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005576
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005577 ExprResult RHSRes = Self.PerformImplicitConversion(
5578 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5579 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005580 if (RHSRes.isInvalid())
5581 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005582 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005583 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005584 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005585 return false;
John Wiegley01296292011-04-08 18:41:53 +00005586 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005587
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005588 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005589
5590 // Emit a better diagnostic if one of the expressions is a null pointer
5591 // constant and the other is a pointer type. In this case, the user most
5592 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005593 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005594 return true;
5595
5596 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005597 << LHS.get()->getType() << RHS.get()->getType()
5598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005599 return true;
5600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005601 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005602 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005603 << LHS.get()->getType() << RHS.get()->getType()
5604 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005605 // FIXME: Print the possible common types by printing the return types of
5606 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005607 break;
5608
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005609 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005610 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005611 }
5612 return true;
5613}
5614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005615/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005616/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005617static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005618 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005619 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005620 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005621 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005622 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005623 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005624 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005625 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
John Wiegley01296292011-04-08 18:41:53 +00005627 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005628 return false;
5629}
5630
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005631/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005632///
5633/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5634/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005635QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5636 ExprResult &RHS, ExprValueKind &VK,
5637 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005638 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005639 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5640 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005641
Richard Smith45edb702012-08-07 22:06:48 +00005642 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005643 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005644 //
5645 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5646 // a is that of a integer vector with the same number of elements and
5647 // size as the vectors of b and c. If one of either b or c is a scalar
5648 // it is implicitly converted to match the type of the vector.
5649 // Otherwise the expression is ill-formed. If both b and c are scalars,
5650 // then b and c are checked and converted to the type of a if possible.
5651 // Unlike the OpenCL ?: operator, the expression is evaluated as
5652 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005653 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005654 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005655 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005656 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005657 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005658 }
5659
John McCall7decc9e2010-11-18 06:31:45 +00005660 // Assume r-value.
5661 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005662 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005663
Sebastian Redl1a99f442009-04-16 17:51:27 +00005664 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005665 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005666 return Context.DependentTy;
5667
Richard Smith45edb702012-08-07 22:06:48 +00005668 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005669 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005670 QualType LTy = LHS.get()->getType();
5671 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005672 bool LVoid = LTy->isVoidType();
5673 bool RVoid = RTy->isVoidType();
5674 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005675 // ... one of the following shall hold:
5676 // -- The second or the third operand (but not both) is a (possibly
5677 // parenthesized) throw-expression; the result is of the type
5678 // and value category of the other.
5679 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5680 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5681 if (LThrow != RThrow) {
5682 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5683 VK = NonThrow->getValueKind();
5684 // DR (no number yet): the result is a bit-field if the
5685 // non-throw-expression operand is a bit-field.
5686 OK = NonThrow->getObjectKind();
5687 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005688 }
5689
Sebastian Redl1a99f442009-04-16 17:51:27 +00005690 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005691 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005692 if (LVoid && RVoid)
5693 return Context.VoidTy;
5694
5695 // Neither holds, error.
5696 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5697 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005698 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005699 return QualType();
5700 }
5701
5702 // Neither is void.
5703
Richard Smithf2b084f2012-08-08 06:13:49 +00005704 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005705 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005706 // either has (cv) class type [...] an attempt is made to convert each of
5707 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005708 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005709 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005710 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005711 QualType L2RType, R2LType;
5712 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005713 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005714 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005715 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005716 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717
Sebastian Redl1a99f442009-04-16 17:51:27 +00005718 // If both can be converted, [...] the program is ill-formed.
5719 if (HaveL2R && HaveR2L) {
5720 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005721 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005722 return QualType();
5723 }
5724
5725 // If exactly one conversion is possible, that conversion is applied to
5726 // the chosen operand and the converted operands are used in place of the
5727 // original operands for the remainder of this section.
5728 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005729 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005730 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005731 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005732 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005733 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005734 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005735 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005736 }
5737 }
5738
Richard Smithf2b084f2012-08-08 06:13:49 +00005739 // C++11 [expr.cond]p3
5740 // if both are glvalues of the same value category and the same type except
5741 // for cv-qualification, an attempt is made to convert each of those
5742 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005743 // FIXME:
5744 // Resolving a defect in P0012R1: we extend this to cover all cases where
5745 // one of the operands is reference-compatible with the other, in order
5746 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005747 ExprValueKind LVK = LHS.get()->getValueKind();
5748 ExprValueKind RVK = RHS.get()->getValueKind();
5749 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005750 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005751 // DerivedToBase was already handled by the class-specific case above.
5752 // FIXME: Should we allow ObjC conversions here?
5753 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5754 if (CompareReferenceRelationship(
5755 QuestionLoc, LTy, RTy, DerivedToBase,
5756 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005757 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5758 // [...] subject to the constraint that the reference must bind
5759 // directly [...]
5760 !RHS.get()->refersToBitField() &&
5761 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005762 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005763 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005764 } else if (CompareReferenceRelationship(
5765 QuestionLoc, RTy, LTy, DerivedToBase,
5766 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005767 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5768 !LHS.get()->refersToBitField() &&
5769 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005770 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5771 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005772 }
5773 }
5774
5775 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005776 // If the second and third operands are glvalues of the same value
5777 // category and have the same type, the result is of that type and
5778 // value category and it is a bit-field if the second or the third
5779 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005780 // We only extend this to bitfields, not to the crazy other kinds of
5781 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005782 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005783 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005784 LHS.get()->isOrdinaryOrBitFieldObject() &&
5785 RHS.get()->isOrdinaryOrBitFieldObject()) {
5786 VK = LHS.get()->getValueKind();
5787 if (LHS.get()->getObjectKind() == OK_BitField ||
5788 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005789 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005790
5791 // If we have function pointer types, unify them anyway to unify their
5792 // exception specifications, if any.
5793 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5794 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005795 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005796 /*ConvertArgs*/false);
5797 LTy = Context.getQualifiedType(LTy, Qs);
5798
5799 assert(!LTy.isNull() && "failed to find composite pointer type for "
5800 "canonically equivalent function ptr types");
5801 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5802 }
5803
John McCall7decc9e2010-11-18 06:31:45 +00005804 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005805 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005806
Richard Smithf2b084f2012-08-08 06:13:49 +00005807 // C++11 [expr.cond]p5
5808 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005809 // do not have the same type, and either has (cv) class type, ...
5810 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5811 // ... overload resolution is used to determine the conversions (if any)
5812 // to be applied to the operands. If the overload resolution fails, the
5813 // program is ill-formed.
5814 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5815 return QualType();
5816 }
5817
Richard Smithf2b084f2012-08-08 06:13:49 +00005818 // C++11 [expr.cond]p6
5819 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005820 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005821 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5822 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005823 if (LHS.isInvalid() || RHS.isInvalid())
5824 return QualType();
5825 LTy = LHS.get()->getType();
5826 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005827
5828 // After those conversions, one of the following shall hold:
5829 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005830 // is of that type. If the operands have class type, the result
5831 // is a prvalue temporary of the result type, which is
5832 // copy-initialized from either the second operand or the third
5833 // operand depending on the value of the first operand.
5834 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5835 if (LTy->isRecordType()) {
5836 // The operands have class type. Make a temporary copy.
5837 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005838
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005839 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5840 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005841 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005842 if (LHSCopy.isInvalid())
5843 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005844
5845 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5846 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005847 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005848 if (RHSCopy.isInvalid())
5849 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005850
John Wiegley01296292011-04-08 18:41:53 +00005851 LHS = LHSCopy;
5852 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005853 }
5854
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005855 // If we have function pointer types, unify them anyway to unify their
5856 // exception specifications, if any.
5857 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5858 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5859 assert(!LTy.isNull() && "failed to find composite pointer type for "
5860 "canonically equivalent function ptr types");
5861 }
5862
Sebastian Redl1a99f442009-04-16 17:51:27 +00005863 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005864 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005865
Douglas Gregor46188682010-05-18 22:42:18 +00005866 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005867 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005868 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5869 /*AllowBothBool*/true,
5870 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005871
Sebastian Redl1a99f442009-04-16 17:51:27 +00005872 // -- The second and third operands have arithmetic or enumeration type;
5873 // the usual arithmetic conversions are performed to bring them to a
5874 // common type, and the result is of that type.
5875 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005876 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005877 if (LHS.isInvalid() || RHS.isInvalid())
5878 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005879 if (ResTy.isNull()) {
5880 Diag(QuestionLoc,
5881 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5882 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5883 return QualType();
5884 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005885
5886 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5887 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5888
5889 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005890 }
5891
5892 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005893 // type and the other is a null pointer constant, or both are null
5894 // pointer constants, at least one of which is non-integral; pointer
5895 // conversions and qualification conversions are performed to bring them
5896 // to their composite pointer type. The result is of the composite
5897 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005898 // -- The second and third operands have pointer to member type, or one has
5899 // pointer to member type and the other is a null pointer constant;
5900 // pointer to member conversions and qualification conversions are
5901 // performed to bring them to a common type, whose cv-qualification
5902 // shall match the cv-qualification of either the second or the third
5903 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005904 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5905 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005906 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005907
Douglas Gregor697a3912010-04-01 22:47:07 +00005908 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005909 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5910 if (!Composite.isNull())
5911 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005912
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005913 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005914 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005915 return QualType();
5916
Sebastian Redl1a99f442009-04-16 17:51:27 +00005917 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005918 << LHS.get()->getType() << RHS.get()->getType()
5919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005920 return QualType();
5921}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005922
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005923static FunctionProtoType::ExceptionSpecInfo
5924mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5925 FunctionProtoType::ExceptionSpecInfo ESI2,
5926 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5927 ExceptionSpecificationType EST1 = ESI1.Type;
5928 ExceptionSpecificationType EST2 = ESI2.Type;
5929
5930 // If either of them can throw anything, that is the result.
5931 if (EST1 == EST_None) return ESI1;
5932 if (EST2 == EST_None) return ESI2;
5933 if (EST1 == EST_MSAny) return ESI1;
5934 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005935 if (EST1 == EST_NoexceptFalse) return ESI1;
5936 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005937
5938 // If either of them is non-throwing, the result is the other.
5939 if (EST1 == EST_DynamicNone) return ESI2;
5940 if (EST2 == EST_DynamicNone) return ESI1;
5941 if (EST1 == EST_BasicNoexcept) return ESI2;
5942 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005943 if (EST1 == EST_NoexceptTrue) return ESI2;
5944 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005945
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005946 // If we're left with value-dependent computed noexcept expressions, we're
5947 // stuck. Before C++17, we can just drop the exception specification entirely,
5948 // since it's not actually part of the canonical type. And this should never
5949 // happen in C++17, because it would mean we were computing the composite
5950 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00005951 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005952 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005953 "computing composite pointer type of dependent types");
5954 return FunctionProtoType::ExceptionSpecInfo();
5955 }
5956
5957 // Switch over the possibilities so that people adding new values know to
5958 // update this function.
5959 switch (EST1) {
5960 case EST_None:
5961 case EST_DynamicNone:
5962 case EST_MSAny:
5963 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00005964 case EST_DependentNoexcept:
5965 case EST_NoexceptFalse:
5966 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005967 llvm_unreachable("handled above");
5968
5969 case EST_Dynamic: {
5970 // This is the fun case: both exception specifications are dynamic. Form
5971 // the union of the two lists.
5972 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5973 llvm::SmallPtrSet<QualType, 8> Found;
5974 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5975 for (QualType E : Exceptions)
5976 if (Found.insert(S.Context.getCanonicalType(E)).second)
5977 ExceptionTypeStorage.push_back(E);
5978
5979 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5980 Result.Exceptions = ExceptionTypeStorage;
5981 return Result;
5982 }
5983
5984 case EST_Unevaluated:
5985 case EST_Uninstantiated:
5986 case EST_Unparsed:
5987 llvm_unreachable("shouldn't see unresolved exception specifications here");
5988 }
5989
5990 llvm_unreachable("invalid ExceptionSpecificationType");
5991}
5992
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005993/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005994///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005995/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005996/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005997/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005998/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005999///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006000/// \param Loc The location of the operator requiring these two expressions to
6001/// be converted to the composite pointer type.
6002///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006003/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006004QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006005 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006006 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006007 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006008
6009 // C++1z [expr]p14:
6010 // The composite pointer type of two operands p1 and p2 having types T1
6011 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006012 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006013
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006014 // where at least one is a pointer or pointer to member type or
6015 // std::nullptr_t is:
6016 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6017 T1->isNullPtrType();
6018 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6019 T2->isNullPtrType();
6020 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006021 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006022
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006023 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6024 // This can't actually happen, following the standard, but we also use this
6025 // to implement the end of [expr.conv], which hits this case.
6026 //
6027 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6028 if (T1IsPointerLike &&
6029 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006030 if (ConvertArgs)
6031 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6032 ? CK_NullToMemberPointer
6033 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006034 return T1;
6035 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006036 if (T2IsPointerLike &&
6037 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006038 if (ConvertArgs)
6039 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6040 ? CK_NullToMemberPointer
6041 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006042 return T2;
6043 }
Mike Stump11289f42009-09-09 15:08:12 +00006044
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006045 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006046 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006047 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006048 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6049 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006050
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006051 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6052 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6053 // the union of cv1 and cv2;
6054 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6055 // "pointer to function", where the function types are otherwise the same,
6056 // "pointer to function";
6057 // FIXME: This rule is defective: it should also permit removing noexcept
6058 // from a pointer to member function. As a Clang extension, we also
6059 // permit removing 'noreturn', so we generalize this rule to;
6060 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6061 // "pointer to member function" and the pointee types can be unified
6062 // by a function pointer conversion, that conversion is applied
6063 // before checking the following rules.
6064 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6065 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6066 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6067 // respectively;
6068 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6069 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6070 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6071 // T1 or the cv-combined type of T1 and T2, respectively;
6072 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6073 // T2;
6074 //
6075 // If looked at in the right way, these bullets all do the same thing.
6076 // What we do here is, we build the two possible cv-combined types, and try
6077 // the conversions in both directions. If only one works, or if the two
6078 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006079 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006080 //
6081 // Note that this will fail to find a composite pointer type for "pointer
6082 // to void" and "pointer to function". We can't actually perform the final
6083 // conversion in this case, even though a composite pointer type formally
6084 // exists.
6085 SmallVector<unsigned, 4> QualifierUnion;
6086 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006087 QualType Composite1 = T1;
6088 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006089 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006090 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006091 const PointerType *Ptr1, *Ptr2;
6092 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6093 (Ptr2 = Composite2->getAs<PointerType>())) {
6094 Composite1 = Ptr1->getPointeeType();
6095 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006096
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006097 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006098 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006099 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006100 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006101
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006102 QualifierUnion.push_back(
6103 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006104 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006105 continue;
6106 }
Mike Stump11289f42009-09-09 15:08:12 +00006107
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006108 const MemberPointerType *MemPtr1, *MemPtr2;
6109 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6110 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6111 Composite1 = MemPtr1->getPointeeType();
6112 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006114 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006115 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006116 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006117 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006118
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006119 QualifierUnion.push_back(
6120 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6121 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6122 MemPtr2->getClass()));
6123 continue;
6124 }
Mike Stump11289f42009-09-09 15:08:12 +00006125
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006126 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006127
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006128 // Cannot unwrap any more types.
6129 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006130 }
Mike Stump11289f42009-09-09 15:08:12 +00006131
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006132 // Apply the function pointer conversion to unify the types. We've already
6133 // unwrapped down to the function types, and we want to merge rather than
6134 // just convert, so do this ourselves rather than calling
6135 // IsFunctionConversion.
6136 //
6137 // FIXME: In order to match the standard wording as closely as possible, we
6138 // currently only do this under a single level of pointers. Ideally, we would
6139 // allow this in general, and set NeedConstBefore to the relevant depth on
6140 // the side(s) where we changed anything.
6141 if (QualifierUnion.size() == 1) {
6142 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6143 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6144 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6145 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6146
6147 // The result is noreturn if both operands are.
6148 bool Noreturn =
6149 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6150 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6151 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6152
6153 // The result is nothrow if both operands are.
6154 SmallVector<QualType, 8> ExceptionTypeStorage;
6155 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6156 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6157 ExceptionTypeStorage);
6158
6159 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6160 FPT1->getParamTypes(), EPI1);
6161 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6162 FPT2->getParamTypes(), EPI2);
6163 }
6164 }
6165 }
6166
Richard Smith5e9746f2016-10-21 22:00:42 +00006167 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006168 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006169 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006170 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006171 for (unsigned I = 0; I != NeedConstBefore; ++I)
6172 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006173 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006175
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006176 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006177 auto MOC = MemberOfClass.rbegin();
6178 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6179 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6180 auto Classes = *MOC++;
6181 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006182 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006183 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006184 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006185 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006186 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006187 } else {
6188 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006189 Composite1 =
6190 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6191 Composite2 =
6192 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006193 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006194 }
6195
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006196 struct Conversion {
6197 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006198 Expr *&E1, *&E2;
6199 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006200 InitializedEntity Entity;
6201 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006202 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006203 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006204
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006205 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6206 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006207 : S(S), E1(E1), E2(E2), Composite(Composite),
6208 Entity(InitializedEntity::InitializeTemporary(Composite)),
6209 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6210 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6211 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006212
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006213 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006214 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6215 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006216 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006217 E1 = E1Result.getAs<Expr>();
6218
6219 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6220 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006221 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006222 E2 = E2Result.getAs<Expr>();
6223
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006224 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006225 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006226 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006227
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006228 // Try to convert to each composite pointer type.
6229 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006230 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6231 if (ConvertArgs && C1.perform())
6232 return QualType();
6233 return C1.Composite;
6234 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006235 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006236
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006237 if (C1.Viable == C2.Viable) {
6238 // Either Composite1 and Composite2 are viable and are different, or
6239 // neither is viable.
6240 // FIXME: How both be viable and different?
6241 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006242 }
6243
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006244 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006245 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6246 return QualType();
6247
6248 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006249}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006250
John McCalldadc5752010-08-24 06:29:42 +00006251ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006252 if (!E)
6253 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006254
John McCall31168b02011-06-15 23:02:42 +00006255 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6256
6257 // If the result is a glvalue, we shouldn't bind it.
6258 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006259 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006260
John McCall31168b02011-06-15 23:02:42 +00006261 // In ARC, calls that return a retainable type can return retained,
6262 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006263 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006264 E->getType()->isObjCRetainableType()) {
6265
6266 bool ReturnsRetained;
6267
6268 // For actual calls, we compute this by examining the type of the
6269 // called value.
6270 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6271 Expr *Callee = Call->getCallee()->IgnoreParens();
6272 QualType T = Callee->getType();
6273
6274 if (T == Context.BoundMemberTy) {
6275 // Handle pointer-to-members.
6276 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6277 T = BinOp->getRHS()->getType();
6278 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6279 T = Mem->getMemberDecl()->getType();
6280 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006281
John McCall31168b02011-06-15 23:02:42 +00006282 if (const PointerType *Ptr = T->getAs<PointerType>())
6283 T = Ptr->getPointeeType();
6284 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6285 T = Ptr->getPointeeType();
6286 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6287 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006288
John McCall31168b02011-06-15 23:02:42 +00006289 const FunctionType *FTy = T->getAs<FunctionType>();
6290 assert(FTy && "call to value not of function type?");
6291 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6292
6293 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6294 // type always produce a +1 object.
6295 } else if (isa<StmtExpr>(E)) {
6296 ReturnsRetained = true;
6297
Ted Kremeneke65b0862012-03-06 20:05:56 +00006298 // We hit this case with the lambda conversion-to-block optimization;
6299 // we don't want any extra casts here.
6300 } else if (isa<CastExpr>(E) &&
6301 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006302 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006303
John McCall31168b02011-06-15 23:02:42 +00006304 // For message sends and property references, we try to find an
6305 // actual method. FIXME: we should infer retention by selector in
6306 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006307 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006308 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006309 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6310 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006311 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6312 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006313 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006314 // Don't do reclaims if we're using the zero-element array
6315 // constant.
6316 if (ArrayLit->getNumElements() == 0 &&
6317 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6318 return E;
6319
Ted Kremeneke65b0862012-03-06 20:05:56 +00006320 D = ArrayLit->getArrayWithObjectsMethod();
6321 } else if (ObjCDictionaryLiteral *DictLit
6322 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006323 // Don't do reclaims if we're using the zero-element dictionary
6324 // constant.
6325 if (DictLit->getNumElements() == 0 &&
6326 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6327 return E;
6328
Ted Kremeneke65b0862012-03-06 20:05:56 +00006329 D = DictLit->getDictWithObjectsMethod();
6330 }
John McCall31168b02011-06-15 23:02:42 +00006331
6332 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006333
6334 // Don't do reclaims on performSelector calls; despite their
6335 // return type, the invoked method doesn't necessarily actually
6336 // return an object.
6337 if (!ReturnsRetained &&
6338 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006339 return E;
John McCall31168b02011-06-15 23:02:42 +00006340 }
6341
John McCall16de4d22011-11-14 19:53:16 +00006342 // Don't reclaim an object of Class type.
6343 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006344 return E;
John McCall16de4d22011-11-14 19:53:16 +00006345
Tim Shen4a05bb82016-06-21 20:29:17 +00006346 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006347
John McCall2d637d22011-09-10 06:18:15 +00006348 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6349 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006350 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6351 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006352 }
6353
David Blaikiebbafb8a2012-03-11 07:00:24 +00006354 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006355 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006356
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006357 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6358 // a fast path for the common case that the type is directly a RecordType.
6359 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006360 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006361 while (!RT) {
6362 switch (T->getTypeClass()) {
6363 case Type::Record:
6364 RT = cast<RecordType>(T);
6365 break;
6366 case Type::ConstantArray:
6367 case Type::IncompleteArray:
6368 case Type::VariableArray:
6369 case Type::DependentSizedArray:
6370 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6371 break;
6372 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006373 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006374 }
6375 }
Mike Stump11289f42009-09-09 15:08:12 +00006376
Richard Smithfd555f62012-02-22 02:04:18 +00006377 // That should be enough to guarantee that this type is complete, if we're
6378 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006379 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006380 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006381 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006382
6383 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006384 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006385
John McCall31168b02011-06-15 23:02:42 +00006386 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006387 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006388 CheckDestructorAccess(E->getExprLoc(), Destructor,
6389 PDiag(diag::err_access_dtor_temp)
6390 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006391 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6392 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006393
Richard Smithfd555f62012-02-22 02:04:18 +00006394 // If destructor is trivial, we can avoid the extra copy.
6395 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006396 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006397
John McCall28fc7092011-11-10 05:35:25 +00006398 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006399 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006400 }
Richard Smitheec915d62012-02-18 04:13:32 +00006401
6402 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006403 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6404
6405 if (IsDecltype)
6406 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6407
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006408 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006409}
6410
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006411ExprResult
John McCall5d413782010-12-06 08:20:24 +00006412Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006413 if (SubExpr.isInvalid())
6414 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006415
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006416 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006417}
6418
John McCall28fc7092011-11-10 05:35:25 +00006419Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006420 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006421
Eli Friedman3bda6b12012-02-02 23:15:15 +00006422 CleanupVarDeclMarking();
6423
John McCall28fc7092011-11-10 05:35:25 +00006424 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6425 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006426 assert(Cleanup.exprNeedsCleanups() ||
6427 ExprCleanupObjects.size() == FirstCleanup);
6428 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006429 return SubExpr;
6430
Craig Topper5fc8fc22014-08-27 06:28:36 +00006431 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6432 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006433
Tim Shen4a05bb82016-06-21 20:29:17 +00006434 auto *E = ExprWithCleanups::Create(
6435 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006436 DiscardCleanupsInEvaluationContext();
6437
6438 return E;
6439}
6440
John McCall5d413782010-12-06 08:20:24 +00006441Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006442 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006443
Eli Friedman3bda6b12012-02-02 23:15:15 +00006444 CleanupVarDeclMarking();
6445
Tim Shen4a05bb82016-06-21 20:29:17 +00006446 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006447 return SubStmt;
6448
6449 // FIXME: In order to attach the temporaries, wrap the statement into
6450 // a StmtExpr; currently this is only used for asm statements.
6451 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6452 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006453 CompoundStmt *CompStmt = CompoundStmt::Create(
6454 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006455 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6456 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006457 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006458}
6459
Richard Smithfd555f62012-02-22 02:04:18 +00006460/// Process the expression contained within a decltype. For such expressions,
6461/// certain semantic checks on temporaries are delayed until this point, and
6462/// are omitted for the 'topmost' call in the decltype expression. If the
6463/// topmost call bound a temporary, strip that temporary off the expression.
6464ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006465 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006466
6467 // C++11 [expr.call]p11:
6468 // If a function call is a prvalue of object type,
6469 // -- if the function call is either
6470 // -- the operand of a decltype-specifier, or
6471 // -- the right operand of a comma operator that is the operand of a
6472 // decltype-specifier,
6473 // a temporary object is not introduced for the prvalue.
6474
6475 // Recursively rebuild ParenExprs and comma expressions to strip out the
6476 // outermost CXXBindTemporaryExpr, if any.
6477 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6478 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6479 if (SubExpr.isInvalid())
6480 return ExprError();
6481 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006482 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006483 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006484 }
6485 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6486 if (BO->getOpcode() == BO_Comma) {
6487 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6488 if (RHS.isInvalid())
6489 return ExprError();
6490 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006491 return E;
6492 return new (Context) BinaryOperator(
6493 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006494 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006495 }
6496 }
6497
6498 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006499 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6500 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006501 if (TopCall)
6502 E = TopCall;
6503 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006504 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006505
6506 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006507 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006508
Richard Smithf86b0ae2012-07-28 19:54:11 +00006509 // In MS mode, don't perform any extra checking of call return types within a
6510 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006511 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006512 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006513
Richard Smithfd555f62012-02-22 02:04:18 +00006514 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006515 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6516 I != N; ++I) {
6517 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006518 if (Call == TopCall)
6519 continue;
6520
David Majnemerced8bdf2015-02-25 17:36:15 +00006521 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006522 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006523 Call, Call->getDirectCallee()))
6524 return ExprError();
6525 }
6526
6527 // Now all relevant types are complete, check the destructors are accessible
6528 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006529 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6530 I != N; ++I) {
6531 CXXBindTemporaryExpr *Bind =
6532 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006533 if (Bind == TopBind)
6534 continue;
6535
6536 CXXTemporary *Temp = Bind->getTemporary();
6537
6538 CXXRecordDecl *RD =
6539 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6540 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6541 Temp->setDestructor(Destructor);
6542
Richard Smith7d847b12012-05-11 22:20:10 +00006543 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6544 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006545 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006546 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006547 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6548 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006549
6550 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006551 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006552 }
6553
6554 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006555 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006556}
6557
Richard Smith79c927b2013-11-06 19:31:51 +00006558/// Note a set of 'operator->' functions that were used for a member access.
6559static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006560 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006561 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6562 // FIXME: Make this configurable?
6563 unsigned Limit = 9;
6564 if (OperatorArrows.size() > Limit) {
6565 // Produce Limit-1 normal notes and one 'skipping' note.
6566 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6567 SkipCount = OperatorArrows.size() - (Limit - 1);
6568 }
6569
6570 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6571 if (I == SkipStart) {
6572 S.Diag(OperatorArrows[I]->getLocation(),
6573 diag::note_operator_arrows_suppressed)
6574 << SkipCount;
6575 I += SkipCount;
6576 } else {
6577 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6578 << OperatorArrows[I]->getCallResultType();
6579 ++I;
6580 }
6581 }
6582}
6583
Nico Weber964d3322015-02-16 22:35:45 +00006584ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6585 SourceLocation OpLoc,
6586 tok::TokenKind OpKind,
6587 ParsedType &ObjectType,
6588 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006589 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006590 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006591 if (Result.isInvalid()) return ExprError();
6592 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006593
John McCall526ab472011-10-25 17:37:35 +00006594 Result = CheckPlaceholderExpr(Base);
6595 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006596 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006597
John McCallb268a282010-08-23 23:25:46 +00006598 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006599 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006600 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006601 // If we have a pointer to a dependent type and are using the -> operator,
6602 // the object type is the type that the pointer points to. We might still
6603 // have enough information about that type to do something useful.
6604 if (OpKind == tok::arrow)
6605 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6606 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607
John McCallba7bf592010-08-24 05:47:05 +00006608 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006609 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006610 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006611 }
Mike Stump11289f42009-09-09 15:08:12 +00006612
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006613 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006614 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006615 // returned, with the original second operand.
6616 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006617 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006618 bool NoArrowOperatorFound = false;
6619 bool FirstIteration = true;
6620 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006621 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006622 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006623 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006624 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006626 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006627 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6628 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006629 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006630 noteOperatorArrows(*this, OperatorArrows);
6631 Diag(OpLoc, diag::note_operator_arrow_depth)
6632 << getLangOpts().ArrowDepth;
6633 return ExprError();
6634 }
6635
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006636 Result = BuildOverloadedArrowExpr(
6637 S, Base, OpLoc,
6638 // When in a template specialization and on the first loop iteration,
6639 // potentially give the default diagnostic (with the fixit in a
6640 // separate note) instead of having the error reported back to here
6641 // and giving a diagnostic with a fixit attached to the error itself.
6642 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006643 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006644 : &NoArrowOperatorFound);
6645 if (Result.isInvalid()) {
6646 if (NoArrowOperatorFound) {
6647 if (FirstIteration) {
6648 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006649 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006650 << FixItHint::CreateReplacement(OpLoc, ".");
6651 OpKind = tok::period;
6652 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006653 }
6654 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6655 << BaseType << Base->getSourceRange();
6656 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006657 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006658 Diag(CD->getLocStart(),
6659 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006660 }
6661 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006662 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006663 }
John McCallb268a282010-08-23 23:25:46 +00006664 Base = Result.get();
6665 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006666 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006667 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006668 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006669 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006670 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6671 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006672 return ExprError();
6673 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006674 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006675 }
Mike Stump11289f42009-09-09 15:08:12 +00006676
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006677 if (OpKind == tok::arrow &&
6678 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006679 BaseType = BaseType->getPointeeType();
6680 }
Mike Stump11289f42009-09-09 15:08:12 +00006681
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006682 // Objective-C properties allow "." access on Objective-C pointer types,
6683 // so adjust the base type to the object type itself.
6684 if (BaseType->isObjCObjectPointerType())
6685 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006686
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006687 // C++ [basic.lookup.classref]p2:
6688 // [...] If the type of the object expression is of pointer to scalar
6689 // type, the unqualified-id is looked up in the context of the complete
6690 // postfix-expression.
6691 //
6692 // This also indicates that we could be parsing a pseudo-destructor-name.
6693 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006694 // expressions or normal member (ivar or property) access expressions, and
6695 // it's legal for the type to be incomplete if this is a pseudo-destructor
6696 // call. We'll do more incomplete-type checks later in the lookup process,
6697 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006698 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006699 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006700 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006701 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006702 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006703 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006704 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006705 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006706 }
Mike Stump11289f42009-09-09 15:08:12 +00006707
Douglas Gregor3024f072012-04-16 07:05:22 +00006708 // The object type must be complete (or dependent), or
6709 // C++11 [expr.prim.general]p3:
6710 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006711 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006712 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006713 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006714 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006715 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006716 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006718 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006719 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006720 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006721 // type C (or of pointer to a class type C), the unqualified-id is looked
6722 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006723 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006724 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006725}
6726
Simon Pilgrim75c26882016-09-30 14:25:09 +00006727static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006728 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006729 if (Base->hasPlaceholderType()) {
6730 ExprResult result = S.CheckPlaceholderExpr(Base);
6731 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006732 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006733 }
6734 ObjectType = Base->getType();
6735
David Blaikie1d578782011-12-16 16:03:09 +00006736 // C++ [expr.pseudo]p2:
6737 // The left-hand side of the dot operator shall be of scalar type. The
6738 // left-hand side of the arrow operator shall be of pointer to scalar type.
6739 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006740 // Note that this is rather different from the normal handling for the
6741 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006742 if (OpKind == tok::arrow) {
6743 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6744 ObjectType = Ptr->getPointeeType();
6745 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006746 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006747 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6748 << ObjectType << true
6749 << FixItHint::CreateReplacement(OpLoc, ".");
6750 if (S.isSFINAEContext())
6751 return true;
6752
6753 OpKind = tok::period;
6754 }
6755 }
6756
6757 return false;
6758}
6759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006760/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006761/// pointer objects.
6762static bool
6763canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6764 QualType DestructedType) {
6765 // If this is a record type, check if its destructor is callable.
6766 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6767 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6768 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6769 return false;
6770 }
6771
6772 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6773 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6774 DestructedType->isVectorType();
6775}
6776
John McCalldadc5752010-08-24 06:29:42 +00006777ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006778 SourceLocation OpLoc,
6779 tok::TokenKind OpKind,
6780 const CXXScopeSpec &SS,
6781 TypeSourceInfo *ScopeTypeInfo,
6782 SourceLocation CCLoc,
6783 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006784 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006785 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006786
Eli Friedman0ce4de42012-01-25 04:35:06 +00006787 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006788 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6789 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006790
Douglas Gregorc5c57342012-09-10 14:57:06 +00006791 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6792 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006793 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006794 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006795 else {
Nico Weber58829272012-01-23 05:50:57 +00006796 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6797 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006798 return ExprError();
6799 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006800 }
6801
6802 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006803 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006804 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006805 if (DestructedTypeInfo) {
6806 QualType DestructedType = DestructedTypeInfo->getType();
6807 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006808 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006809 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6810 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006811 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6812 // Foo *foo;
6813 // foo.~Foo();
6814 if (OpKind == tok::period && ObjectType->isPointerType() &&
6815 Context.hasSameUnqualifiedType(DestructedType,
6816 ObjectType->getPointeeType())) {
6817 auto Diagnostic =
6818 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6819 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006821 // Issue a fixit only when the destructor is valid.
6822 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6823 *this, DestructedType))
6824 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6825
6826 // Recover by setting the object type to the destructed type and the
6827 // operator to '->'.
6828 ObjectType = DestructedType;
6829 OpKind = tok::arrow;
6830 } else {
6831 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6832 << ObjectType << DestructedType << Base->getSourceRange()
6833 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6834
6835 // Recover by setting the destructed type to the object type.
6836 DestructedType = ObjectType;
6837 DestructedTypeInfo =
6838 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6839 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6840 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006841 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006842 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006843
John McCall31168b02011-06-15 23:02:42 +00006844 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6845 // Okay: just pretend that the user provided the correctly-qualified
6846 // type.
6847 } else {
6848 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6849 << ObjectType << DestructedType << Base->getSourceRange()
6850 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6851 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006852
John McCall31168b02011-06-15 23:02:42 +00006853 // Recover by setting the destructed type to the object type.
6854 DestructedType = ObjectType;
6855 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6856 DestructedTypeStart);
6857 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6858 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006859 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006862 // C++ [expr.pseudo]p2:
6863 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6864 // form
6865 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006867 //
6868 // shall designate the same scalar type.
6869 if (ScopeTypeInfo) {
6870 QualType ScopeType = ScopeTypeInfo->getType();
6871 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006872 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006874 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006875 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006876 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006877 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006879 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006880 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006881 }
6882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883
John McCallb268a282010-08-23 23:25:46 +00006884 Expr *Result
6885 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6886 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006887 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006888 ScopeTypeInfo,
6889 CCLoc,
6890 TildeLoc,
6891 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
David Majnemerced8bdf2015-02-25 17:36:15 +00006893 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006894}
6895
John McCalldadc5752010-08-24 06:29:42 +00006896ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006897 SourceLocation OpLoc,
6898 tok::TokenKind OpKind,
6899 CXXScopeSpec &SS,
6900 UnqualifiedId &FirstTypeName,
6901 SourceLocation CCLoc,
6902 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006903 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006904 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6905 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006906 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006907 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6908 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006909 "Invalid second type name in pseudo-destructor");
6910
Eli Friedman0ce4de42012-01-25 04:35:06 +00006911 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006912 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6913 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006914
6915 // Compute the object type that we should use for name lookup purposes. Only
6916 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006917 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006918 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006919 if (ObjectType->isRecordType())
6920 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006921 else if (ObjectType->isDependentType())
6922 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
6925 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006926 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006927 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006928 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006929 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006930 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006931 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006932 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006933 S, &SS, true, false, ObjectTypePtrForLookup,
6934 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006935 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006936 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6937 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006938 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006939 // couldn't find anything useful in scope. Just store the identifier and
6940 // it's location, and we'll perform (qualified) name lookup again at
6941 // template instantiation time.
6942 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6943 SecondTypeName.StartLocation);
6944 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006945 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006946 diag::err_pseudo_dtor_destructor_non_type)
6947 << SecondTypeName.Identifier << ObjectType;
6948 if (isSFINAEContext())
6949 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006950
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006951 // Recover by assuming we had the right type all along.
6952 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006953 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006954 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006955 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006956 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006957 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006958 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006959 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006960 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006961 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006962 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006963 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006964 TemplateId->TemplateNameLoc,
6965 TemplateId->LAngleLoc,
6966 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006967 TemplateId->RAngleLoc,
6968 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006969 if (T.isInvalid() || !T.get()) {
6970 // Recover by assuming we had the right type all along.
6971 DestructedType = ObjectType;
6972 } else
6973 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
6976 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006977 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006978 if (!DestructedType.isNull()) {
6979 if (!DestructedTypeInfo)
6980 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006981 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006982 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006985 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006986 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006987 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006988 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006989 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006990 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006992 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006993 S, &SS, true, false, ObjectTypePtrForLookup,
6994 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006995 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006996 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006997 diag::err_pseudo_dtor_destructor_non_type)
6998 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007000 if (isSFINAEContext())
7001 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007003 // Just drop this type. It's unnecessary anyway.
7004 ScopeType = QualType();
7005 } else
7006 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007007 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007008 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007009 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007010 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007011 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007012 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007013 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007014 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007015 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007016 TemplateId->TemplateNameLoc,
7017 TemplateId->LAngleLoc,
7018 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007019 TemplateId->RAngleLoc,
7020 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007021 if (T.isInvalid() || !T.get()) {
7022 // Recover by dropping this type.
7023 ScopeType = QualType();
7024 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007026 }
7027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007028
Douglas Gregor90ad9222010-02-24 23:02:30 +00007029 if (!ScopeType.isNull() && !ScopeTypeInfo)
7030 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7031 FirstTypeName.StartLocation);
7032
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033
John McCallb268a282010-08-23 23:25:46 +00007034 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007035 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007036 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007037}
7038
David Blaikie1d578782011-12-16 16:03:09 +00007039ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7040 SourceLocation OpLoc,
7041 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007042 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007043 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007044 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007045 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7046 return ExprError();
7047
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007048 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7049 false);
David Blaikie1d578782011-12-16 16:03:09 +00007050
7051 TypeLocBuilder TLB;
7052 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7053 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7054 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7055 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7056
7057 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007058 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007059 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007060}
7061
John Wiegley01296292011-04-08 18:41:53 +00007062ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007063 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007064 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00007065 if (Method->getParent()->isLambda() &&
7066 Method->getConversionType()->isBlockPointerType()) {
7067 // This is a lambda coversion to block pointer; check if the argument
7068 // is a LambdaExpr.
7069 Expr *SubE = E;
7070 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7071 if (CE && CE->getCastKind() == CK_NoOp)
7072 SubE = CE->getSubExpr();
7073 SubE = SubE->IgnoreParens();
7074 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7075 SubE = BE->getSubExpr();
7076 if (isa<LambdaExpr>(SubE)) {
7077 // For the conversion to block pointer on a lambda expression, we
7078 // construct a special BlockLiteral instead; this doesn't really make
7079 // a difference in ARC, but outside of ARC the resulting block literal
7080 // follows the normal lifetime rules for block literals instead of being
7081 // autoreleased.
7082 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007083 PushExpressionEvaluationContext(
7084 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00007085 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
7086 E->getExprLoc(),
7087 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00007088 PopExpressionEvaluationContext();
7089
Eli Friedman98b01ed2012-03-01 04:01:32 +00007090 if (Exp.isInvalid())
7091 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
7092 return Exp;
7093 }
7094 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007095
Craig Topperc3ec1492014-05-26 06:22:03 +00007096 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00007097 FoundDecl, Method);
7098 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00007099 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00007100
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007101 MemberExpr *ME = new (Context) MemberExpr(
7102 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7103 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007104 if (HadMultipleCandidates)
7105 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007106 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007107
Alp Toker314cc812014-01-25 16:55:45 +00007108 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007109 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7110 ResultType = ResultType.getNonLValueExprType(Context);
7111
Douglas Gregor27381f32009-11-23 12:27:39 +00007112 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00007113 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00007114 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00007115
7116 if (CheckFunctionCall(Method, CE,
7117 Method->getType()->castAs<FunctionProtoType>()))
7118 return ExprError();
7119
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007120 return CE;
7121}
7122
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007123ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7124 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007125 // If the operand is an unresolved lookup expression, the expression is ill-
7126 // formed per [over.over]p1, because overloaded function names cannot be used
7127 // without arguments except in explicit contexts.
7128 ExprResult R = CheckPlaceholderExpr(Operand);
7129 if (R.isInvalid())
7130 return R;
7131
7132 // The operand may have been modified when checking the placeholder type.
7133 Operand = R.get();
7134
Richard Smith51ec0cf2017-02-21 01:17:38 +00007135 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007136 // The expression operand for noexcept is in an unevaluated expression
7137 // context, so side effects could result in unintended consequences.
7138 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7139 }
7140
Richard Smithf623c962012-04-17 00:58:00 +00007141 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007142 return new (Context)
7143 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007144}
7145
7146ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7147 Expr *Operand, SourceLocation RParen) {
7148 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007149}
7150
Eli Friedmanf798f652012-05-24 22:04:19 +00007151static bool IsSpecialDiscardedValue(Expr *E) {
7152 // In C++11, discarded-value expressions of a certain form are special,
7153 // according to [expr]p10:
7154 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7155 // expression is an lvalue of volatile-qualified type and it has
7156 // one of the following forms:
7157 E = E->IgnoreParens();
7158
Eli Friedmanc49c2262012-05-24 22:36:31 +00007159 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007160 if (isa<DeclRefExpr>(E))
7161 return true;
7162
Eli Friedmanc49c2262012-05-24 22:36:31 +00007163 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007164 if (isa<ArraySubscriptExpr>(E))
7165 return true;
7166
Eli Friedmanc49c2262012-05-24 22:36:31 +00007167 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007168 if (isa<MemberExpr>(E))
7169 return true;
7170
Eli Friedmanc49c2262012-05-24 22:36:31 +00007171 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007172 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7173 if (UO->getOpcode() == UO_Deref)
7174 return true;
7175
7176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007177 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007178 if (BO->isPtrMemOp())
7179 return true;
7180
Eli Friedmanc49c2262012-05-24 22:36:31 +00007181 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007182 if (BO->getOpcode() == BO_Comma)
7183 return IsSpecialDiscardedValue(BO->getRHS());
7184 }
7185
Eli Friedmanc49c2262012-05-24 22:36:31 +00007186 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007187 // operands are one of the above, or
7188 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7189 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7190 IsSpecialDiscardedValue(CO->getFalseExpr());
7191 // The related edge case of "*x ?: *x".
7192 if (BinaryConditionalOperator *BCO =
7193 dyn_cast<BinaryConditionalOperator>(E)) {
7194 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7195 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7196 IsSpecialDiscardedValue(BCO->getFalseExpr());
7197 }
7198
7199 // Objective-C++ extensions to the rule.
7200 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7201 return true;
7202
7203 return false;
7204}
7205
John McCall34376a62010-12-04 03:47:34 +00007206/// Perform the conversions required for an expression used in a
7207/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007208ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007209 if (E->hasPlaceholderType()) {
7210 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007211 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007212 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007213 }
7214
John McCallfee942d2010-12-02 02:07:15 +00007215 // C99 6.3.2.1:
7216 // [Except in specific positions,] an lvalue that does not have
7217 // array type is converted to the value stored in the
7218 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007219 if (E->isRValue()) {
7220 // In C, function designators (i.e. expressions of function type)
7221 // are r-values, but we still want to do function-to-pointer decay
7222 // on them. This is both technically correct and convenient for
7223 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007224 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007225 return DefaultFunctionArrayConversion(E);
7226
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007227 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007228 }
John McCallfee942d2010-12-02 02:07:15 +00007229
Eli Friedmanf798f652012-05-24 22:04:19 +00007230 if (getLangOpts().CPlusPlus) {
7231 // The C++11 standard defines the notion of a discarded-value expression;
7232 // normally, we don't need to do anything to handle it, but if it is a
7233 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7234 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007235 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007236 E->getType().isVolatileQualified() &&
7237 IsSpecialDiscardedValue(E)) {
7238 ExprResult Res = DefaultLvalueConversion(E);
7239 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007240 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007241 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007242 }
Richard Smith122f88d2016-12-06 23:52:28 +00007243
7244 // C++1z:
7245 // If the expression is a prvalue after this optional conversion, the
7246 // temporary materialization conversion is applied.
7247 //
7248 // We skip this step: IR generation is able to synthesize the storage for
7249 // itself in the aggregate case, and adding the extra node to the AST is
7250 // just clutter.
7251 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7252 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007253 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007254 }
John McCall34376a62010-12-04 03:47:34 +00007255
7256 // GCC seems to also exclude expressions of incomplete enum type.
7257 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7258 if (!T->getDecl()->isComplete()) {
7259 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007260 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007261 return E;
John McCall34376a62010-12-04 03:47:34 +00007262 }
7263 }
7264
John Wiegley01296292011-04-08 18:41:53 +00007265 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7266 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007267 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007268 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007269
John McCallca61b652010-12-04 12:29:11 +00007270 if (!E->getType()->isVoidType())
7271 RequireCompleteType(E->getExprLoc(), E->getType(),
7272 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007273 return E;
John McCall34376a62010-12-04 03:47:34 +00007274}
7275
Faisal Valia17d19f2013-11-07 05:17:06 +00007276// If we can unambiguously determine whether Var can never be used
7277// in a constant expression, return true.
7278// - if the variable and its initializer are non-dependent, then
7279// we can unambiguously check if the variable is a constant expression.
7280// - if the initializer is not value dependent - we can determine whether
7281// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007282// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007283// never be a constant expression.
7284// - FXIME: if the initializer is dependent, we can still do some analysis and
7285// identify certain cases unambiguously as non-const by using a Visitor:
7286// - such as those that involve odr-use of a ParmVarDecl, involve a new
7287// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007288static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007289 ASTContext &Context) {
7290 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007291 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007292
7293 // If there is no initializer - this can not be a constant expression.
7294 if (!Var->getAnyInitializer(DefVD)) return true;
7295 assert(DefVD);
7296 if (DefVD->isWeak()) return false;
7297 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007298
Faisal Valia17d19f2013-11-07 05:17:06 +00007299 Expr *Init = cast<Expr>(Eval->Value);
7300
7301 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007302 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7303 // of value-dependent expressions, and use it here to determine whether the
7304 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007305 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007306 }
7307
Simon Pilgrim75c26882016-09-30 14:25:09 +00007308 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007309}
7310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007311/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007312/// that must be captured by any of its enclosing lambdas that are ready to
7313/// capture. If there is a lambda that can capture a nested
7314/// potential-capture, go ahead and do so. Also, check to see if any
7315/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007316/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007317
Faisal Valiab3d6462013-12-07 20:22:44 +00007318static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7319 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7320
Simon Pilgrim75c26882016-09-30 14:25:09 +00007321 assert(!S.isUnevaluatedContext());
7322 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007323#ifndef NDEBUG
7324 DeclContext *DC = S.CurContext;
7325 while (DC && isa<CapturedDecl>(DC))
7326 DC = DC->getParent();
7327 assert(
7328 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007329 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007330#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007331
7332 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7333
Faisal Valiab3d6462013-12-07 20:22:44 +00007334 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007335 // lambda (within a generic outer lambda), must be captured by an
7336 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007337 const unsigned NumPotentialCaptures =
7338 CurrentLSI->getNumPotentialVariableCaptures();
7339 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007340 Expr *VarExpr = nullptr;
7341 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007342 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007343 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007344 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007345 // need to check enclosing lambda's for speculative captures.
7346 // For e.g.:
7347 // Even though 'x' is not odr-used, it should be captured.
7348 // int test() {
7349 // const int x = 10;
7350 // auto L = [=](auto a) {
7351 // (void) +x + a;
7352 // };
7353 // }
7354 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007355 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007356 continue;
7357
7358 // If we have a capture-capable lambda for the variable, go ahead and
7359 // capture the variable in that lambda (and all its enclosing lambdas).
7360 if (const Optional<unsigned> Index =
7361 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007362 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007363 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7364 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7365 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007366 }
7367 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007368 VariableCanNeverBeAConstantExpression(Var, S.Context);
7369 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7370 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007371 // can not be used in a constant expression - which means
7372 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007373 // capture violation early, if the variable is un-captureable.
7374 // This is purely for diagnosing errors early. Otherwise, this
7375 // error would get diagnosed when the lambda becomes capture ready.
7376 QualType CaptureType, DeclRefType;
7377 SourceLocation ExprLoc = VarExpr->getExprLoc();
7378 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007379 /*EllipsisLoc*/ SourceLocation(),
7380 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007381 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007382 // We will never be able to capture this variable, and we need
7383 // to be able to in any and all instantiations, so diagnose it.
7384 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007385 /*EllipsisLoc*/ SourceLocation(),
7386 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007387 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007388 }
7389 }
7390 }
7391
Faisal Valiab3d6462013-12-07 20:22:44 +00007392 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007393 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007394 // If we have a capture-capable lambda for 'this', go ahead and capture
7395 // 'this' in that lambda (and all its enclosing lambdas).
7396 if (const Optional<unsigned> Index =
7397 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007398 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007399 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7400 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7401 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7402 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007403 }
7404 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007405
7406 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007407 CurrentLSI->clearPotentialCaptures();
7408}
7409
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007410static ExprResult attemptRecovery(Sema &SemaRef,
7411 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007412 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007413 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7414 Consumer.getLookupResult().getLookupKind());
7415 const CXXScopeSpec *SS = Consumer.getSS();
7416 CXXScopeSpec NewSS;
7417
7418 // Use an approprate CXXScopeSpec for building the expr.
7419 if (auto *NNS = TC.getCorrectionSpecifier())
7420 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7421 else if (SS && !TC.WillReplaceSpecifier())
7422 NewSS = *SS;
7423
Richard Smithde6d6c42015-12-29 19:43:10 +00007424 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007425 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007426 R.addDecl(ND);
7427 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007428 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007429 CXXRecordDecl *Record = nullptr;
7430 if (auto *NNS = TC.getCorrectionSpecifier())
7431 Record = NNS->getAsType()->getAsCXXRecordDecl();
7432 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007433 Record =
7434 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7435 if (Record)
7436 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007437
7438 // Detect and handle the case where the decl might be an implicit
7439 // member.
7440 bool MightBeImplicitMember;
7441 if (!Consumer.isAddressOfOperand())
7442 MightBeImplicitMember = true;
7443 else if (!NewSS.isEmpty())
7444 MightBeImplicitMember = false;
7445 else if (R.isOverloadedResult())
7446 MightBeImplicitMember = false;
7447 else if (R.isUnresolvableResult())
7448 MightBeImplicitMember = true;
7449 else
7450 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7451 isa<IndirectFieldDecl>(ND) ||
7452 isa<MSPropertyDecl>(ND);
7453
7454 if (MightBeImplicitMember)
7455 return SemaRef.BuildPossibleImplicitMemberExpr(
7456 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007457 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007458 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7459 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7460 Ivar->getIdentifier());
7461 }
7462 }
7463
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007464 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7465 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007466}
7467
Kaelyn Takata6c759512014-10-27 18:07:37 +00007468namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007469class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7470 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7471
7472public:
7473 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7474 : TypoExprs(TypoExprs) {}
7475 bool VisitTypoExpr(TypoExpr *TE) {
7476 TypoExprs.insert(TE);
7477 return true;
7478 }
7479};
7480
Kaelyn Takata6c759512014-10-27 18:07:37 +00007481class TransformTypos : public TreeTransform<TransformTypos> {
7482 typedef TreeTransform<TransformTypos> BaseTransform;
7483
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007484 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7485 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007486 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007487 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007488 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007489 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007490
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007491 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007492 /// If the TypoExprs were successfully corrected, then the diagnostics should
7493 /// suggest the corrections. Otherwise the diagnostics will not suggest
7494 /// anything (having been passed an empty TypoCorrection).
7495 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007496 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007497 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007498 if (State.DiagHandler) {
7499 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7500 ExprResult Replacement = TransformCache[TE];
7501
7502 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7503 // TypoCorrection, replacing the existing decls. This ensures the right
7504 // NamedDecl is used in diagnostics e.g. in the case where overload
7505 // resolution was used to select one from several possible decls that
7506 // had been stored in the TypoCorrection.
7507 if (auto *ND = getDeclFromExpr(
7508 Replacement.isInvalid() ? nullptr : Replacement.get()))
7509 TC.setCorrectionDecl(ND);
7510
7511 State.DiagHandler(TC);
7512 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007513 SemaRef.clearDelayedTypo(TE);
7514 }
7515 }
7516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007517 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007518 /// given combination of the other TypoExprs, retry those corrections against
7519 /// the next combination of substitutions for the other TypoExprs by advancing
7520 /// to the next potential correction of the second TypoExpr. For the second
7521 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7522 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7523 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7524 /// TransformCache). Returns true if there is still any untried combinations
7525 /// of corrections.
7526 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7527 for (auto TE : TypoExprs) {
7528 auto &State = SemaRef.getTypoExprState(TE);
7529 TransformCache.erase(TE);
7530 if (!State.Consumer->finished())
7531 return true;
7532 State.Consumer->resetCorrectionStream();
7533 }
7534 return false;
7535 }
7536
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007537 NamedDecl *getDeclFromExpr(Expr *E) {
7538 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7539 E = OverloadResolution[OE];
7540
7541 if (!E)
7542 return nullptr;
7543 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007544 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007545 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007546 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007547 // FIXME: Add any other expr types that could be be seen by the delayed typo
7548 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007549 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007550 return nullptr;
7551 }
7552
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007553 ExprResult TryTransform(Expr *E) {
7554 Sema::SFINAETrap Trap(SemaRef);
7555 ExprResult Res = TransformExpr(E);
7556 if (Trap.hasErrorOccurred() || Res.isInvalid())
7557 return ExprError();
7558
7559 return ExprFilter(Res.get());
7560 }
7561
Kaelyn Takata6c759512014-10-27 18:07:37 +00007562public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007563 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7564 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007565
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007566 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7567 MultiExprArg Args,
7568 SourceLocation RParenLoc,
7569 Expr *ExecConfig = nullptr) {
7570 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7571 RParenLoc, ExecConfig);
7572 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007573 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007574 Expr *ResultCall = Result.get();
7575 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7576 ResultCall = BE->getSubExpr();
7577 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7578 OverloadResolution[OE] = CE->getCallee();
7579 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007580 }
7581 return Result;
7582 }
7583
Kaelyn Takata6c759512014-10-27 18:07:37 +00007584 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7585
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007586 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7587
Kaelyn Takata6c759512014-10-27 18:07:37 +00007588 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007589 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007590 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007591 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007592
Kaelyn Takata6c759512014-10-27 18:07:37 +00007593 // Exit if either the transform was valid or if there were no TypoExprs
7594 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007595 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007596 !CheckAndAdvanceTypoExprCorrectionStreams())
7597 break;
7598 }
7599
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007600 // Ensure none of the TypoExprs have multiple typo correction candidates
7601 // with the same edit length that pass all the checks and filters.
7602 // TODO: Properly handle various permutations of possible corrections when
7603 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007604 // Also, disable typo correction while attempting the transform when
7605 // handling potentially ambiguous typo corrections as any new TypoExprs will
7606 // have been introduced by the application of one of the correction
7607 // candidates and add little to no value if corrected.
7608 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007609 while (!AmbiguousTypoExprs.empty()) {
7610 auto TE = AmbiguousTypoExprs.back();
7611 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007612 auto &State = SemaRef.getTypoExprState(TE);
7613 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007614 TransformCache.erase(TE);
7615 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007616 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007617 TransformCache.erase(TE);
7618 Res = ExprError();
7619 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007620 }
7621 AmbiguousTypoExprs.remove(TE);
7622 State.Consumer->restoreSavedPosition();
7623 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007624 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007625 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007626
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007627 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007628 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007629 FindTypoExprs(TypoExprs).TraverseStmt(E);
7630
Kaelyn Takata6c759512014-10-27 18:07:37 +00007631 EmitAllDiagnostics();
7632
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007633 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007634 }
7635
7636 ExprResult TransformTypoExpr(TypoExpr *E) {
7637 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7638 // cached transformation result if there is one and the TypoExpr isn't the
7639 // first one that was encountered.
7640 auto &CacheEntry = TransformCache[E];
7641 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7642 return CacheEntry;
7643 }
7644
7645 auto &State = SemaRef.getTypoExprState(E);
7646 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7647
7648 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7649 // typo correction and return it.
7650 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007651 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007652 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007653 // FIXME: If we would typo-correct to an invalid declaration, it's
7654 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007655 ExprResult NE = State.RecoveryHandler ?
7656 State.RecoveryHandler(SemaRef, E, TC) :
7657 attemptRecovery(SemaRef, *State.Consumer, TC);
7658 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007659 // Check whether there may be a second viable correction with the same
7660 // edit distance; if so, remember this TypoExpr may have an ambiguous
7661 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007662 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007663 if ((Next = State.Consumer->peekNextCorrection()) &&
7664 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7665 AmbiguousTypoExprs.insert(E);
7666 } else {
7667 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007668 }
7669 assert(!NE.isUnset() &&
7670 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007671 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007672 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007673 }
7674 return CacheEntry = ExprError();
7675 }
7676};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007677}
Faisal Valia17d19f2013-11-07 05:17:06 +00007678
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007679ExprResult
7680Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7681 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007682 // If the current evaluation context indicates there are uncorrected typos
7683 // and the current expression isn't guaranteed to not have typos, try to
7684 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007685 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007686 (E->isTypeDependent() || E->isValueDependent() ||
7687 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007688 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7689 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7690 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007691 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007692 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007693 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007694 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007695 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007696 ExprEvalContexts.back().NumTypos -= TyposResolved;
7697 return Result;
7698 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007699 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007700 }
7701 return E;
7702}
7703
Richard Smith945f8d32013-01-14 22:39:08 +00007704ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007705 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007706 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007707 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007708 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007709
7710 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007711 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007712
7713 // If we are an init-expression in a lambdas init-capture, we should not
7714 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007715 // containing full-expression is done).
7716 // template<class ... Ts> void test(Ts ... t) {
7717 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7718 // return a;
7719 // }() ...);
7720 // }
7721 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7722 // when we parse the lambda introducer, and teach capturing (but not
7723 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7724 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7725 // lambda where we've entered the introducer but not the body, or represent a
7726 // lambda where we've entered the body, depending on where the
7727 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007728 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007729 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007730 return ExprError();
7731
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007732 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007733 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007734 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007735 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007736 if (FullExpr.isInvalid())
7737 return ExprError();
7738 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007739
Richard Smith945f8d32013-01-14 22:39:08 +00007740 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007741 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007742 if (FullExpr.isInvalid())
7743 return ExprError();
7744
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007745 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007746 if (FullExpr.isInvalid())
7747 return ExprError();
7748 }
John Wiegley01296292011-04-08 18:41:53 +00007749
Kaelyn Takata49d84322014-11-11 23:26:56 +00007750 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7751 if (FullExpr.isInvalid())
7752 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007753
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007754 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007755
Simon Pilgrim75c26882016-09-30 14:25:09 +00007756 // At the end of this full expression (which could be a deeply nested
7757 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007758 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007759 // Consider the following code:
7760 // void f(int, int);
7761 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007762 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007763 // const int x = 10, y = 20;
7764 // auto L = [=](auto a) {
7765 // auto M = [=](auto b) {
7766 // f(x, b); <-- requires x to be captured by L and M
7767 // f(y, a); <-- requires y to be captured by L, but not all Ms
7768 // };
7769 // };
7770 // }
7771
Simon Pilgrim75c26882016-09-30 14:25:09 +00007772 // FIXME: Also consider what happens for something like this that involves
7773 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007774 // void f() {
7775 // const int n = 0;
7776 // auto L = [&](auto a) {
7777 // +n + ({ 0; a; });
7778 // };
7779 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007780 //
7781 // Here, we see +n, and then the full-expression 0; ends, so we don't
7782 // capture n (and instead remove it from our list of potential captures),
7783 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007784 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007785
Alexey Bataev31939e32016-11-11 12:36:20 +00007786 LambdaScopeInfo *const CurrentLSI =
7787 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007788 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007789 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007790 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007791 // By ensuring we are in the context of a lambda's call operator
7792 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007793 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007794 // PR, a proper fix would entail :
7795 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007796 // - Add to Sema an integer holding the smallest (outermost) scope
7797 // index that we are *lexically* within, and save/restore/set to
7798 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007799 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007800 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007801 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007802 DeclContext *DC = CurContext;
7803 while (DC && isa<CapturedDecl>(DC))
7804 DC = DC->getParent();
7805 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007806 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007807 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007808 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7809 *this);
John McCall5d413782010-12-06 08:20:24 +00007810 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007811}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007812
7813StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7814 if (!FullStmt) return StmtError();
7815
John McCall5d413782010-12-06 08:20:24 +00007816 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007817}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007818
Simon Pilgrim75c26882016-09-30 14:25:09 +00007819Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007820Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7821 CXXScopeSpec &SS,
7822 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007823 DeclarationName TargetName = TargetNameInfo.getName();
7824 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007825 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007826
Douglas Gregor43edb322011-10-24 22:31:10 +00007827 // If the name itself is dependent, then the result is dependent.
7828 if (TargetName.isDependentName())
7829 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007830
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007831 // Do the redeclaration lookup in the current scope.
7832 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7833 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007834 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007835 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007836
Douglas Gregor43edb322011-10-24 22:31:10 +00007837 switch (R.getResultKind()) {
7838 case LookupResult::Found:
7839 case LookupResult::FoundOverloaded:
7840 case LookupResult::FoundUnresolvedValue:
7841 case LookupResult::Ambiguous:
7842 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007843
Douglas Gregor43edb322011-10-24 22:31:10 +00007844 case LookupResult::NotFound:
7845 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007846
Douglas Gregor43edb322011-10-24 22:31:10 +00007847 case LookupResult::NotFoundInCurrentInstantiation:
7848 return IER_Dependent;
7849 }
David Blaikie8a40f702012-01-17 06:56:22 +00007850
7851 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007852}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007853
Simon Pilgrim75c26882016-09-30 14:25:09 +00007854Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007855Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7856 bool IsIfExists, CXXScopeSpec &SS,
7857 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007858 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007859
Richard Smith151c4562016-12-20 21:35:28 +00007860 // Check for an unexpanded parameter pack.
7861 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7862 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7863 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007864 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007865
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007866 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7867}