blob: 8f882e4ca32f0b3bb4014c81398db7b2b63c57f4 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner29375652006-12-04 18:06:35 +00006//
7//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00008///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000011///
12//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000013
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000015#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000023#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000026#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000045/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
Richard Smith715ee072018-06-20 21:58:20 +000082ParsedType Sema::getConstructorName(IdentifierInfo &II,
83 SourceLocation NameLoc,
Richard Smith69bc9aa2018-06-22 19:50:19 +000084 Scope *S, CXXScopeSpec &SS,
85 bool EnteringContext) {
Richard Smith715ee072018-06-20 21:58:20 +000086 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
87 assert(CurClass && &II == CurClass->getIdentifier() &&
88 "not a constructor name");
89
Richard Smith69bc9aa2018-06-22 19:50:19 +000090 // When naming a constructor as a member of a dependent context (eg, in a
91 // friend declaration or an inherited constructor declaration), form an
92 // unresolved "typename" type.
Gauthier Harnischef629c72019-06-14 08:25:52 +000093 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
Richard Smith69bc9aa2018-06-22 19:50:19 +000094 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
95 return ParsedType::make(T);
96 }
97
Richard Smith715ee072018-06-20 21:58:20 +000098 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
99 return ParsedType();
100
101 // Find the injected-class-name declaration. Note that we make no attempt to
102 // diagnose cases where the injected-class-name is shadowed: the only
103 // declaration that can validly shadow the injected-class-name is a
104 // non-static data member, and if the class contains both a non-static data
105 // member and a constructor then it is ill-formed (we check that in
106 // CheckCompletedCXXClass).
107 CXXRecordDecl *InjectedClassName = nullptr;
108 for (NamedDecl *ND : CurClass->lookup(&II)) {
109 auto *RD = dyn_cast<CXXRecordDecl>(ND);
110 if (RD && RD->isInjectedClassName()) {
111 InjectedClassName = RD;
112 break;
113 }
114 }
Richard Smith2e34bbd2018-08-08 00:42:42 +0000115 if (!InjectedClassName) {
116 if (!CurClass->isInvalidDecl()) {
117 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
118 // properly. Work around it here for now.
119 Diag(SS.getLastQualifierNameLoc(),
120 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
121 }
Ilya Biryukova2d58252018-07-04 08:50:12 +0000122 return ParsedType();
Richard Smith2e34bbd2018-08-08 00:42:42 +0000123 }
Richard Smith715ee072018-06-20 21:58:20 +0000124
125 QualType T = Context.getTypeDeclType(InjectedClassName);
126 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
127 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
128
129 return ParsedType::make(T);
130}
131
John McCallba7bf592010-08-24 05:47:05 +0000132ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000133 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000134 SourceLocation NameLoc,
135 Scope *S, CXXScopeSpec &SS,
136 ParsedType ObjectTypePtr,
137 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 // Determine where to perform name lookup.
139
140 // FIXME: This area of the standard is very messy, and the current
141 // wording is rather unclear about which scopes we search for the
142 // destructor name; see core issues 399 and 555. Issue 399 in
143 // particular shows where the current description of destructor name
144 // lookup is completely out of line with existing practice, e.g.,
145 // this appears to be ill-formed:
146 //
147 // namespace N {
148 // template <typename T> struct S {
149 // ~S();
150 // };
151 // }
152 //
153 // void f(N::S<int>* s) {
154 // s->N::S<int>::~S();
155 // }
156 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000158 // For this reason, we're currently only doing the C++03 version of this
159 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000161 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000162 bool isDependent = false;
163 bool LookInScope = false;
164
Richard Smith64e033f2015-01-15 00:48:52 +0000165 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000166 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000167
Douglas Gregorfe17d252010-02-16 19:09:40 +0000168 // If we have an object type, it's because we are in a
169 // pseudo-destructor-expression or a member access expression, and
170 // we know what type we're looking for.
171 if (ObjectTypePtr)
172 SearchType = GetTypeFromParser(ObjectTypePtr);
173
174 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000175 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176
Douglas Gregor46841e12010-02-23 00:15:22 +0000177 bool AlreadySearched = false;
178 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000179 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000181 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000182 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000183 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000184 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000185 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000186 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000187 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000188 // Here, we determine whether the code below is permitted to look at the
189 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000190 DeclContext *DC = computeDeclContext(SS, EnteringContext);
191 if (DC && DC->isFileContext()) {
192 AlreadySearched = true;
193 LookupCtx = DC;
194 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000195 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000196 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000197 LookInScope = true;
198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000199
Sebastian Redla771d222010-07-07 23:17:38 +0000200 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000201 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000202 if (AlreadySearched) {
203 // Nothing left to do.
204 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
205 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000206 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000207 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
208 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000209 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210 LookupCtx = computeDeclContext(SearchType);
211 isDependent = SearchType->isDependentType();
212 } else {
213 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000214 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000215 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000216 } else if (ObjectTypePtr) {
217 // C++ [basic.lookup.classref]p3:
218 // If the unqualified-id is ~type-name, the type-name is looked up
219 // in the context of the entire postfix-expression. If the type T
220 // of the object expression is of a class type C, the type-name is
221 // also looked up in the scope of class C. At least one of the
222 // lookups shall find a name that refers to (possibly
223 // cv-qualified) T.
224 LookupCtx = computeDeclContext(SearchType);
225 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000226 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000227 "Caller should have completed object type");
228
229 LookInScope = true;
230 } else {
231 // Perform lookup into the current scope (only).
232 LookInScope = true;
233 }
234
Craig Topperc3ec1492014-05-26 06:22:03 +0000235 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000236 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
237 for (unsigned Step = 0; Step != 2; ++Step) {
238 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000239 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000240 // we're allowed to look there).
241 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000242 if (Step == 0 && LookupCtx) {
243 if (RequireCompleteDeclContext(SS, LookupCtx))
244 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000245 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000246 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000247 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000248 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000249 continue;
John McCallcb731542017-06-11 20:33:00 +0000250 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251
252 // FIXME: Should we be suppressing ambiguities here?
253 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000254 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000255
256 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
257 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000258 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000259
260 if (SearchType.isNull() || SearchType->isDependentType() ||
261 Context.hasSameUnqualifiedType(T, SearchType)) {
262 // We found our type!
263
Richard Smithc278c002014-01-22 00:30:17 +0000264 return CreateParsedType(T,
265 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000266 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000267
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000268 if (!SearchType.isNull())
269 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000270 }
271
272 // If the name that we found is a class template name, and it is
273 // the same name as the template name in the last part of the
274 // nested-name-specifier (if present) or the object type, then
275 // this is the destructor for that class.
276 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000278 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
279 QualType MemberOfType;
280 if (SS.isSet()) {
281 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
282 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000283 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
284 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285 }
286 }
287 if (MemberOfType.isNull())
288 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289
Douglas Gregorfe17d252010-02-16 19:09:40 +0000290 if (MemberOfType.isNull())
291 continue;
292
293 // We're referring into a class template specialization. If the
294 // class template we found is the same as the template being
295 // specialized, we found what we are looking for.
296 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
297 if (ClassTemplateSpecializationDecl *Spec
298 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
299 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
300 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000301 return CreateParsedType(
302 MemberOfType,
303 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000304 }
305
306 continue;
307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308
Douglas Gregorfe17d252010-02-16 19:09:40 +0000309 // We're referring to an unresolved class template
310 // specialization. Determine whether we class template we found
311 // is the same as the template being specialized or, if we don't
312 // know which template is being specialized, that it at least
313 // has the same name.
314 if (const TemplateSpecializationType *SpecType
315 = MemberOfType->getAs<TemplateSpecializationType>()) {
316 TemplateName SpecName = SpecType->getTemplateName();
317
318 // The class template we found is the same template being
319 // specialized.
320 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
321 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000322 return CreateParsedType(
323 MemberOfType,
324 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000325
326 continue;
327 }
328
329 // The class template we found has the same name as the
330 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000332 = SpecName.getAsDependentTemplateName()) {
333 if (DepTemplate->isIdentifier() &&
334 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000335 return CreateParsedType(
336 MemberOfType,
337 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000338
339 continue;
340 }
341 }
342 }
343 }
344
345 if (isDependent) {
346 // We didn't find our type, but that's okay: it's dependent
347 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000348
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000349 // FIXME: What if we have no nested-name-specifier?
350 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
351 SS.getWithLocInContext(Context),
352 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000353 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000354 }
355
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000356 if (NonMatchingTypeDecl) {
357 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
358 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
359 << T << SearchType;
360 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
361 << T;
362 } else if (ObjectTypePtr)
363 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000365 else {
366 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
367 diag::err_destructor_class_name);
368 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000369 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000370 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
371 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
372 Class->getNameAsString());
373 }
374 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000375
David Blaikieefdccaa2016-01-15 23:43:34 +0000376 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000377}
378
Richard Smithef2cd8f2017-02-08 20:39:08 +0000379ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
380 ParsedType ObjectType) {
381 if (DS.getTypeSpecType() == DeclSpec::TST_error)
382 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000383
Richard Smithef2cd8f2017-02-08 20:39:08 +0000384 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
385 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
386 return nullptr;
387 }
388
389 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
390 "unexpected type in getDestructorType");
391 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
392
393 // If we know the type of the object, check that the correct destructor
394 // type was named now; we can give better diagnostics this way.
395 QualType SearchType = GetTypeFromParser(ObjectType);
396 if (!SearchType.isNull() && !SearchType->isDependentType() &&
397 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000398 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
399 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000400 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000401 }
402
403 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000404}
405
Richard Smithd091dc12013-12-05 00:58:33 +0000406bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
407 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000408 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000409
410 if (!SS.isValid())
411 return false;
412
413 switch (SS.getScopeRep()->getKind()) {
414 case NestedNameSpecifier::Identifier:
415 case NestedNameSpecifier::TypeSpec:
416 case NestedNameSpecifier::TypeSpecWithTemplate:
417 // Per C++11 [over.literal]p2, literal operators can only be declared at
418 // namespace scope. Therefore, this unqualified-id cannot name anything.
419 // Reject it early, because we have no AST representation for this in the
420 // case where the scope is dependent.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000421 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
422 << SS.getScopeRep();
Richard Smithd091dc12013-12-05 00:58:33 +0000423 return true;
424
425 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000426 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000427 case NestedNameSpecifier::Namespace:
428 case NestedNameSpecifier::NamespaceAlias:
429 return false;
430 }
431
432 llvm_unreachable("unknown nested name specifier kind");
433}
434
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000436ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000437 SourceLocation TypeidLoc,
438 TypeSourceInfo *Operand,
439 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000440 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000442 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000443 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000444 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000445 Qualifiers Quals;
446 QualType T
447 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
448 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000449 if (T->getAs<RecordType>() &&
450 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
451 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452
David Majnemer6f3150a2014-11-21 21:09:12 +0000453 if (T->isVariablyModifiedType())
454 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
455
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000456 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
457 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000458}
459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000460/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000462 SourceLocation TypeidLoc,
463 Expr *E,
464 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000465 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000466 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000467 if (E->getType()->isPlaceholderType()) {
468 ExprResult result = CheckPlaceholderExpr(E);
469 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000470 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000471 }
472
Douglas Gregor9da64192010-04-26 22:37:10 +0000473 QualType T = E->getType();
474 if (const RecordType *RecordT = T->getAs<RecordType>()) {
475 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
476 // C++ [expr.typeid]p3:
477 // [...] If the type of the expression is a class type, the class
478 // shall be completely-defined.
479 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
480 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481
Douglas Gregor9da64192010-04-26 22:37:10 +0000482 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000483 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000484 // polymorphic class type [...] [the] expression is an unevaluated
485 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000486 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000487 // The subexpression is potentially evaluated; switch the context
488 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000489 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000490 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000491 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000492
493 // We require a vtable to query the type at run time.
494 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000495 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000496 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000498
Douglas Gregor9da64192010-04-26 22:37:10 +0000499 // C++ [expr.typeid]p4:
500 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 // cv-qualified type, the result of the typeid expression refers to a
502 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000503 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000504 Qualifiers Quals;
505 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
506 if (!Context.hasSameType(T, UnqualT)) {
507 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000508 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000509 }
510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
David Majnemer6f3150a2014-11-21 21:09:12 +0000512 if (E->getType()->isVariablyModifiedType())
513 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
514 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000515 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000516 E->HasSideEffects(Context, WasEvaluated)) {
517 // The expression operand for typeid is in an unevaluated expression
518 // context, so side effects could result in unintended consequences.
519 Diag(E->getExprLoc(), WasEvaluated
520 ? diag::warn_side_effects_typeid
521 : diag::warn_side_effects_unevaluated_context);
522 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000523
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000524 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
525 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000526}
527
528/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000529ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000530Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
531 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Anastasia Stulova46b55fa2019-07-18 10:02:35 +0000532 // typeid is not supported in OpenCL.
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000533 if (getLangOpts().OpenCLCPlusPlus) {
534 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
535 << "typeid");
536 }
537
Douglas Gregor9da64192010-04-26 22:37:10 +0000538 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000539 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000540 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000541
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000542 if (!CXXTypeInfoDecl) {
543 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
544 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
545 LookupQualifiedName(R, getStdNamespace());
546 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000547 // Microsoft's typeinfo doesn't have type_info in std but in the global
548 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000549 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000550 LookupQualifiedName(R, Context.getTranslationUnitDecl());
551 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
552 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000553 if (!CXXTypeInfoDecl)
554 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Nico Weber1b7f39d2012-05-20 01:27:21 +0000557 if (!getLangOpts().RTTI) {
558 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
559 }
560
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000561 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor9da64192010-04-26 22:37:10 +0000563 if (isType) {
564 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000565 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000566 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
567 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000568 if (T.isNull())
569 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Douglas Gregor9da64192010-04-26 22:37:10 +0000571 if (!TInfo)
572 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000573
Douglas Gregor9da64192010-04-26 22:37:10 +0000574 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000578 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000579}
580
David Majnemer1dbc7a72016-03-27 04:46:07 +0000581/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
582/// a single GUID.
583static void
584getUuidAttrOfType(Sema &SemaRef, QualType QT,
585 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
586 // Optionally remove one level of pointer, reference or array indirection.
587 const Type *Ty = QT.getTypePtr();
588 if (QT->isPointerType() || QT->isReferenceType())
589 Ty = QT->getPointeeType().getTypePtr();
590 else if (QT->isArrayType())
591 Ty = Ty->getBaseElementTypeUnsafe();
592
Reid Klecknere516eab2016-12-13 18:58:09 +0000593 const auto *TD = Ty->getAsTagDecl();
594 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000595 return;
596
Reid Klecknere516eab2016-12-13 18:58:09 +0000597 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000598 UuidAttrs.insert(Uuid);
599 return;
600 }
601
602 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000603 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000604 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
605 for (const TemplateArgument &TA : TAL.asArray()) {
606 const UuidAttr *UuidForTA = nullptr;
607 if (TA.getKind() == TemplateArgument::Type)
608 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
609 else if (TA.getKind() == TemplateArgument::Declaration)
610 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
611
612 if (UuidForTA)
613 UuidAttrs.insert(UuidForTA);
614 }
615 }
616}
617
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000618/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000619ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
620 SourceLocation TypeidLoc,
621 TypeSourceInfo *Operand,
622 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000623 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000624 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000625 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
626 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
627 if (UuidAttrs.empty())
628 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
629 if (UuidAttrs.size() > 1)
630 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000631 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
David Majnemer2041b462016-03-28 03:19:50 +0000634 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000635 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000636}
637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000638/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000639ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
640 SourceLocation TypeidLoc,
641 Expr *E,
642 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000643 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000644 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000645 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
646 UuidStr = "00000000-0000-0000-0000-000000000000";
647 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000648 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
649 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
650 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000651 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000652 if (UuidAttrs.size() > 1)
653 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000654 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000655 }
Francois Pichetb7577652010-12-27 01:32:00 +0000656 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000657
David Majnemer2041b462016-03-28 03:19:50 +0000658 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000659 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000660}
661
662/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
663ExprResult
664Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
665 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000667 if (!MSVCGuidDecl) {
668 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
669 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
670 LookupQualifiedName(R, Context.getTranslationUnitDecl());
671 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
672 if (!MSVCGuidDecl)
673 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674 }
675
Francois Pichet9f4f2072010-09-08 12:20:18 +0000676 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677
Francois Pichet9f4f2072010-09-08 12:20:18 +0000678 if (isType) {
679 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000680 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000681 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
682 &TInfo);
683 if (T.isNull())
684 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Francois Pichet9f4f2072010-09-08 12:20:18 +0000686 if (!TInfo)
687 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
688
689 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
690 }
691
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000693 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
694}
695
Steve Naroff66356bd2007-09-16 14:56:35 +0000696/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000697ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000698Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000699 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000700 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000701 return new (Context)
702 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000703}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000704
Sebastian Redl576fd422009-05-10 18:38:11 +0000705/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000706ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000707Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000708 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000709}
710
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000711/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000712ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000713Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
714 bool IsThrownVarInScope = false;
715 if (Ex) {
716 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000717 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000718 // copy/move construction of a class object [...]
719 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000720 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000721 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000722 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000723 // innermost enclosing try-block (if there is one), the copy/move
724 // operation from the operand to the exception object (15.1) can be
725 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000726 // exception object
727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
728 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
729 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
730 for( ; S; S = S->getParent()) {
731 if (S->isDeclScope(Var)) {
732 IsThrownVarInScope = true;
733 break;
734 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000735
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000736 if (S->getFlags() &
737 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
738 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
739 Scope::TryScope))
740 break;
741 }
742 }
743 }
744 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000745
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000746 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
747}
748
Simon Pilgrim75c26882016-09-30 14:25:09 +0000749ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000750 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000751 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000752 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +0000753 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +0000754 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +0000755 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexey Bataevc416e642019-02-08 18:02:25 +0000756 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000757
Justin Lebar2a8db342016-09-28 22:45:54 +0000758 // Exceptions aren't allowed in CUDA device code.
759 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000760 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
761 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000762
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000763 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
764 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
765
John Wiegley01296292011-04-08 18:41:53 +0000766 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000767 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
768 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000769 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000770
771 // Initialize the exception result. This implicitly weeds out
772 // abstract types or types with inaccessible copy constructors.
773
774 // C++0x [class.copymove]p31:
775 // When certain criteria are met, an implementation is allowed to omit the
776 // copy/move construction of a class object [...]
777 //
778 // - in a throw-expression, when the operand is the name of a
779 // non-volatile automatic object (other than a function or
780 // catch-clause
781 // parameter) whose scope does not extend beyond the end of the
782 // innermost enclosing try-block (if there is one), the copy/move
783 // operation from the operand to the exception object (15.1) can be
784 // omitted by constructing the automatic object directly into the
785 // exception object
786 const VarDecl *NRVOVariable = nullptr;
787 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000788 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000789
790 InitializedEntity Entity = InitializedEntity::InitializeException(
791 OpLoc, ExceptionObjectTy,
792 /*NRVO=*/NRVOVariable != nullptr);
793 ExprResult Res = PerformMoveOrCopyInitialization(
794 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
795 if (Res.isInvalid())
796 return ExprError();
797 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000798 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000799
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000800 return new (Context)
801 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802}
803
David Majnemere7a818f2015-03-06 18:53:55 +0000804static void
805collectPublicBases(CXXRecordDecl *RD,
806 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
807 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
808 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
809 bool ParentIsPublic) {
810 for (const CXXBaseSpecifier &BS : RD->bases()) {
811 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
812 bool NewSubobject;
813 // Virtual bases constitute the same subobject. Non-virtual bases are
814 // always distinct subobjects.
815 if (BS.isVirtual())
816 NewSubobject = VBases.insert(BaseDecl).second;
817 else
818 NewSubobject = true;
819
820 if (NewSubobject)
821 ++SubobjectsSeen[BaseDecl];
822
823 // Only add subobjects which have public access throughout the entire chain.
824 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
825 if (PublicPath)
826 PublicSubobjectsSeen.insert(BaseDecl);
827
828 // Recurse on to each base subobject.
829 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
830 PublicPath);
831 }
832}
833
834static void getUnambiguousPublicSubobjects(
835 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
836 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
837 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
838 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
839 SubobjectsSeen[RD] = 1;
840 PublicSubobjectsSeen.insert(RD);
841 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
842 /*ParentIsPublic=*/true);
843
844 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
845 // Skip ambiguous objects.
846 if (SubobjectsSeen[PublicSubobject] > 1)
847 continue;
848
849 Objects.push_back(PublicSubobject);
850 }
851}
852
Sebastian Redl4de47b42009-04-27 20:27:31 +0000853/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000854bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
855 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856 // If the type of the exception would be an incomplete type or a pointer
857 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000858 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000859 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000860 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000861 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000862 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000863 }
864 if (!isPointer || !Ty->isVoidType()) {
865 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000866 isPointer ? diag::err_throw_incomplete_ptr
867 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000868 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000869 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000870
David Majnemerd09a51c2015-03-03 01:50:05 +0000871 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000872 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000873 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000874 }
875
Eli Friedman91a3d272010-06-03 20:39:03 +0000876 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000877 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
878 if (!RD)
879 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000880
Douglas Gregor88d292c2010-05-13 16:44:06 +0000881 // If we are throwing a polymorphic class type or pointer thereof,
882 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000883 MarkVTableUsed(ThrowLoc, RD);
884
Eli Friedman36ebbec2010-10-12 20:32:36 +0000885 // If a pointer is thrown, the referenced object will not be destroyed.
886 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000887 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000888
Richard Smitheec915d62012-02-18 04:13:32 +0000889 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000890 if (!RD->hasIrrelevantDestructor()) {
891 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
892 MarkFunctionReferenced(E->getExprLoc(), Destructor);
893 CheckDestructorAccess(E->getExprLoc(), Destructor,
894 PDiag(diag::err_access_dtor_exception) << Ty);
895 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000896 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000897 }
898 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000899
David Majnemerdfa6d202015-03-11 18:36:39 +0000900 // The MSVC ABI creates a list of all types which can catch the exception
901 // object. This list also references the appropriate copy constructor to call
902 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000903 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000904 // We are only interested in the public, unambiguous bases contained within
905 // the exception object. Bases which are ambiguous or otherwise
906 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000907 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
908 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000909
David Majnemere7a818f2015-03-06 18:53:55 +0000910 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000911 // Attempt to lookup the copy constructor. Various pieces of machinery
912 // will spring into action, like template instantiation, which means this
913 // cannot be a simple walk of the class's decls. Instead, we must perform
914 // lookup and overload resolution.
915 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
916 if (!CD)
917 continue;
918
919 // Mark the constructor referenced as it is used by this throw expression.
920 MarkFunctionReferenced(E->getExprLoc(), CD);
921
922 // Skip this copy constructor if it is trivial, we don't need to record it
923 // in the catchable type data.
924 if (CD->isTrivial())
925 continue;
926
927 // The copy constructor is non-trivial, create a mapping from this class
928 // type to this constructor.
929 // N.B. The selection of copy constructor is not sensitive to this
930 // particular throw-site. Lookup will be performed at the catch-site to
931 // ensure that the copy constructor is, in fact, accessible (via
932 // friendship or any other means).
933 Context.addCopyConstructorForExceptionObject(Subobject, CD);
934
935 // We don't keep the instantiated default argument expressions around so
936 // we must rebuild them here.
937 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000938 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
939 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000940 }
941 }
942 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000943
Akira Hatanakac39a2432019-05-10 02:16:37 +0000944 // Under the Itanium C++ ABI, memory for the exception object is allocated by
945 // the runtime with no ability for the compiler to request additional
946 // alignment. Warn if the exception type requires alignment beyond the minimum
947 // guaranteed by the target C++ runtime.
948 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
949 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
950 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
951 if (ExnObjAlign < TypeAlign) {
952 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
953 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
954 << Ty << (unsigned)TypeAlign.getQuantity()
955 << (unsigned)ExnObjAlign.getQuantity();
956 }
957 }
958
David Majnemerba3e5ec2015-03-13 18:26:17 +0000959 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000960}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000961
Faisal Vali67b04462016-06-11 16:41:54 +0000962static QualType adjustCVQualifiersForCXXThisWithinLambda(
963 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
964 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
965
966 QualType ClassType = ThisTy->getPointeeType();
967 LambdaScopeInfo *CurLSI = nullptr;
968 DeclContext *CurDC = CurSemaContext;
969
970 // Iterate through the stack of lambdas starting from the innermost lambda to
971 // the outermost lambda, checking if '*this' is ever captured by copy - since
972 // that could change the cv-qualifiers of the '*this' object.
973 // The object referred to by '*this' starts out with the cv-qualifiers of its
974 // member function. We then start with the innermost lambda and iterate
975 // outward checking to see if any lambda performs a by-copy capture of '*this'
976 // - and if so, any nested lambda must respect the 'constness' of that
977 // capturing lamdbda's call operator.
978 //
979
Faisal Vali999f27e2017-05-02 20:56:34 +0000980 // Since the FunctionScopeInfo stack is representative of the lexical
981 // nesting of the lambda expressions during initial parsing (and is the best
982 // place for querying information about captures about lambdas that are
983 // partially processed) and perhaps during instantiation of function templates
984 // that contain lambda expressions that need to be transformed BUT not
985 // necessarily during instantiation of a nested generic lambda's function call
986 // operator (which might even be instantiated at the end of the TU) - at which
987 // time the DeclContext tree is mature enough to query capture information
988 // reliably - we use a two pronged approach to walk through all the lexically
989 // enclosing lambda expressions:
990 //
991 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
992 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
993 // enclosed by the call-operator of the LSI below it on the stack (while
994 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
995 // the stack represents the innermost lambda.
996 //
997 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
998 // represents a lambda's call operator. If it does, we must be instantiating
999 // a generic lambda's call operator (represented by the Current LSI, and
1000 // should be the only scenario where an inconsistency between the LSI and the
1001 // DeclContext should occur), so climb out the DeclContexts if they
1002 // represent lambdas, while querying the corresponding closure types
1003 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +00001004
Faisal Vali999f27e2017-05-02 20:56:34 +00001005 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +00001006 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +00001007 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1008 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1009 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +00001010 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1011 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001012
1013 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001014 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001015
Faisal Vali67b04462016-06-11 16:41:54 +00001016 auto C = CurLSI->getCXXThisCapture();
1017
1018 if (C.isCopyCapture()) {
1019 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1020 if (CurLSI->CallOperator->isConst())
1021 ClassType.addConst();
1022 return ASTCtx.getPointerType(ClassType);
1023 }
1024 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001025
1026 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1027 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001028 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001029 assert(CurLSI && "While computing 'this' capture-type for a generic "
1030 "lambda, we must have a corresponding LambdaScopeInfo");
1031 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1032 "While computing 'this' capture-type for a generic lambda, when we "
1033 "run out of enclosing LSI's, yet the enclosing DC is a "
1034 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1035 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001036 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001037
Faisal Vali67b04462016-06-11 16:41:54 +00001038 auto IsThisCaptured =
1039 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1040 IsConst = false;
1041 IsByCopy = false;
1042 for (auto &&C : Closure->captures()) {
1043 if (C.capturesThis()) {
1044 if (C.getCaptureKind() == LCK_StarThis)
1045 IsByCopy = true;
1046 if (Closure->getLambdaCallOperator()->isConst())
1047 IsConst = true;
1048 return true;
1049 }
1050 }
1051 return false;
1052 };
1053
1054 bool IsByCopyCapture = false;
1055 bool IsConstCapture = false;
1056 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1057 while (Closure &&
1058 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1059 if (IsByCopyCapture) {
1060 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1061 if (IsConstCapture)
1062 ClassType.addConst();
1063 return ASTCtx.getPointerType(ClassType);
1064 }
1065 Closure = isLambdaCallOperator(Closure->getParent())
1066 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1067 : nullptr;
1068 }
1069 }
1070 return ASTCtx.getPointerType(ClassType);
1071}
1072
Eli Friedman73a04092012-01-07 04:59:52 +00001073QualType Sema::getCurrentThisType() {
1074 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001075 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001076
Richard Smith938f40b2011-06-11 17:19:42 +00001077 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1078 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001079 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001080 }
Faisal Validc6b5962016-03-21 09:25:37 +00001081
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001082 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001083 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001084
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001085 assert(isa<CXXRecordDecl>(DC) &&
1086 "Trying to get 'this' type from static method?");
1087
1088 // This is a lambda call operator that is being instantiated as a default
1089 // initializer. DC must point to the enclosing class type, so we can recover
1090 // the 'this' type from it.
1091
1092 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1093 // There are no cv-qualifiers for 'this' within default initializers,
1094 // per [expr.prim.general]p4.
1095 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001096 }
Faisal Vali67b04462016-06-11 16:41:54 +00001097
1098 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1099 // might need to be adjusted if the lambda or any of its enclosing lambda's
1100 // captures '*this' by copy.
1101 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1102 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1103 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001104 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001105}
1106
Simon Pilgrim75c26882016-09-30 14:25:09 +00001107Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001108 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001109 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001110 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001111 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1112{
1113 if (!Enabled || !ContextDecl)
1114 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001115
1116 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001117 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1118 Record = Template->getTemplatedDecl();
1119 else
1120 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001121
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001122 QualType T = S.Context.getRecordType(Record);
1123 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1124
1125 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001126
Douglas Gregor3024f072012-04-16 07:05:22 +00001127 this->Enabled = true;
1128}
1129
1130
1131Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1132 if (Enabled) {
1133 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1134 }
1135}
1136
Simon Pilgrim75c26882016-09-30 14:25:09 +00001137bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001138 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1139 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001140 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001141 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001142 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001143
Faisal Validc6b5962016-03-21 09:25:37 +00001144 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001145
Reid Kleckner87a31802018-03-12 21:43:02 +00001146 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1147 ? *FunctionScopeIndexToStopAt
1148 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001149
Simon Pilgrim75c26882016-09-30 14:25:09 +00001150 // Check that we can capture the *enclosing object* (referred to by '*this')
1151 // by the capturing-entity/closure (lambda/block/etc) at
1152 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1153
1154 // Note: The *enclosing object* can only be captured by-value by a
1155 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001156 // [*this] { ... }.
1157 // Every other capture of the *enclosing object* results in its by-reference
1158 // capture.
1159
1160 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1161 // stack), we can capture the *enclosing object* only if:
1162 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1163 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001164 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001165 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001166 // -- or, there is some enclosing closure 'E' that has already captured the
1167 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001168 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001169 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001170 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001171
1172
Faisal Validc6b5962016-03-21 09:25:37 +00001173 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001174 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001175 if (CapturingScopeInfo *CSI =
1176 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1177 if (CSI->CXXThisCaptureIndex != 0) {
1178 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001179 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001180 break;
1181 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001182 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1183 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1184 // This context can't implicitly capture 'this'; fail out.
1185 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;
1189 }
Eli Friedman20139d32012-01-11 02:36:31 +00001190 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001191 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001192 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001193 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001194 (Explicit && idx == MaxFunctionScopesIndex)) {
1195 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1196 // iteration through can be an explicit capture, all enclosing closures,
1197 // if any, must perform implicit captures.
1198
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001199 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001200 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001201 continue;
1202 }
Eli Friedman20139d32012-01-11 02:36:31 +00001203 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001204 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001205 Diag(Loc, diag::err_this_capture)
1206 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001207 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001208 }
Eli Friedman73a04092012-01-07 04:59:52 +00001209 break;
1210 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001211 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001212
1213 // If we got here, then the closure at MaxFunctionScopesIndex on the
1214 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1215 // (including implicit by-reference captures in any enclosing closures).
1216
1217 // In the loop below, respect the ByCopy flag only for the closure requesting
1218 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001219 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001220 // implicitly capturing the *enclosing object* by reference (see loop
1221 // above)).
1222 assert((!ByCopy ||
1223 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1224 "Only a lambda can capture the enclosing object (referred to by "
1225 "*this) by copy");
Faisal Vali67b04462016-06-11 16:41:54 +00001226 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001227 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1228 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001229 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001230
Richard Smith30116532019-05-28 23:09:46 +00001231 // The type of the corresponding data member (not a 'this' pointer if 'by
1232 // copy').
1233 QualType CaptureType = ThisTy;
1234 if (ByCopy) {
1235 // If we are capturing the object referred to by '*this' by copy, ignore
1236 // any cv qualifiers inherited from the type of the member function for
1237 // the type of the closure-type's corresponding data member and any use
1238 // of 'this'.
1239 CaptureType = ThisTy->getPointeeType();
1240 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1241 }
1242
Faisal Validc6b5962016-03-21 09:25:37 +00001243 bool isNested = NumCapturingClosures > 1;
Richard Smithb5a45bb2019-05-31 01:17:04 +00001244 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001245 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001246 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001247}
1248
Richard Smith938f40b2011-06-11 17:19:42 +00001249ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001250 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1251 /// is a non-lvalue expression whose value is the address of the object for
1252 /// which the function is called.
1253
Douglas Gregor09deffa2011-10-18 16:47:30 +00001254 QualType ThisTy = getCurrentThisType();
Richard Smith8458c9e2019-05-24 01:35:07 +00001255 if (ThisTy.isNull())
1256 return Diag(Loc, diag::err_invalid_this_use);
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001257 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
Richard Smith8458c9e2019-05-24 01:35:07 +00001258}
John McCallf3a88602011-02-03 08:15:49 +00001259
Richard Smith8458c9e2019-05-24 01:35:07 +00001260Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1261 bool IsImplicit) {
1262 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1263 MarkThisReferenced(This);
1264 return This;
1265}
1266
1267void Sema::MarkThisReferenced(CXXThisExpr *This) {
1268 CheckCXXThisCapture(This->getExprLoc());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001269}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001270
Douglas Gregor3024f072012-04-16 07:05:22 +00001271bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1272 // If we're outside the body of a member function, then we'll have a specified
1273 // type for 'this'.
1274 if (CXXThisTypeOverride.isNull())
1275 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001276
Douglas Gregor3024f072012-04-16 07:05:22 +00001277 // Determine whether we're looking into a class that's currently being
1278 // defined.
1279 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1280 return Class && Class->isBeingDefined();
1281}
1282
Vedant Kumara14a1f92018-01-17 18:53:51 +00001283/// Parse construction of a specified type.
1284/// Can be interpreted either as function-style casting ("int(x)")
1285/// or class type construction ("ClassType(x,y,z)")
1286/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001287ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001288Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001289 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001290 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001291 SourceLocation RParenOrBraceLoc,
1292 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001293 if (!TypeRep)
1294 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295
John McCall97513962010-01-15 18:39:57 +00001296 TypeSourceInfo *TInfo;
1297 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1298 if (!TInfo)
1299 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001300
Vedant Kumara14a1f92018-01-17 18:53:51 +00001301 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1302 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001303 // Avoid creating a non-type-dependent expression that contains typos.
1304 // Non-type-dependent expressions are liable to be discarded without
1305 // checking for embedded typos.
1306 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1307 !Result.get()->isTypeDependent())
1308 Result = CorrectDelayedTyposInExpr(Result.get());
1309 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001310}
1311
Douglas Gregor2b88c112010-09-08 00:15:04 +00001312ExprResult
1313Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001314 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001315 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001316 SourceLocation RParenOrBraceLoc,
1317 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001318 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001319 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001320
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001321 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001322 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1323 // directly. We work around this by dropping the locations of the braces.
1324 SourceRange Locs = ListInitialization
1325 ? SourceRange()
1326 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1327 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1328 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001329 }
1330
Richard Smith600b5262017-01-26 20:40:47 +00001331 assert((!ListInitialization ||
1332 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1333 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001334 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001335
Richard Smith60437622017-02-09 19:17:44 +00001336 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1337 InitializationKind Kind =
1338 Exprs.size()
1339 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001340 ? InitializationKind::CreateDirectList(
1341 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1342 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1343 RParenOrBraceLoc)
1344 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1345 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001346
1347 // C++1z [expr.type.conv]p1:
1348 // If the type is a placeholder for a deduced class type, [...perform class
1349 // template argument deduction...]
1350 DeducedType *Deduced = Ty->getContainedDeducedType();
1351 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1352 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1353 Kind, Exprs);
1354 if (Ty.isNull())
1355 return ExprError();
1356 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1357 }
1358
Douglas Gregordd04d332009-01-16 18:33:17 +00001359 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001360 // If the expression list is a parenthesized single expression, the type
1361 // conversion expression is equivalent (in definedness, and if defined in
1362 // meaning) to the corresponding cast expression.
1363 if (Exprs.size() == 1 && !ListInitialization &&
1364 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001365 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001366 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1367 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001368 }
1369
Richard Smith49a6b6e2017-03-24 01:14:25 +00001370 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001371 QualType ElemTy = Ty;
1372 if (Ty->isArrayType()) {
1373 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001374 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1375 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001376 ElemTy = Context.getBaseElementType(Ty);
1377 }
1378
Richard Smith49a6b6e2017-03-24 01:14:25 +00001379 // There doesn't seem to be an explicit rule against this but sanity demands
1380 // we only construct objects with object types.
1381 if (Ty->isFunctionType())
1382 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1383 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001384
Richard Smith49a6b6e2017-03-24 01:14:25 +00001385 // C++17 [expr.type.conv]p2:
1386 // If the type is cv void and the initializer is (), the expression is a
1387 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001388 if (!Ty->isVoidType() &&
1389 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001390 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001391 return ExprError();
1392
Richard Smith49a6b6e2017-03-24 01:14:25 +00001393 // Otherwise, the expression is a prvalue of the specified type whose
1394 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001395 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1396 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001397
Richard Smith49a6b6e2017-03-24 01:14:25 +00001398 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001399 return Result;
1400
1401 Expr *Inner = Result.get();
1402 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1403 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001404 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1405 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001406 // If we created a CXXTemporaryObjectExpr, that node also represents the
1407 // functional cast. Otherwise, create an explicit cast to represent
1408 // the syntactic form of a functional-style cast that was used here.
1409 //
1410 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1411 // would give a more consistent AST representation than using a
1412 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1413 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001414 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001415 SourceRange Locs = ListInitialization
1416 ? SourceRange()
1417 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001418 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001419 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1420 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001421 }
1422
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001423 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001424}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001425
Artem Belevich78929ef2018-09-21 17:29:33 +00001426bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1427 // [CUDA] Ignore this function, if we can't call it.
1428 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1429 if (getLangOpts().CUDA &&
1430 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1431 return false;
1432
1433 SmallVector<const FunctionDecl*, 4> PreventedBy;
1434 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1435
1436 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1437 return Result;
1438
1439 // In case of CUDA, return true if none of the 1-argument deallocator
1440 // functions are actually callable.
1441 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1442 assert(FD->getNumParams() == 1 &&
1443 "Only single-operand functions should be in PreventedBy");
1444 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1445 });
1446}
1447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001448/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001449/// deallocation function.
1450static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001452 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001453
1454 if (FD->getOverloadedOperator() != OO_Delete &&
1455 FD->getOverloadedOperator() != OO_Array_Delete)
1456 return false;
1457
1458 unsigned UsualParams = 1;
1459
1460 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1461 S.Context.hasSameUnqualifiedType(
1462 FD->getParamDecl(UsualParams)->getType(),
1463 S.Context.getSizeType()))
1464 ++UsualParams;
1465
1466 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1467 S.Context.hasSameUnqualifiedType(
1468 FD->getParamDecl(UsualParams)->getType(),
1469 S.Context.getTypeDeclType(S.getStdAlignValT())))
1470 ++UsualParams;
1471
1472 return UsualParams == FD->getNumParams();
1473}
1474
1475namespace {
1476 struct UsualDeallocFnInfo {
1477 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001478 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001479 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001480 Destroying(false), HasSizeT(false), HasAlignValT(false),
1481 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001482 // A function template declaration is never a usual deallocation function.
1483 if (!FD)
1484 return;
Richard Smith5b349582017-10-13 01:55:36 +00001485 unsigned NumBaseParams = 1;
1486 if (FD->isDestroyingOperatorDelete()) {
1487 Destroying = true;
1488 ++NumBaseParams;
1489 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001490
1491 if (NumBaseParams < FD->getNumParams() &&
1492 S.Context.hasSameUnqualifiedType(
1493 FD->getParamDecl(NumBaseParams)->getType(),
1494 S.Context.getSizeType())) {
1495 ++NumBaseParams;
1496 HasSizeT = true;
1497 }
1498
1499 if (NumBaseParams < FD->getNumParams() &&
1500 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1501 ++NumBaseParams;
1502 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001503 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001504
1505 // In CUDA, determine how much we'd like / dislike to call this.
1506 if (S.getLangOpts().CUDA)
1507 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1508 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001509 }
1510
Eric Fiselierfa752f22018-03-21 19:19:48 +00001511 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001512
Richard Smithf75dcbe2016-10-11 00:21:10 +00001513 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1514 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001515 // C++ P0722:
1516 // A destroying operator delete is preferred over a non-destroying
1517 // operator delete.
1518 if (Destroying != Other.Destroying)
1519 return Destroying;
1520
Richard Smithf75dcbe2016-10-11 00:21:10 +00001521 // C++17 [expr.delete]p10:
1522 // If the type has new-extended alignment, a function with a parameter
1523 // of type std::align_val_t is preferred; otherwise a function without
1524 // such a parameter is preferred
1525 if (HasAlignValT != Other.HasAlignValT)
1526 return HasAlignValT == WantAlign;
1527
1528 if (HasSizeT != Other.HasSizeT)
1529 return HasSizeT == WantSize;
1530
1531 // Use CUDA call preference as a tiebreaker.
1532 return CUDAPref > Other.CUDAPref;
1533 }
1534
Richard Smithb2f0f052016-10-10 18:54:32 +00001535 DeclAccessPair Found;
1536 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001537 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001538 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001539 };
1540}
1541
1542/// Determine whether a type has new-extended alignment. This may be called when
1543/// the type is incomplete (for a delete-expression with an incomplete pointee
1544/// type), in which case it will conservatively return false if the alignment is
1545/// not known.
1546static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1547 return S.getLangOpts().AlignedAllocation &&
1548 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1549 S.getASTContext().getTargetInfo().getNewAlign();
1550}
1551
1552/// Select the correct "usual" deallocation function to use from a selection of
1553/// deallocation functions (either global or class-scope).
1554static UsualDeallocFnInfo resolveDeallocationOverload(
1555 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1556 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1557 UsualDeallocFnInfo Best;
1558
Richard Smithb2f0f052016-10-10 18:54:32 +00001559 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001560 UsualDeallocFnInfo Info(S, I.getPair());
1561 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1562 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001563 continue;
1564
1565 if (!Best) {
1566 Best = Info;
1567 if (BestFns)
1568 BestFns->push_back(Info);
1569 continue;
1570 }
1571
Richard Smithf75dcbe2016-10-11 00:21:10 +00001572 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001573 continue;
1574
1575 // If more than one preferred function is found, all non-preferred
1576 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001577 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001578 BestFns->clear();
1579
1580 Best = Info;
1581 if (BestFns)
1582 BestFns->push_back(Info);
1583 }
1584
1585 return Best;
1586}
1587
1588/// Determine whether a given type is a class for which 'delete[]' would call
1589/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1590/// we need to store the array size (even if the type is
1591/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001592static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1593 QualType allocType) {
1594 const RecordType *record =
1595 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1596 if (!record) return false;
1597
1598 // Try to find an operator delete[] in class scope.
1599
1600 DeclarationName deleteName =
1601 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1602 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1603 S.LookupQualifiedName(ops, record->getDecl());
1604
1605 // We're just doing this for information.
1606 ops.suppressDiagnostics();
1607
1608 // Very likely: there's no operator delete[].
1609 if (ops.empty()) return false;
1610
1611 // If it's ambiguous, it should be illegal to call operator delete[]
1612 // on this thing, so it doesn't matter if we allocate extra space or not.
1613 if (ops.isAmbiguous()) return false;
1614
Richard Smithb2f0f052016-10-10 18:54:32 +00001615 // C++17 [expr.delete]p10:
1616 // If the deallocation functions have class scope, the one without a
1617 // parameter of type std::size_t is selected.
1618 auto Best = resolveDeallocationOverload(
1619 S, ops, /*WantSize*/false,
1620 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1621 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001622}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001624/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001625///
Sebastian Redld74dd492012-02-12 18:41:05 +00001626/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001627/// @code new (memory) int[size][4] @endcode
1628/// or
1629/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001630///
1631/// \param StartLoc The first location of the expression.
1632/// \param UseGlobal True if 'new' was prefixed with '::'.
1633/// \param PlacementLParen Opening paren of the placement arguments.
1634/// \param PlacementArgs Placement new arguments.
1635/// \param PlacementRParen Closing paren of the placement arguments.
1636/// \param TypeIdParens If the type is in parens, the source range.
1637/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001638/// \param Initializer The initializing expression or initializer-list, or null
1639/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001640ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001641Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001642 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001644 Declarator &D, Expr *Initializer) {
Richard Smithb9fb1212019-05-06 03:47:15 +00001645 Optional<Expr *> ArraySize;
Sebastian Redl351bb782008-12-02 14:43:59 +00001646 // If the specified type is an array, unwrap it and save the expression.
1647 if (D.getNumTypeObjects() > 0 &&
1648 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001649 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001650 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001651 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1652 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001653 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001654 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1655 << D.getSourceRange());
Richard Smithb9fb1212019-05-06 03:47:15 +00001656 if (!Chunk.Arr.NumElts && !Initializer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001657 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1658 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001659
Sebastian Redl351bb782008-12-02 14:43:59 +00001660 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001661 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001662 }
1663
Douglas Gregor73341c42009-09-11 00:18:58 +00001664 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001665 if (ArraySize) {
1666 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001667 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1668 break;
1669
1670 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1671 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001672 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001673 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001674 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1675 // shall be a converted constant expression (5.19) of type std::size_t
1676 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001677 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1678 assert(IntWidth && "Builtin type of size 0?");
1679 llvm::APSInt Value(IntWidth);
1680 Array.NumElts
1681 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1682 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001683 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001684 } else {
1685 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001686 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001687 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001688 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001689 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001690 if (!Array.NumElts)
1691 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001692 }
1693 }
1694 }
1695 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001696
Craig Topperc3ec1492014-05-26 06:22:03 +00001697 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001698 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001699 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001700 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701
Sebastian Redl6047f072012-02-16 12:22:20 +00001702 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001703 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001704 DirectInitRange = List->getSourceRange();
1705
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001706 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1707 PlacementLParen, PlacementArgs, PlacementRParen,
1708 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001709 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001710}
1711
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001712static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1713 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001714 if (!Init)
1715 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001716 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1717 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001718 if (isa<ImplicitValueInitExpr>(Init))
1719 return true;
1720 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1721 return !CCE->isListInitialization() &&
1722 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001723 else if (Style == CXXNewExpr::ListInit) {
1724 assert(isa<InitListExpr>(Init) &&
1725 "Shouldn't create list CXXConstructExprs for arrays.");
1726 return true;
1727 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001728 return false;
1729}
1730
Akira Hatanaka71645c22018-12-21 07:05:36 +00001731bool
1732Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1733 if (!getLangOpts().AlignedAllocationUnavailable)
1734 return false;
1735 if (FD.isDefined())
1736 return false;
1737 bool IsAligned = false;
1738 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1739 return true;
1740 return false;
1741}
1742
Akira Hatanakacae83f72017-06-29 18:48:40 +00001743// Emit a diagnostic if an aligned allocation/deallocation function that is not
1744// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001745void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1746 SourceLocation Loc) {
1747 if (isUnavailableAlignedAllocationFunction(FD)) {
1748 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001749 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001750 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001751
Akira Hatanaka71645c22018-12-21 07:05:36 +00001752 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1753 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1754 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001755 << IsDelete << FD.getType().getAsString() << OSName
1756 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001757 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001758 }
1759}
1760
John McCalldadc5752010-08-24 06:29:42 +00001761ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001762Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001763 SourceLocation PlacementLParen,
1764 MultiExprArg PlacementArgs,
1765 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001766 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001767 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001768 TypeSourceInfo *AllocTypeInfo,
Richard Smithb9fb1212019-05-06 03:47:15 +00001769 Optional<Expr *> ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001770 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001771 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001772 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001773 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001774
Sebastian Redl6047f072012-02-16 12:22:20 +00001775 CXXNewExpr::InitializationStyle initStyle;
1776 if (DirectInitRange.isValid()) {
1777 assert(Initializer && "Have parens but no initializer.");
1778 initStyle = CXXNewExpr::CallInit;
1779 } else if (Initializer && isa<InitListExpr>(Initializer))
1780 initStyle = CXXNewExpr::ListInit;
1781 else {
1782 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1783 isa<CXXConstructExpr>(Initializer)) &&
1784 "Initializer expression that cannot have been implicitly created.");
1785 initStyle = CXXNewExpr::NoInit;
1786 }
1787
1788 Expr **Inits = &Initializer;
1789 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001790 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1791 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1792 Inits = List->getExprs();
1793 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001794 }
1795
Richard Smith60437622017-02-09 19:17:44 +00001796 // C++11 [expr.new]p15:
1797 // A new-expression that creates an object of type T initializes that
1798 // object as follows:
1799 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001800 // - If the new-initializer is omitted, the object is default-
1801 // initialized (8.5); if no initialization is performed,
1802 // the object has indeterminate value
1803 = initStyle == CXXNewExpr::NoInit
1804 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1805 // - Otherwise, the new-initializer is interpreted according to
1806 // the
1807 // initialization rules of 8.5 for direct-initialization.
1808 : initStyle == CXXNewExpr::ListInit
1809 ? InitializationKind::CreateDirectList(
1810 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001811 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001812 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1813 DirectInitRange.getBegin(),
1814 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001815
Richard Smith60437622017-02-09 19:17:44 +00001816 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1817 auto *Deduced = AllocType->getContainedDeducedType();
1818 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1819 if (ArraySize)
Richard Smithb9fb1212019-05-06 03:47:15 +00001820 return ExprError(
1821 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1822 diag::err_deduced_class_template_compound_type)
1823 << /*array*/ 2
1824 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
Richard Smith60437622017-02-09 19:17:44 +00001825
1826 InitializedEntity Entity
1827 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1828 AllocType = DeduceTemplateSpecializationFromInitializer(
1829 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1830 if (AllocType.isNull())
1831 return ExprError();
1832 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001833 bool Braced = (initStyle == CXXNewExpr::ListInit);
1834 if (NumInits == 1) {
1835 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1836 Inits = p->getInits();
1837 NumInits = p->getNumInits();
1838 Braced = true;
1839 }
1840 }
1841
Sebastian Redl6047f072012-02-16 12:22:20 +00001842 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001843 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1844 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001845 if (NumInits > 1) {
1846 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001847 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001848 diag::err_auto_new_ctor_multiple_expressions)
1849 << AllocType << TypeRange);
1850 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001851 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001852 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001853 << AllocType << TypeRange;
Richard Smith42a22372019-04-24 02:22:38 +00001854 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001855 QualType DeducedType;
Richard Smith42a22372019-04-24 02:22:38 +00001856 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001857 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Richard Smith42a22372019-04-24 02:22:38 +00001858 << AllocType << Deduce->getType()
1859 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001860 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001861 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001862 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001863 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001864
Douglas Gregorcda95f42010-05-16 16:01:03 +00001865 // Per C++0x [expr.new]p5, the type being constructed may be a
1866 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001867 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001868 if (const ConstantArrayType *Array
1869 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001870 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1871 Context.getSizeType(),
1872 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001873 AllocType = Array->getElementType();
1874 }
1875 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001876
Douglas Gregor3999e152010-10-06 16:00:31 +00001877 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1878 return ExprError();
1879
Simon Pilgrim75c26882016-09-30 14:25:09 +00001880 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001881 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001882 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1883 AllocType->isObjCLifetimeType()) {
1884 AllocType = Context.getLifetimeQualifiedType(AllocType,
1885 AllocType->getObjCARCImplicitLifetime());
1886 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001887
John McCall31168b02011-06-15 23:02:42 +00001888 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001889
Richard Smithb9fb1212019-05-06 03:47:15 +00001890 if (ArraySize && *ArraySize &&
1891 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1892 ExprResult result = CheckPlaceholderExpr(*ArraySize);
John McCall5e77d762013-04-16 07:28:30 +00001893 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001894 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001895 }
Richard Smith8dd34252012-02-04 07:07:42 +00001896 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1897 // integral or enumeration type with a non-negative value."
1898 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1899 // enumeration type, or a class type for which a single non-explicit
1900 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001901 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001902 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001903 llvm::Optional<uint64_t> KnownArraySize;
Richard Smithb9fb1212019-05-06 03:47:15 +00001904 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001905 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001906 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001907 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1908
Richard Smithb9fb1212019-05-06 03:47:15 +00001909 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001910 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001911
Simon Pilgrim75c26882016-09-30 14:25:09 +00001912 if (!ConvertedSize.isInvalid() &&
Richard Smithb9fb1212019-05-06 03:47:15 +00001913 (*ArraySize)->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001914 // Diagnose the compatibility of this conversion.
1915 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
Richard Smithb9fb1212019-05-06 03:47:15 +00001916 << (*ArraySize)->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001917 } else {
1918 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1919 protected:
1920 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001921
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001922 public:
1923 SizeConvertDiagnoser(Expr *ArraySize)
1924 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1925 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001926
1927 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1928 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001929 return S.Diag(Loc, diag::err_array_size_not_integral)
1930 << S.getLangOpts().CPlusPlus11 << T;
1931 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001932
1933 SemaDiagnosticBuilder diagnoseIncomplete(
1934 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001935 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1936 << T << ArraySize->getSourceRange();
1937 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001938
1939 SemaDiagnosticBuilder diagnoseExplicitConv(
1940 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001941 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1942 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001943
1944 SemaDiagnosticBuilder noteExplicitConv(
1945 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001946 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1947 << ConvTy->isEnumeralType() << ConvTy;
1948 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001949
1950 SemaDiagnosticBuilder diagnoseAmbiguous(
1951 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001952 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1953 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001954
1955 SemaDiagnosticBuilder noteAmbiguous(
1956 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001957 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1958 << ConvTy->isEnumeralType() << ConvTy;
1959 }
Richard Smithccc11812013-05-21 19:05:48 +00001960
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001961 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1962 QualType T,
1963 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001964 return S.Diag(Loc,
1965 S.getLangOpts().CPlusPlus11
1966 ? diag::warn_cxx98_compat_array_size_conversion
1967 : diag::ext_array_size_conversion)
1968 << T << ConvTy->isEnumeralType() << ConvTy;
1969 }
Richard Smithb9fb1212019-05-06 03:47:15 +00001970 } SizeDiagnoser(*ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001971
Richard Smithb9fb1212019-05-06 03:47:15 +00001972 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001973 SizeDiagnoser);
1974 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001975 if (ConvertedSize.isInvalid())
1976 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001978 ArraySize = ConvertedSize.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00001979 QualType SizeType = (*ArraySize)->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001980
Douglas Gregor0bf31402010-10-08 23:50:27 +00001981 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001982 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001984 // C++98 [expr.new]p7:
1985 // The expression in a direct-new-declarator shall have integral type
1986 // with a non-negative value.
1987 //
Richard Smith0511d232016-10-05 22:41:02 +00001988 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1989 // per CWG1464. Otherwise, if it's not a constant, we must have an
1990 // unparenthesized array type.
Richard Smithb9fb1212019-05-06 03:47:15 +00001991 if (!(*ArraySize)->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001992 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001993 // We've already performed any required implicit conversion to integer or
1994 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001995 // FIXME: Per CWG1464, we are required to check the value prior to
1996 // converting to size_t. This will never find a negative array size in
1997 // C++14 onwards, because Value is always unsigned here!
Richard Smithb9fb1212019-05-06 03:47:15 +00001998 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001999 if (Value.isSigned() && Value.isNegative()) {
Richard Smithb9fb1212019-05-06 03:47:15 +00002000 return ExprError(Diag((*ArraySize)->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002001 diag::err_typecheck_negative_array_size)
Richard Smithb9fb1212019-05-06 03:47:15 +00002002 << (*ArraySize)->getSourceRange());
Richard Smith0511d232016-10-05 22:41:02 +00002003 }
2004
2005 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002006 unsigned ActiveSizeBits =
2007 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002008 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002009 return ExprError(
Richard Smithb9fb1212019-05-06 03:47:15 +00002010 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2011 << Value.toString(10) << (*ArraySize)->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002012 }
Richard Smith0511d232016-10-05 22:41:02 +00002013
2014 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002015 } else if (TypeIdParens.isValid()) {
2016 // Can't have dynamic array size when the type-id is in parentheses.
Richard Smithb9fb1212019-05-06 03:47:15 +00002017 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2018 << (*ArraySize)->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002019 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2020 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
Douglas Gregorf2753b32010-07-13 15:54:32 +00002022 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002023 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025
John McCall036f2f62011-05-15 07:14:44 +00002026 // Note that we do *not* convert the argument in any way. It can
2027 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002028 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002029
Craig Topperc3ec1492014-05-26 06:22:03 +00002030 FunctionDecl *OperatorNew = nullptr;
2031 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002032 unsigned Alignment =
2033 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2034 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2035 bool PassAlignment = getLangOpts().AlignedAllocation &&
2036 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037
Brian Gesiakcb024022018-04-01 22:59:22 +00002038 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002039 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002040 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Richard Smithb9fb1212019-05-06 03:47:15 +00002041 FindAllocationFunctions(
2042 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2043 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2044 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002045 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002046
2047 // If this is an array allocation, compute whether the usual array
2048 // deallocation function for the type has a size_t parameter.
2049 bool UsualArrayDeleteWantsSize = false;
2050 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002051 UsualArrayDeleteWantsSize =
2052 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002053
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002054 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002055 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002057 OperatorNew->getType()->getAs<FunctionProtoType>();
2058 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2059 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060
Richard Smithd6f9e732014-05-13 19:56:21 +00002061 // We've already converted the placement args, just fill in any default
2062 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002063 // argument. Skip the second parameter too if we're passing in the
2064 // alignment; we've already filled it in.
2065 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2066 PassAlignment ? 2 : 1, PlacementArgs,
2067 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002068 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002070 if (!AllPlaceArgs.empty())
2071 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002072
Richard Smithd6f9e732014-05-13 19:56:21 +00002073 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002074 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002075
2076 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Richard Smithb2f0f052016-10-10 18:54:32 +00002078 // Warn if the type is over-aligned and is being allocated by (unaligned)
2079 // global operator new.
2080 if (PlacementArgs.empty() && !PassAlignment &&
2081 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002082 (OperatorNew->getBeginLoc().isValid() &&
2083 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002084 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002085 Diag(StartLoc, diag::warn_overaligned_type)
2086 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002087 << unsigned(Alignment / Context.getCharWidth())
2088 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002089 }
2090 }
2091
Sebastian Redl6047f072012-02-16 12:22:20 +00002092 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002093 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2094 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002095 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002096 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002097 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002098 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2099 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002100 }
2101
Richard Smithdd2ca572012-11-26 08:32:48 +00002102 // If we can perform the initialization, and we've not already done so,
2103 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002104 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002105 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002106 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002107 // The type we initialize is the complete type, including the array bound.
2108 QualType InitType;
2109 if (KnownArraySize)
2110 InitType = Context.getConstantArrayType(
2111 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2112 *KnownArraySize),
2113 ArrayType::Normal, 0);
2114 else if (ArraySize)
2115 InitType =
2116 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2117 else
2118 InitType = AllocType;
2119
Douglas Gregor85dabae2009-12-16 01:38:02 +00002120 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002121 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002122 InitializationSequence InitSeq(*this, Entity, Kind,
2123 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002125 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002126 if (FullInit.isInvalid())
2127 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Sebastian Redl6047f072012-02-16 12:22:20 +00002129 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2130 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002131 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002132 if (CXXBindTemporaryExpr *Binder =
2133 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002134 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002136 Initializer = FullInit.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00002137
2138 // FIXME: If we have a KnownArraySize, check that the array bound of the
2139 // initializer is no greater than that constant value.
2140
2141 if (ArraySize && !*ArraySize) {
2142 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2143 if (CAT) {
2144 // FIXME: Track that the array size was inferred rather than explicitly
2145 // specified.
2146 ArraySize = IntegerLiteral::Create(
2147 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2148 } else {
2149 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2150 << Initializer->getSourceRange();
2151 }
2152 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Douglas Gregor6642ca22010-02-26 05:06:18 +00002155 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002156 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002157 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2158 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002159 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002160 }
2161 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002162 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2163 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002164 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002165 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002166
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002167 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2168 PassAlignment, UsualArrayDeleteWantsSize,
2169 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2170 Initializer, ResultType, AllocTypeInfo, Range,
2171 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002172}
2173
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002174/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002175/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002176bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002177 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002178 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2179 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002180 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002181 return Diag(Loc, diag::err_bad_new_type)
2182 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002183 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002184 return Diag(Loc, diag::err_bad_new_type)
2185 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002186 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002187 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002188 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002189 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002190 diag::err_allocation_of_abstract_type))
2191 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002192 else if (AllocType->isVariablyModifiedType())
2193 return Diag(Loc, diag::err_variably_modified_new_type)
2194 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002195 else if (AllocType.getAddressSpace() != LangAS::Default &&
2196 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002197 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002198 << AllocType.getUnqualifiedType()
2199 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002200 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002201 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2202 QualType BaseAllocType = Context.getBaseElementType(AT);
2203 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2204 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002205 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002206 << BaseAllocType;
2207 }
2208 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002209
Sebastian Redlbd150f42008-11-21 19:14:01 +00002210 return false;
2211}
2212
Brian Gesiak87412d92018-02-15 20:09:25 +00002213static bool resolveAllocationOverload(
2214 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2215 bool &PassAlignment, FunctionDecl *&Operator,
2216 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002217 OverloadCandidateSet Candidates(R.getNameLoc(),
2218 OverloadCandidateSet::CSK_Normal);
2219 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2220 Alloc != AllocEnd; ++Alloc) {
2221 // Even member operator new/delete are implicitly treated as
2222 // static, so don't use AddMemberCandidate.
2223 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2224
2225 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2226 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2227 /*ExplicitTemplateArgs=*/nullptr, Args,
2228 Candidates,
2229 /*SuppressUserConversions=*/false);
2230 continue;
2231 }
2232
2233 FunctionDecl *Fn = cast<FunctionDecl>(D);
2234 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2235 /*SuppressUserConversions=*/false);
2236 }
2237
2238 // Do the resolution.
2239 OverloadCandidateSet::iterator Best;
2240 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2241 case OR_Success: {
2242 // Got one!
2243 FunctionDecl *FnDecl = Best->Function;
2244 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2245 Best->FoundDecl) == Sema::AR_inaccessible)
2246 return true;
2247
2248 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002249 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002250 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002251
Richard Smithb2f0f052016-10-10 18:54:32 +00002252 case OR_No_Viable_Function:
2253 // C++17 [expr.new]p13:
2254 // If no matching function is found and the allocated object type has
2255 // new-extended alignment, the alignment argument is removed from the
2256 // argument list, and overload resolution is performed again.
2257 if (PassAlignment) {
2258 PassAlignment = false;
2259 AlignArg = Args[1];
2260 Args.erase(Args.begin() + 1);
2261 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002262 Operator, &Candidates, AlignArg,
2263 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002264 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002265
Richard Smithb2f0f052016-10-10 18:54:32 +00002266 // MSVC will fall back on trying to find a matching global operator new
2267 // if operator new[] cannot be found. Also, MSVC will leak by not
2268 // generating a call to operator delete or operator delete[], but we
2269 // will not replicate that bug.
2270 // FIXME: Find out how this interacts with the std::align_val_t fallback
2271 // once MSVC implements it.
2272 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2273 S.Context.getLangOpts().MSVCCompat) {
2274 R.clear();
2275 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2276 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2277 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2278 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002279 Operator, /*Candidates=*/nullptr,
2280 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002281 }
Richard Smith1cdec012013-09-29 04:40:38 +00002282
Brian Gesiak87412d92018-02-15 20:09:25 +00002283 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002284 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2285 << R.getLookupName() << Range);
Richard Smithb2f0f052016-10-10 18:54:32 +00002286
Brian Gesiak87412d92018-02-15 20:09:25 +00002287 // If we have aligned candidates, only note the align_val_t candidates
2288 // from AlignedCandidates and the non-align_val_t candidates from
2289 // Candidates.
2290 if (AlignedCandidates) {
2291 auto IsAligned = [](OverloadCandidate &C) {
2292 return C.Function->getNumParams() > 1 &&
2293 C.Function->getParamDecl(1)->getType()->isAlignValT();
2294 };
2295 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002296
Brian Gesiak87412d92018-02-15 20:09:25 +00002297 // This was an overaligned allocation, so list the aligned candidates
2298 // first.
2299 Args.insert(Args.begin() + 1, AlignArg);
David Blaikie5e328052019-05-03 00:44:50 +00002300 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
Brian Gesiak87412d92018-02-15 20:09:25 +00002301 R.getNameLoc(), IsAligned);
2302 Args.erase(Args.begin() + 1);
David Blaikie5e328052019-05-03 00:44:50 +00002303 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
Brian Gesiak87412d92018-02-15 20:09:25 +00002304 IsUnaligned);
2305 } else {
David Blaikie5e328052019-05-03 00:44:50 +00002306 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002307 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002308 }
Richard Smith1cdec012013-09-29 04:40:38 +00002309 return true;
2310
Richard Smithb2f0f052016-10-10 18:54:32 +00002311 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002312 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002313 Candidates.NoteCandidates(
2314 PartialDiagnosticAt(R.getNameLoc(),
2315 S.PDiag(diag::err_ovl_ambiguous_call)
2316 << R.getLookupName() << Range),
2317 S, OCD_ViableCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002318 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002319 return true;
2320
2321 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002322 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002323 Candidates.NoteCandidates(
2324 PartialDiagnosticAt(R.getNameLoc(),
2325 S.PDiag(diag::err_ovl_deleted_call)
2326 << R.getLookupName() << Range),
2327 S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002328 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002329 return true;
2330 }
2331 }
2332 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002333}
2334
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002335bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002336 AllocationFunctionScope NewScope,
2337 AllocationFunctionScope DeleteScope,
2338 QualType AllocType, bool IsArray,
2339 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002340 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002341 FunctionDecl *&OperatorDelete,
2342 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002343 // --- Choosing an allocation function ---
2344 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002345 // 1) If looking in AFS_Global scope for allocation functions, only look in
2346 // the global scope. Else, if AFS_Class, only look in the scope of the
2347 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002348 // 2) If an array size is given, look for operator new[], else look for
2349 // operator new.
2350 // 3) The first argument is always size_t. Append the arguments from the
2351 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002352
Richard Smithb2f0f052016-10-10 18:54:32 +00002353 SmallVector<Expr*, 8> AllocArgs;
2354 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2355
2356 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002357 // FIXME: Should the Sema create the expression and embed it in the syntax
2358 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002359 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002360 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002361 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002362 Context.getSizeType(),
2363 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002364 AllocArgs.push_back(&Size);
2365
2366 QualType AlignValT = Context.VoidTy;
2367 if (PassAlignment) {
2368 DeclareGlobalNewDelete();
2369 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2370 }
2371 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2372 if (PassAlignment)
2373 AllocArgs.push_back(&Align);
2374
2375 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002376
Douglas Gregor6642ca22010-02-26 05:06:18 +00002377 // C++ [expr.new]p8:
2378 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002379 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002380 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002381 // type, the allocation function's name is operator new[] and the
2382 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002383 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002384 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002385
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002386 QualType AllocElemType = Context.getBaseElementType(AllocType);
2387
Richard Smithb2f0f052016-10-10 18:54:32 +00002388 // Find the allocation function.
2389 {
2390 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2391
2392 // C++1z [expr.new]p9:
2393 // If the new-expression begins with a unary :: operator, the allocation
2394 // function's name is looked up in the global scope. Otherwise, if the
2395 // allocated type is a class type T or array thereof, the allocation
2396 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002397 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002398 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2399
2400 // We can see ambiguity here if the allocation function is found in
2401 // multiple base classes.
2402 if (R.isAmbiguous())
2403 return true;
2404
2405 // If this lookup fails to find the name, or if the allocated type is not
2406 // a class type, the allocation function's name is looked up in the
2407 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002408 if (R.empty()) {
2409 if (NewScope == AFS_Class)
2410 return true;
2411
Richard Smithb2f0f052016-10-10 18:54:32 +00002412 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002413 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002414
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002415 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
Sven van Haastregt1006a062019-06-26 13:31:24 +00002416 if (PlaceArgs.empty()) {
2417 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2418 } else {
2419 Diag(StartLoc, diag::err_openclcxx_placement_new);
2420 }
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002421 return true;
2422 }
2423
Richard Smithb2f0f052016-10-10 18:54:32 +00002424 assert(!R.empty() && "implicitly declared allocation functions not found");
2425 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2426
2427 // We do our own custom access checks below.
2428 R.suppressDiagnostics();
2429
2430 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002431 OperatorNew, /*Candidates=*/nullptr,
2432 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002433 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002434 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002435
Richard Smithb2f0f052016-10-10 18:54:32 +00002436 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002437 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002438 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002439 return false;
2440 }
2441
Richard Smithb2f0f052016-10-10 18:54:32 +00002442 // Note, the name of OperatorNew might have been changed from array to
2443 // non-array by resolveAllocationOverload.
2444 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2445 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2446 ? OO_Array_Delete
2447 : OO_Delete);
2448
Douglas Gregor6642ca22010-02-26 05:06:18 +00002449 // C++ [expr.new]p19:
2450 //
2451 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002452 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002453 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002454 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002455 // the scope of T. If this lookup fails to find the name, or if
2456 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002457 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002458 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002459 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002460 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002461 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002462 LookupQualifiedName(FoundDelete, RD);
2463 }
John McCallfb6f5262010-03-18 08:19:33 +00002464 if (FoundDelete.isAmbiguous())
2465 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002466
Richard Smithb2f0f052016-10-10 18:54:32 +00002467 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002468 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002469 if (DeleteScope == AFS_Class)
2470 return true;
2471
Douglas Gregor6642ca22010-02-26 05:06:18 +00002472 DeclareGlobalNewDelete();
2473 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2474 }
2475
2476 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002477
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002478 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002479
John McCalld3be2c82010-09-14 21:34:24 +00002480 // Whether we're looking for a placement operator delete is dictated
2481 // by whether we selected a placement operator new, not by whether
2482 // we had explicit placement arguments. This matters for things like
2483 // struct A { void *operator new(size_t, int = 0); ... };
2484 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002485 //
2486 // We don't have any definition for what a "placement allocation function"
2487 // is, but we assume it's any allocation function whose
2488 // parameter-declaration-clause is anything other than (size_t).
2489 //
2490 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2491 // This affects whether an exception from the constructor of an overaligned
2492 // type uses the sized or non-sized form of aligned operator delete.
2493 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2494 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002495
2496 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002497 // C++ [expr.new]p20:
2498 // A declaration of a placement deallocation function matches the
2499 // declaration of a placement allocation function if it has the
2500 // same number of parameters and, after parameter transformations
2501 // (8.3.5), all parameter types except the first are
2502 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002503 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002504 // To perform this comparison, we compute the function type that
2505 // the deallocation function should have, and use that type both
2506 // for template argument deduction and for comparison purposes.
2507 QualType ExpectedFunctionType;
2508 {
2509 const FunctionProtoType *Proto
2510 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002511
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002512 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002513 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002514 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2515 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002516
John McCalldb40c7f2010-12-14 08:05:40 +00002517 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002518 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002519 EPI.Variadic = Proto->isVariadic();
2520
Douglas Gregor6642ca22010-02-26 05:06:18 +00002521 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002522 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002523 }
2524
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002525 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002526 DEnd = FoundDelete.end();
2527 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002528 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002529 if (FunctionTemplateDecl *FnTmpl =
2530 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002531 // Perform template argument deduction to try to match the
2532 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002533 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002534 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2535 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002536 continue;
2537 } else
2538 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2539
Richard Smithbaa47832016-12-01 02:11:49 +00002540 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2541 ExpectedFunctionType,
2542 /*AdjustExcpetionSpec*/true),
2543 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002544 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002545 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002546
Richard Smithb2f0f052016-10-10 18:54:32 +00002547 if (getLangOpts().CUDA)
2548 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2549 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002550 // C++1y [expr.new]p22:
2551 // For a non-placement allocation function, the normal deallocation
2552 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002553 //
2554 // Per [expr.delete]p10, this lookup prefers a member operator delete
2555 // without a size_t argument, but prefers a non-member operator delete
2556 // with a size_t where possible (which it always is in this case).
2557 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2558 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2559 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2560 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2561 &BestDeallocFns);
2562 if (Selected)
2563 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2564 else {
2565 // If we failed to select an operator, all remaining functions are viable
2566 // but ambiguous.
2567 for (auto Fn : BestDeallocFns)
2568 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002569 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002570 }
2571
2572 // C++ [expr.new]p20:
2573 // [...] If the lookup finds a single matching deallocation
2574 // function, that function will be called; otherwise, no
2575 // deallocation function will be called.
2576 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002577 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002578
Richard Smithb2f0f052016-10-10 18:54:32 +00002579 // C++1z [expr.new]p23:
2580 // If the lookup finds a usual deallocation function (3.7.4.2)
2581 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002582 // as a placement deallocation function, would have been
2583 // selected as a match for the allocation function, the program
2584 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002585 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002586 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002587 UsualDeallocFnInfo Info(*this,
2588 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002589 // Core issue, per mail to core reflector, 2016-10-09:
2590 // If this is a member operator delete, and there is a corresponding
2591 // non-sized member operator delete, this isn't /really/ a sized
2592 // deallocation function, it just happens to have a size_t parameter.
2593 bool IsSizedDelete = Info.HasSizeT;
2594 if (IsSizedDelete && !FoundGlobalDelete) {
2595 auto NonSizedDelete =
2596 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2597 /*WantAlign*/Info.HasAlignValT);
2598 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2599 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2600 IsSizedDelete = false;
2601 }
2602
2603 if (IsSizedDelete) {
2604 SourceRange R = PlaceArgs.empty()
2605 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002606 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002607 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002608 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2609 if (!OperatorDelete->isImplicit())
2610 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2611 << DeleteName;
2612 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002613 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002614
2615 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2616 Matches[0].first);
2617 } else if (!Matches.empty()) {
2618 // We found multiple suitable operators. Per [expr.new]p20, that means we
2619 // call no 'operator delete' function, but we should at least warn the user.
2620 // FIXME: Suppress this warning if the construction cannot throw.
2621 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2622 << DeleteName << AllocElemType;
2623
2624 for (auto &Match : Matches)
2625 Diag(Match.second->getLocation(),
2626 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002627 }
2628
Sebastian Redlfaf68082008-12-03 20:26:15 +00002629 return false;
2630}
2631
2632/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2633/// delete. These are:
2634/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002635/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002636/// void* operator new(std::size_t) throw(std::bad_alloc);
2637/// void* operator new[](std::size_t) throw(std::bad_alloc);
2638/// void operator delete(void *) throw();
2639/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002640/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002641/// void* operator new(std::size_t);
2642/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002643/// void operator delete(void *) noexcept;
2644/// void operator delete[](void *) noexcept;
2645/// // C++1y:
2646/// void* operator new(std::size_t);
2647/// void* operator new[](std::size_t);
2648/// void operator delete(void *) noexcept;
2649/// void operator delete[](void *) noexcept;
2650/// void operator delete(void *, std::size_t) noexcept;
2651/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002652/// @endcode
2653/// Note that the placement and nothrow forms of new are *not* implicitly
2654/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002655void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002656 if (GlobalNewDeleteDeclared)
2657 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658
Anastasia Stulova46b55fa2019-07-18 10:02:35 +00002659 // The implicitly declared new and delete operators
2660 // are not supported in OpenCL.
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002661 if (getLangOpts().OpenCLCPlusPlus)
2662 return;
2663
Douglas Gregor87f54062009-09-15 22:30:29 +00002664 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665 // [...] The following allocation and deallocation functions (18.4) are
2666 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002667 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668 //
Sebastian Redl37588092011-03-14 18:08:30 +00002669 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002670 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 // void* operator new[](std::size_t) throw(std::bad_alloc);
2672 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002673 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002674 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002675 // void* operator new(std::size_t);
2676 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002677 // void operator delete(void*) noexcept;
2678 // void operator delete[](void*) noexcept;
2679 // C++1y:
2680 // void* operator new(std::size_t);
2681 // void* operator new[](std::size_t);
2682 // void operator delete(void*) noexcept;
2683 // void operator delete[](void*) noexcept;
2684 // void operator delete(void*, std::size_t) noexcept;
2685 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002686 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002687 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002688 // new, operator new[], operator delete, operator delete[].
2689 //
2690 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2691 // "std" or "bad_alloc" as necessary to form the exception specification.
2692 // However, we do not make these implicit declarations visible to name
2693 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002694 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002695 // The "std::bad_alloc" class has not yet been declared, so build it
2696 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2698 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002699 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002701 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002702 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002703 }
Richard Smith59139022016-09-30 22:41:36 +00002704 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002705 // The "std::align_val_t" enum class has not yet been declared, so build it
2706 // implicitly.
2707 auto *AlignValT = EnumDecl::Create(
2708 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2709 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2710 AlignValT->setIntegerType(Context.getSizeType());
2711 AlignValT->setPromotionType(Context.getSizeType());
2712 AlignValT->setImplicit(true);
2713 StdAlignValT = AlignValT;
2714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715
Sebastian Redlfaf68082008-12-03 20:26:15 +00002716 GlobalNewDeleteDeclared = true;
2717
2718 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2719 QualType SizeT = Context.getSizeType();
2720
Richard Smith96269c52016-09-29 22:49:46 +00002721 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2722 QualType Return, QualType Param) {
2723 llvm::SmallVector<QualType, 3> Params;
2724 Params.push_back(Param);
2725
2726 // Create up to four variants of the function (sized/aligned).
2727 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2728 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002729 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002730
2731 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2732 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2733 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002734 if (Sized)
2735 Params.push_back(SizeT);
2736
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002737 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002738 if (Aligned)
2739 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2740
2741 DeclareGlobalAllocationFunction(
2742 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2743
2744 if (Aligned)
2745 Params.pop_back();
2746 }
2747 }
2748 };
2749
2750 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2751 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2752 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2753 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002754}
2755
2756/// DeclareGlobalAllocationFunction - Declares a single implicit global
2757/// allocation function if it doesn't already exist.
2758void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002759 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002760 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002761 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2762
2763 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002764 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2765 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2766 Alloc != AllocEnd; ++Alloc) {
2767 // Only look at non-template functions, as it is the predefined,
2768 // non-templated allocation function we are trying to declare here.
2769 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002770 if (Func->getNumParams() == Params.size()) {
2771 llvm::SmallVector<QualType, 3> FuncParams;
2772 for (auto *P : Func->parameters())
2773 FuncParams.push_back(
2774 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2775 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002776 // Make the function visible to name lookup, even if we found it in
2777 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002778 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002779 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002780 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002781 }
Chandler Carruth93538422010-02-03 11:02:14 +00002782 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002783 }
2784 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002785
Erich Keane881e83d2019-03-04 14:54:52 +00002786 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
Erich Keane00022812019-05-23 16:05:21 +00002787 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
Richard Smithc015bc22014-02-07 22:39:53 +00002788
Richard Smithf8b417c2014-02-08 00:42:45 +00002789 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002791 = (Name.getCXXOverloadedOperator() == OO_New ||
2792 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002793 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002794 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002795 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002796 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002797 EPI.ExceptionSpec.Type = EST_Dynamic;
2798 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002799 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002800 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002801 EPI.ExceptionSpec =
2802 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804
Artem Belevich07db5cf2016-10-21 20:34:05 +00002805 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2806 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2807 FunctionDecl *Alloc = FunctionDecl::Create(
2808 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2809 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2810 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002811 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002812 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002813
Petr Hosek821b38f2018-12-04 03:25:25 +00002814 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2815 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2816 ? VisibilityAttr::Hidden
2817 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Artem Belevich07db5cf2016-10-21 20:34:05 +00002819 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2820 for (QualType T : Params) {
2821 ParamDecls.push_back(ParmVarDecl::Create(
2822 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2823 /*TInfo=*/nullptr, SC_None, nullptr));
2824 ParamDecls.back()->setImplicit();
2825 }
2826 Alloc->setParams(ParamDecls);
2827 if (ExtraAttr)
2828 Alloc->addAttr(ExtraAttr);
2829 Context.getTranslationUnitDecl()->addDecl(Alloc);
2830 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2831 };
2832
2833 if (!LangOpts.CUDA)
2834 CreateAllocationFunctionDecl(nullptr);
2835 else {
2836 // Host and device get their own declaration so each can be
2837 // defined or re-declared independently.
2838 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2839 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002840 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002841}
2842
Richard Smith1cdec012013-09-29 04:40:38 +00002843FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2844 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002845 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002846 DeclarationName Name) {
2847 DeclareGlobalNewDelete();
2848
2849 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2850 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2851
Richard Smithb2f0f052016-10-10 18:54:32 +00002852 // FIXME: It's possible for this to result in ambiguity, through a
2853 // user-declared variadic operator delete or the enable_if attribute. We
2854 // should probably not consider those cases to be usual deallocation
2855 // functions. But for now we just make an arbitrary choice in that case.
2856 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2857 Overaligned);
2858 assert(Result.FD && "operator delete missing from global scope?");
2859 return Result.FD;
2860}
Richard Smith1cdec012013-09-29 04:40:38 +00002861
Richard Smithb2f0f052016-10-10 18:54:32 +00002862FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2863 CXXRecordDecl *RD) {
2864 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002865
Richard Smithb2f0f052016-10-10 18:54:32 +00002866 FunctionDecl *OperatorDelete = nullptr;
2867 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2868 return nullptr;
2869 if (OperatorDelete)
2870 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002871
Richard Smithb2f0f052016-10-10 18:54:32 +00002872 // If there's no class-specific operator delete, look up the global
2873 // non-array delete.
2874 return FindUsualDeallocationFunction(
2875 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2876 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002877}
2878
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002879bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2880 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002881 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002882 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002883 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002884 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885
John McCall27b18f82009-11-17 02:14:36 +00002886 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002887 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002888
Chandler Carruthb6f99172010-06-28 00:30:51 +00002889 Found.suppressDiagnostics();
2890
Richard Smithb2f0f052016-10-10 18:54:32 +00002891 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002892
Richard Smithb2f0f052016-10-10 18:54:32 +00002893 // C++17 [expr.delete]p10:
2894 // If the deallocation functions have class scope, the one without a
2895 // parameter of type std::size_t is selected.
2896 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2897 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2898 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002899
Richard Smithb2f0f052016-10-10 18:54:32 +00002900 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002901 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002902 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002903
Richard Smithb2f0f052016-10-10 18:54:32 +00002904 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002905 if (Operator->isDeleted()) {
2906 if (Diagnose) {
2907 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002908 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002909 }
2910 return true;
2911 }
2912
Richard Smith921bd202012-02-26 09:11:52 +00002913 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002914 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002915 return true;
2916
John McCall66a87592010-08-04 00:31:26 +00002917 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002918 }
John McCall66a87592010-08-04 00:31:26 +00002919
Richard Smithb2f0f052016-10-10 18:54:32 +00002920 // We found multiple suitable operators; complain about the ambiguity.
2921 // FIXME: The standard doesn't say to do this; it appears that the intent
2922 // is that this should never happen.
2923 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002924 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002925 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2926 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002927 for (auto &Match : Matches)
2928 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002929 }
John McCall66a87592010-08-04 00:31:26 +00002930 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002931 }
2932
2933 // We did find operator delete/operator delete[] declarations, but
2934 // none of them were suitable.
2935 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002936 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002937 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2938 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939
Richard Smithb2f0f052016-10-10 18:54:32 +00002940 for (NamedDecl *D : Found)
2941 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002942 diag::note_member_declared_here) << Name;
2943 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002944 return true;
2945 }
2946
Craig Topperc3ec1492014-05-26 06:22:03 +00002947 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002948 return false;
2949}
2950
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002951namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002952/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002953/// initializing deletee have the same array form.
2954class MismatchingNewDeleteDetector {
2955public:
2956 enum MismatchResult {
2957 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2958 NoMismatch,
2959 /// Indicates that variable is initialized with mismatching form of \a new.
2960 VarInitMismatches,
2961 /// Indicates that member is initialized with mismatching form of \a new.
2962 MemberInitMismatches,
2963 /// Indicates that 1 or more constructors' definitions could not been
2964 /// analyzed, and they will be checked again at the end of translation unit.
2965 AnalyzeLater
2966 };
2967
2968 /// \param EndOfTU True, if this is the final analysis at the end of
2969 /// translation unit. False, if this is the initial analysis at the point
2970 /// delete-expression was encountered.
2971 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002972 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002973 HasUndefinedConstructors(false) {}
2974
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002975 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002976 /// matching form of new-expression.
2977 ///
2978 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2979 /// point where delete-expression is encountered, then a warning will be
2980 /// issued immediately. If return value is \c AnalyzeLater at the point where
2981 /// delete-expression is seen, then member will be analyzed at the end of
2982 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2983 /// couldn't be analyzed. If at least one constructor initializes the member
2984 /// with matching type of new, the return value is \c NoMismatch.
2985 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002986 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002987 /// \param Field Class member to analyze.
2988 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2989 /// for deleting the \p Field.
2990 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002991 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002992 /// List of mismatching new-expressions used for initialization of the pointee
2993 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2994 /// Indicates whether delete-expression was in array form.
2995 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002996
2997private:
2998 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002999 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003000 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003001 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003002 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003003 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003004 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003005 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003006 /// \c new either by the member initializer or in-class initialization.
3007 ///
3008 /// If bodies of all constructors are not visible at the end of translation
3009 /// unit or at least one constructor initializes member with the matching
3010 /// form of \c new, mismatch cannot be proven, and this function will return
3011 /// \c NoMismatch.
3012 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003013 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003014 /// \c new.
3015 ///
3016 /// If variable is initialized with matching form of \c new or variable is not
3017 /// initialized with a \c new expression, this function will return true.
3018 /// If variable is initialized with mismatching form of \c new, returns false.
3019 /// \param D Variable to analyze.
3020 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003021 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003022 /// form of \c new.
3023 ///
3024 /// Returns true, if member is initialized with matching form of \c new in
3025 /// member initializer list. Returns false, if member is initialized with the
3026 /// matching form of \c new in this constructor's initializer or given
3027 /// constructor isn't defined at the point where delete-expression is seen, or
3028 /// member isn't initialized by the constructor.
3029 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003030 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003031 /// \c new in member initializer list.
3032 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3033 /// Checks whether member is initialized with mismatching form of \c new by
3034 /// in-class initializer.
3035 MismatchResult analyzeInClassInitializer();
3036};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003037}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003038
3039MismatchingNewDeleteDetector::MismatchResult
3040MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3041 NewExprs.clear();
3042 assert(DE && "Expected delete-expression");
3043 IsArrayForm = DE->isArrayForm();
3044 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3045 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3046 return analyzeMemberExpr(ME);
3047 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3048 if (!hasMatchingVarInit(D))
3049 return VarInitMismatches;
3050 }
3051 return NoMismatch;
3052}
3053
3054const CXXNewExpr *
3055MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3056 assert(E != nullptr && "Expected a valid initializer expression");
3057 E = E->IgnoreParenImpCasts();
3058 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3059 if (ILE->getNumInits() == 1)
3060 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3061 }
3062
3063 return dyn_cast_or_null<const CXXNewExpr>(E);
3064}
3065
3066bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3067 const CXXCtorInitializer *CI) {
3068 const CXXNewExpr *NE = nullptr;
3069 if (Field == CI->getMember() &&
3070 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3071 if (NE->isArray() == IsArrayForm)
3072 return true;
3073 else
3074 NewExprs.push_back(NE);
3075 }
3076 return false;
3077}
3078
3079bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3080 const CXXConstructorDecl *CD) {
3081 if (CD->isImplicit())
3082 return false;
3083 const FunctionDecl *Definition = CD;
3084 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3085 HasUndefinedConstructors = true;
3086 return EndOfTU;
3087 }
3088 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3089 if (hasMatchingNewInCtorInit(CI))
3090 return true;
3091 }
3092 return false;
3093}
3094
3095MismatchingNewDeleteDetector::MismatchResult
3096MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3097 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003098 const Expr *InitExpr = Field->getInClassInitializer();
3099 if (!InitExpr)
3100 return EndOfTU ? NoMismatch : AnalyzeLater;
3101 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003102 if (NE->isArray() != IsArrayForm) {
3103 NewExprs.push_back(NE);
3104 return MemberInitMismatches;
3105 }
3106 }
3107 return NoMismatch;
3108}
3109
3110MismatchingNewDeleteDetector::MismatchResult
3111MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3112 bool DeleteWasArrayForm) {
3113 assert(Field != nullptr && "Analysis requires a valid class member.");
3114 this->Field = Field;
3115 IsArrayForm = DeleteWasArrayForm;
3116 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3117 for (const auto *CD : RD->ctors()) {
3118 if (hasMatchingNewInCtor(CD))
3119 return NoMismatch;
3120 }
3121 if (HasUndefinedConstructors)
3122 return EndOfTU ? NoMismatch : AnalyzeLater;
3123 if (!NewExprs.empty())
3124 return MemberInitMismatches;
3125 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3126 : NoMismatch;
3127}
3128
3129MismatchingNewDeleteDetector::MismatchResult
3130MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3131 assert(ME != nullptr && "Expected a member expression");
3132 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3133 return analyzeField(F, IsArrayForm);
3134 return NoMismatch;
3135}
3136
3137bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3138 const CXXNewExpr *NE = nullptr;
3139 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3140 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3141 NE->isArray() != IsArrayForm) {
3142 NewExprs.push_back(NE);
3143 }
3144 }
3145 return NewExprs.empty();
3146}
3147
3148static void
3149DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3150 const MismatchingNewDeleteDetector &Detector) {
3151 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3152 FixItHint H;
3153 if (!Detector.IsArrayForm)
3154 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3155 else {
3156 SourceLocation RSquare = Lexer::findLocationAfterToken(
3157 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3158 SemaRef.getLangOpts(), true);
3159 if (RSquare.isValid())
3160 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3161 }
3162 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3163 << Detector.IsArrayForm << H;
3164
3165 for (const auto *NE : Detector.NewExprs)
3166 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3167 << Detector.IsArrayForm;
3168}
3169
3170void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3171 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3172 return;
3173 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3174 switch (Detector.analyzeDeleteExpr(DE)) {
3175 case MismatchingNewDeleteDetector::VarInitMismatches:
3176 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003177 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003178 break;
3179 }
3180 case MismatchingNewDeleteDetector::AnalyzeLater: {
3181 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003182 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003183 break;
3184 }
3185 case MismatchingNewDeleteDetector::NoMismatch:
3186 break;
3187 }
3188}
3189
3190void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3191 bool DeleteWasArrayForm) {
3192 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3193 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3194 case MismatchingNewDeleteDetector::VarInitMismatches:
3195 llvm_unreachable("This analysis should have been done for class members.");
3196 case MismatchingNewDeleteDetector::AnalyzeLater:
3197 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3198 "translation unit.");
3199 case MismatchingNewDeleteDetector::MemberInitMismatches:
3200 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3201 break;
3202 case MismatchingNewDeleteDetector::NoMismatch:
3203 break;
3204 }
3205}
3206
Sebastian Redlbd150f42008-11-21 19:14:01 +00003207/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3208/// @code ::delete ptr; @endcode
3209/// or
3210/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003211ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003212Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003213 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003214 // C++ [expr.delete]p1:
3215 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003216 // non-explicit conversion function to a pointer type. The result has type
3217 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003218 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003219 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3220
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003221 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003222 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003223 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003224 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003225
John Wiegley01296292011-04-08 18:41:53 +00003226 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003227 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003228 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003229 if (Ex.isInvalid())
3230 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003231
John Wiegley01296292011-04-08 18:41:53 +00003232 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003233
Richard Smithccc11812013-05-21 19:05:48 +00003234 class DeleteConverter : public ContextualImplicitConverter {
3235 public:
3236 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
Craig Toppere14c0f82014-03-12 04:55:44 +00003238 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003239 // FIXME: If we have an operator T* and an operator void*, we must pick
3240 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003241 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003242 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003243 return true;
3244 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003245 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003246
Richard Smithccc11812013-05-21 19:05:48 +00003247 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003248 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003249 return S.Diag(Loc, diag::err_delete_operand) << T;
3250 }
3251
3252 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003253 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003254 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3255 }
3256
3257 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003258 QualType T,
3259 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003260 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3261 }
3262
3263 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003264 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003265 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3266 << ConvTy;
3267 }
3268
3269 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003270 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003271 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3272 }
3273
3274 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003275 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003276 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3277 << ConvTy;
3278 }
3279
3280 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003281 QualType T,
3282 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003283 llvm_unreachable("conversion functions are permitted");
3284 }
3285 } Converter;
3286
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003287 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003288 if (Ex.isInvalid())
3289 return ExprError();
3290 Type = Ex.get()->getType();
3291 if (!Converter.match(Type))
3292 // FIXME: PerformContextualImplicitConversion should return ExprError
3293 // itself in this case.
3294 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003295
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003296 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003297 QualType PointeeElem = Context.getBaseElementType(Pointee);
3298
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003299 if (Pointee.getAddressSpace() != LangAS::Default &&
3300 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003301 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003302 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003303 << Pointee.getUnqualifiedType()
3304 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003305
Craig Topperc3ec1492014-05-26 06:22:03 +00003306 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003307 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003309 // effectively bans deletion of "void*". However, most compilers support
3310 // this, so we treat it as a warning unless we're in a SFINAE context.
3311 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003312 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003313 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003314 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003315 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003316 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003317 // FIXME: This can result in errors if the definition was imported from a
3318 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003319 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003320 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003321 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3322 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3323 }
3324 }
3325
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003326 if (Pointee->isArrayType() && !ArrayForm) {
3327 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003328 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003329 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003330 ArrayForm = true;
3331 }
3332
Anders Carlssona471db02009-08-16 20:29:29 +00003333 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3334 ArrayForm ? OO_Array_Delete : OO_Delete);
3335
Eli Friedmanae4280f2011-07-26 22:25:31 +00003336 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003338 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3339 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003340 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
John McCall284c48f2011-01-27 09:37:56 +00003342 // If we're allocating an array of records, check whether the
3343 // usual operator delete[] has a size_t parameter.
3344 if (ArrayForm) {
3345 // If the user specifically asked to use the global allocator,
3346 // we'll need to do the lookup into the class.
3347 if (UseGlobal)
3348 UsualArrayDeleteWantsSize =
3349 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3350
3351 // Otherwise, the usual operator delete[] should be the
3352 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003353 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003354 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003355 UsualDeallocFnInfo(*this,
3356 DeclAccessPair::make(OperatorDelete, AS_public))
3357 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003358 }
3359
Richard Smitheec915d62012-02-18 04:13:32 +00003360 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003361 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003362 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003363 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003364 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3365 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003366 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003367
Nico Weber5a9259c2016-01-15 21:45:31 +00003368 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3369 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3370 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3371 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373
Richard Smithb2f0f052016-10-10 18:54:32 +00003374 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003375 if (getLangOpts().OpenCLCPlusPlus) {
3376 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3377 return ExprError();
3378 }
3379
Richard Smithb2f0f052016-10-10 18:54:32 +00003380 bool IsComplete = isCompleteType(StartLoc, Pointee);
3381 bool CanProvideSize =
3382 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3383 Pointee.isDestructedType());
3384 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3385
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003386 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003387 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3388 Overaligned, DeleteName);
3389 }
Mike Stump11289f42009-09-09 15:08:12 +00003390
Eli Friedmanfa0df832012-02-02 03:46:19 +00003391 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003392
Richard Smith5b349582017-10-13 01:55:36 +00003393 // Check access and ambiguity of destructor if we're going to call it.
3394 // Note that this is required even for a virtual delete.
3395 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003396 if (PointeeRD) {
3397 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003398 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3399 PDiag(diag::err_access_dtor) << PointeeElem);
3400 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003401 }
3402 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003403
Akira Hatanaka71645c22018-12-21 07:05:36 +00003404 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003405
3406 // Convert the operand to the type of the first parameter of operator
3407 // delete. This is only necessary if we selected a destroying operator
3408 // delete that we are going to call (non-virtually); converting to void*
3409 // is trivial and left to AST consumers to handle.
3410 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3411 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003412 Qualifiers Qs = Pointee.getQualifiers();
3413 if (Qs.hasCVRQualifiers()) {
3414 // Qualifiers are irrelevant to this conversion; we're only looking
3415 // for access and ambiguity.
3416 Qs.removeCVRQualifiers();
3417 QualType Unqual = Context.getPointerType(
3418 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3419 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3420 }
Richard Smith5b349582017-10-13 01:55:36 +00003421 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3422 if (Ex.isInvalid())
3423 return ExprError();
3424 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003425 }
3426
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003427 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003428 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3429 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003430 AnalyzeDeleteExprMismatch(Result);
3431 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003432}
3433
Eric Fiselierfa752f22018-03-21 19:19:48 +00003434static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3435 bool IsDelete,
3436 FunctionDecl *&Operator) {
3437
3438 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3439 IsDelete ? OO_Delete : OO_New);
3440
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003441 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003442 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3443 assert(!R.empty() && "implicitly declared allocation functions not found");
3444 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3445
3446 // We do our own custom access checks below.
3447 R.suppressDiagnostics();
3448
3449 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3450 OverloadCandidateSet Candidates(R.getNameLoc(),
3451 OverloadCandidateSet::CSK_Normal);
3452 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3453 FnOvl != FnOvlEnd; ++FnOvl) {
3454 // Even member operator new/delete are implicitly treated as
3455 // static, so don't use AddMemberCandidate.
3456 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3457
3458 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3459 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3460 /*ExplicitTemplateArgs=*/nullptr, Args,
3461 Candidates,
3462 /*SuppressUserConversions=*/false);
3463 continue;
3464 }
3465
3466 FunctionDecl *Fn = cast<FunctionDecl>(D);
3467 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3468 /*SuppressUserConversions=*/false);
3469 }
3470
3471 SourceRange Range = TheCall->getSourceRange();
3472
3473 // Do the resolution.
3474 OverloadCandidateSet::iterator Best;
3475 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3476 case OR_Success: {
3477 // Got one!
3478 FunctionDecl *FnDecl = Best->Function;
3479 assert(R.getNamingClass() == nullptr &&
3480 "class members should not be considered");
3481
3482 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3483 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3484 << (IsDelete ? 1 : 0) << Range;
3485 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3486 << R.getLookupName() << FnDecl->getSourceRange();
3487 return true;
3488 }
3489
3490 Operator = FnDecl;
3491 return false;
3492 }
3493
3494 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00003495 Candidates.NoteCandidates(
3496 PartialDiagnosticAt(R.getNameLoc(),
3497 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3498 << R.getLookupName() << Range),
3499 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003500 return true;
3501
3502 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00003503 Candidates.NoteCandidates(
3504 PartialDiagnosticAt(R.getNameLoc(),
3505 S.PDiag(diag::err_ovl_ambiguous_call)
3506 << R.getLookupName() << Range),
3507 S, OCD_ViableCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003508 return true;
3509
3510 case OR_Deleted: {
David Blaikie5e328052019-05-03 00:44:50 +00003511 Candidates.NoteCandidates(
3512 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3513 << R.getLookupName() << Range),
3514 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003515 return true;
3516 }
3517 }
3518 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3519}
3520
3521ExprResult
3522Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3523 bool IsDelete) {
3524 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3525 if (!getLangOpts().CPlusPlus) {
3526 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3527 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3528 << "C++";
3529 return ExprError();
3530 }
3531 // CodeGen assumes it can find the global new and delete to call,
3532 // so ensure that they are declared.
3533 DeclareGlobalNewDelete();
3534
3535 FunctionDecl *OperatorNewOrDelete = nullptr;
3536 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3537 OperatorNewOrDelete))
3538 return ExprError();
3539 assert(OperatorNewOrDelete && "should be found");
3540
Akira Hatanaka71645c22018-12-21 07:05:36 +00003541 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3542 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3543
Eric Fiselierfa752f22018-03-21 19:19:48 +00003544 TheCall->setType(OperatorNewOrDelete->getReturnType());
3545 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3546 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3547 InitializedEntity Entity =
3548 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3549 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003550 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003551 if (Arg.isInvalid())
3552 return ExprError();
3553 TheCall->setArg(i, Arg.get());
3554 }
3555 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3556 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3557 "Callee expected to be implicit cast to a builtin function pointer");
3558 Callee->setType(OperatorNewOrDelete->getType());
3559
3560 return TheCallResult;
3561}
3562
Nico Weber5a9259c2016-01-15 21:45:31 +00003563void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3564 bool IsDelete, bool CallCanBeVirtual,
3565 bool WarnOnNonAbstractTypes,
3566 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003567 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003568 return;
3569
3570 // C++ [expr.delete]p3:
3571 // In the first alternative (delete object), if the static type of the
3572 // object to be deleted is different from its dynamic type, the static
3573 // type shall be a base class of the dynamic type of the object to be
3574 // deleted and the static type shall have a virtual destructor or the
3575 // behavior is undefined.
3576 //
3577 const CXXRecordDecl *PointeeRD = dtor->getParent();
3578 // Note: a final class cannot be derived from, no issue there
3579 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3580 return;
3581
Nico Weberbf2260c2017-08-31 06:17:08 +00003582 // If the superclass is in a system header, there's nothing that can be done.
3583 // The `delete` (where we emit the warning) can be in a system header,
3584 // what matters for this warning is where the deleted type is defined.
3585 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3586 return;
3587
Brian Gesiak5488ab42019-01-11 01:54:53 +00003588 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003589 if (PointeeRD->isAbstract()) {
3590 // If the class is abstract, we warn by default, because we're
3591 // sure the code has undefined behavior.
3592 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3593 << ClassType;
3594 } else if (WarnOnNonAbstractTypes) {
3595 // Otherwise, if this is not an array delete, it's a bit suspect,
3596 // but not necessarily wrong.
3597 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3598 << ClassType;
3599 }
3600 if (!IsDelete) {
3601 std::string TypeStr;
3602 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3603 Diag(DtorLoc, diag::note_delete_non_virtual)
3604 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3605 }
3606}
3607
Richard Smith03a4aa32016-06-23 19:02:52 +00003608Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3609 SourceLocation StmtLoc,
3610 ConditionKind CK) {
3611 ExprResult E =
3612 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3613 if (E.isInvalid())
3614 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003615 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3616 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003617}
3618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003619/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003620/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003621ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003622 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003623 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003624 if (ConditionVar->isInvalidDecl())
3625 return ExprError();
3626
Douglas Gregor633caca2009-11-23 23:44:04 +00003627 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor633caca2009-11-23 23:44:04 +00003629 // C++ [stmt.select]p2:
3630 // The declarator shall not specify a function or an array.
3631 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003633 diag::err_invalid_use_of_function_type)
3634 << ConditionVar->getSourceRange());
3635 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003637 diag::err_invalid_use_of_array_type)
3638 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003639
Richard Smith7dcd7332019-06-04 18:30:46 +00003640 ExprResult Condition = BuildDeclRefExpr(
3641 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3642 ConditionVar->getLocation());
Eli Friedman2dfa7932012-01-16 21:00:51 +00003643
Richard Smith03a4aa32016-06-23 19:02:52 +00003644 switch (CK) {
3645 case ConditionKind::Boolean:
3646 return CheckBooleanCondition(StmtLoc, Condition.get());
3647
Richard Smithb130fe72016-06-23 19:16:49 +00003648 case ConditionKind::ConstexprIf:
3649 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3650
Richard Smith03a4aa32016-06-23 19:02:52 +00003651 case ConditionKind::Switch:
3652 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654
Richard Smith03a4aa32016-06-23 19:02:52 +00003655 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003656}
3657
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003658/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003659ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003660 // C++ 6.4p4:
3661 // The value of a condition that is an initialized declaration in a statement
3662 // other than a switch statement is the value of the declared variable
3663 // implicitly converted to type bool. If that conversion is ill-formed, the
3664 // program is ill-formed.
3665 // The value of a condition that is an expression is the value of the
3666 // expression, implicitly converted to bool.
3667 //
Richard Smithb130fe72016-06-23 19:16:49 +00003668 // FIXME: Return this value to the caller so they don't need to recompute it.
3669 llvm::APSInt Value(/*BitWidth*/1);
3670 return (IsConstexpr && !CondExpr->isValueDependent())
3671 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3672 CCEK_ConstexprIf)
3673 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003674}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003675
3676/// Helper function to determine whether this is the (deprecated) C++
3677/// conversion from a string literal to a pointer to non-const char or
3678/// non-const wchar_t (for narrow and wide string literals,
3679/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003680bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003681Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3682 // Look inside the implicit cast, if it exists.
3683 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3684 From = Cast->getSubExpr();
3685
3686 // A string literal (2.13.4) that is not a wide string literal can
3687 // be converted to an rvalue of type "pointer to char"; a wide
3688 // string literal can be converted to an rvalue of type "pointer
3689 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003690 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003691 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003692 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003693 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003694 // This conversion is considered only when there is an
3695 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003696 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3697 switch (StrLit->getKind()) {
3698 case StringLiteral::UTF8:
3699 case StringLiteral::UTF16:
3700 case StringLiteral::UTF32:
3701 // We don't allow UTF literals to be implicitly converted
3702 break;
3703 case StringLiteral::Ascii:
3704 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3705 ToPointeeType->getKind() == BuiltinType::Char_S);
3706 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003707 return Context.typesAreCompatible(Context.getWideCharType(),
3708 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003709 }
3710 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003711 }
3712
3713 return false;
3714}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003715
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003717 SourceLocation CastLoc,
3718 QualType Ty,
3719 CastKind Kind,
3720 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003721 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003722 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003723 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003724 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003725 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003726 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003727 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003728 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Richard Smith72d74052013-07-20 19:41:36 +00003730 if (S.RequireNonAbstractType(CastLoc, Ty,
3731 diag::err_allocation_of_abstract_type))
3732 return ExprError();
3733
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003734 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003735 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
Richard Smith5179eb72016-06-28 19:03:57 +00003737 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3738 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003739 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003740 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003741
Richard Smithf8adcdc2014-07-17 05:12:35 +00003742 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003743 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003744 ConstructorArgs, HadMultipleCandidates,
3745 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3746 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003747 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003748 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003750 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
John McCalle3027922010-08-25 11:45:40 +00003753 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003754 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Richard Smithd3f2d322015-02-24 21:16:19 +00003756 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003757 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003758 return ExprError();
3759
Douglas Gregora4253922010-04-16 22:17:36 +00003760 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003761 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3762 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003763 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003764 if (Result.isInvalid())
3765 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003766 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003767 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3768 CK_UserDefinedConversion, Result.get(),
3769 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregor668443e2011-01-20 00:18:04 +00003771 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003772 }
3773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774}
Douglas Gregora4253922010-04-16 22:17:36 +00003775
Douglas Gregor5fb53972009-01-14 15:45:31 +00003776/// PerformImplicitConversion - Perform an implicit conversion of the
3777/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003778/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003779/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003780/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003781ExprResult
3782Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003783 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003784 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003785 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003786 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3787 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3788 return From;
3789
John McCall0d1da222010-01-12 00:44:57 +00003790 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003791 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003792 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3793 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003794 if (Res.isInvalid())
3795 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003796 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003797 break;
John Wiegley01296292011-04-08 18:41:53 +00003798 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003799
Anders Carlsson110b07b2009-09-15 06:28:28 +00003800 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003801
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003802 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003803 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003804 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003805 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003806 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003807 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Anders Carlsson110b07b2009-09-15 06:28:28 +00003809 // If the user-defined conversion is specified by a conversion function,
3810 // the initial standard conversion sequence converts the source type to
3811 // the implicit object parameter of the conversion function.
3812 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003813 } else {
3814 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003815 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003816 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003817 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003819 // initial standard conversion sequence converts the source type to
3820 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003821 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823 }
Richard Smith72d74052013-07-20 19:41:36 +00003824 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003825 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003826 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003827 PerformImplicitConversion(From, BeforeToType,
3828 ICS.UserDefined.Before, AA_Converting,
3829 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003830 if (Res.isInvalid())
3831 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003832 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003835 ExprResult CastArg = BuildCXXCastArgument(
3836 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3837 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3838 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003839
3840 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003841 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003842
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003843 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003844
Richard Smith1ef75542018-06-27 20:30:34 +00003845 // C++ [over.match.oper]p7:
3846 // [...] the second standard conversion sequence of a user-defined
3847 // conversion sequence is not applied.
3848 if (CCK == CCK_ForBuiltinOverloadedOp)
3849 return From;
3850
Richard Smith507840d2011-11-29 22:48:16 +00003851 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3852 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003853 }
John McCall0d1da222010-01-12 00:44:57 +00003854
3855 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003856 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003857 PDiag(diag::err_typecheck_ambiguous_condition)
3858 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003859 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860
Douglas Gregor39c16d42008-10-24 04:54:22 +00003861 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003862 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003863
3864 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003865 bool Diagnosed =
3866 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3867 From->getType(), From, Action);
3868 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003869 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003870 }
3871
3872 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003873 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003874}
3875
Richard Smith507840d2011-11-29 22:48:16 +00003876/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003877/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003878/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003879/// expression. Flavor is the context in which we're performing this
3880/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003881ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003882Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003883 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003884 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003885 CheckedConversionKind CCK) {
3886 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003887
Mike Stump87c57ac2009-05-16 07:39:55 +00003888 // Overall FIXME: we are recomputing too many types here and doing far too
3889 // much extra work. What this means is that we need to keep track of more
3890 // information that is computed when we try the implicit conversion initially,
3891 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003892 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003893
Douglas Gregor2fe98832008-11-03 19:09:14 +00003894 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003895 // FIXME: When can ToType be a reference type?
3896 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003897 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003898 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003899 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003900 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003901 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003902 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003903 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003904 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3905 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003906 ConstructorArgs, /*HadMultipleCandidates*/ false,
3907 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3908 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003909 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003910 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003911 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3912 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003913 From, /*HadMultipleCandidates*/ false,
3914 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3915 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003916 }
3917
Douglas Gregor980fb162010-04-29 18:24:40 +00003918 // Resolve overloaded function references.
3919 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3920 DeclAccessPair Found;
3921 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3922 true, Found);
3923 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003924 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003925
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003926 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003927 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003928
Douglas Gregor980fb162010-04-29 18:24:40 +00003929 From = FixOverloadedFunctionReference(From, Found, Fn);
3930 FromType = From->getType();
3931 }
3932
Richard Smitha23ab512013-05-23 00:30:41 +00003933 // If we're converting to an atomic type, first convert to the corresponding
3934 // non-atomic type.
3935 QualType ToAtomicType;
3936 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3937 ToAtomicType = ToType;
3938 ToType = ToAtomic->getValueType();
3939 }
3940
George Burgess IV8d141e02015-12-14 22:00:49 +00003941 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003942 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003943 switch (SCS.First) {
3944 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003945 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3946 FromType = FromAtomic->getValueType().getUnqualifiedType();
3947 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3948 From, /*BasePath=*/nullptr, VK_RValue);
3949 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003950 break;
3951
Eli Friedman946b7b52012-01-24 22:51:26 +00003952 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003953 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003954 ExprResult FromRes = DefaultLvalueConversion(From);
3955 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003956 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003957 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003958 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003959 }
John McCall34376a62010-12-04 03:47:34 +00003960
Douglas Gregor39c16d42008-10-24 04:54:22 +00003961 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003962 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003963 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003964 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003965 break;
3966
3967 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003968 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003969 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003970 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003971 break;
3972
3973 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003974 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003975 }
3976
Richard Smith507840d2011-11-29 22:48:16 +00003977 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003978 switch (SCS.Second) {
3979 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003980 // C++ [except.spec]p5:
3981 // [For] assignment to and initialization of pointers to functions,
3982 // pointers to member functions, and references to functions: the
3983 // target entity shall allow at least the exceptions allowed by the
3984 // source value in the assignment or initialization.
3985 switch (Action) {
3986 case AA_Assigning:
3987 case AA_Initializing:
3988 // Note, function argument passing and returning are initialization.
3989 case AA_Passing:
3990 case AA_Returning:
3991 case AA_Sending:
3992 case AA_Passing_CFAudited:
3993 if (CheckExceptionSpecCompatibility(From, ToType))
3994 return ExprError();
3995 break;
3996
3997 case AA_Casting:
3998 case AA_Converting:
3999 // Casts and implicit conversions are not initialization, so are not
4000 // checked for exception specification mismatches.
4001 break;
4002 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004003 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004004 break;
4005
4006 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004007 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004008 if (ToType->isBooleanType()) {
4009 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4010 SCS.Second == ICK_Integral_Promotion &&
4011 "only enums with fixed underlying type can promote to bool");
4012 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004013 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004014 } else {
4015 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004016 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004017 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004018 break;
4019
4020 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004021 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004022 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004023 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004024 break;
4025
4026 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004027 case ICK_Complex_Conversion: {
4028 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4029 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4030 CastKind CK;
4031 if (FromEl->isRealFloatingType()) {
4032 if (ToEl->isRealFloatingType())
4033 CK = CK_FloatingComplexCast;
4034 else
4035 CK = CK_FloatingComplexToIntegralComplex;
4036 } else if (ToEl->isRealFloatingType()) {
4037 CK = CK_IntegralComplexToFloatingComplex;
4038 } else {
4039 CK = CK_IntegralComplexCast;
4040 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004041 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004042 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004043 break;
John McCall8cb679e2010-11-15 09:13:47 +00004044 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004045
Douglas Gregor39c16d42008-10-24 04:54:22 +00004046 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004047 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004048 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004049 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004050 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004051 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004052 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004053 break;
4054
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004055 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004056 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004057 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004058 break;
4059
John McCall31168b02011-06-15 23:02:42 +00004060 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004061 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004062 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004063 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004064 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004065 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004066 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004067 << ToType << From->getType() << Action << From->getSourceRange()
4068 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004069 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004070 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004071 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004072 << From->getType() << ToType << Action << From->getSourceRange()
4073 << 0;
John McCall31168b02011-06-15 23:02:42 +00004074
Douglas Gregor33823722011-06-11 01:09:30 +00004075 if (From->getType()->isObjCObjectPointerType() &&
4076 ToType->isObjCObjectPointerType())
4077 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004078 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4079 !CheckObjCARCUnavailableWeakConversion(ToType,
4080 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004081 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004082 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004083 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004084 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4085 << (Action == AA_Casting) << From->getType() << ToType
4086 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004087 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004088
Richard Smith354abec2017-12-08 23:29:59 +00004089 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004090 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004091 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004092 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004093
4094 // Make sure we extend blocks if necessary.
4095 // FIXME: doing this here is really ugly.
4096 if (Kind == CK_BlockPointerToObjCPointerCast) {
4097 ExprResult E = From;
4098 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004099 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004100 }
Brian Kelley11352a82017-03-29 18:09:02 +00004101 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4102 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004103 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004104 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004105 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004108 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004109 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004110 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004111 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004112 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004113 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004114 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004115
4116 // We may not have been able to figure out what this member pointer resolved
4117 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004118 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004119 (void)isCompleteType(From->getExprLoc(), From->getType());
4120 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004121 }
David Majnemerd96b9972014-08-08 00:10:39 +00004122
Richard Smith507840d2011-11-29 22:48:16 +00004123 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004124 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004125 break;
4126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004128 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004129 // Perform half-to-boolean conversion via float.
4130 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004131 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004132 FromType = Context.FloatTy;
4133 }
4134
Richard Smith507840d2011-11-29 22:48:16 +00004135 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004136 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004137 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004138 break;
4139
Douglas Gregor88d292c2010-05-13 16:44:06 +00004140 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004141 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004142 if (CheckDerivedToBaseConversion(
4143 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4144 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004145 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004146
Richard Smith507840d2011-11-29 22:48:16 +00004147 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4148 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004149 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004150 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004151 }
4152
Douglas Gregor46188682010-05-18 22:42:18 +00004153 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004154 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004155 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004156 break;
4157
George Burgess IVdf1ed002016-01-13 01:52:39 +00004158 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004159 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004160 Expr *Elem = prepareVectorSplat(ToType, From).get();
4161 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4162 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004163 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregor46188682010-05-18 22:42:18 +00004166 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004167 // Case 1. x -> _Complex y
4168 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4169 QualType ElType = ToComplex->getElementType();
4170 bool isFloatingComplex = ElType->isRealFloatingType();
4171
4172 // x -> y
4173 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4174 // do nothing
4175 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004176 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004177 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004178 } else {
4179 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004180 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004181 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004182 }
4183 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004184 From = ImpCastExprToType(From, ToType,
4185 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004186 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004187
4188 // Case 2. _Complex x -> y
4189 } else {
4190 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4191 assert(FromComplex);
4192
4193 QualType ElType = FromComplex->getElementType();
4194 bool isFloatingComplex = ElType->isRealFloatingType();
4195
4196 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004197 From = ImpCastExprToType(From, ElType,
4198 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004199 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004200 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004201
4202 // x -> y
4203 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4204 // do nothing
4205 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004206 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004207 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004208 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004209 } else {
4210 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004211 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004212 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004213 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004214 }
4215 }
Douglas Gregor46188682010-05-18 22:42:18 +00004216 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004217
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004218 case ICK_Block_Pointer_Conversion: {
Marco Antogninid36e1302019-07-09 15:04:27 +00004219 LangAS AddrSpaceL =
Marco Antognini9eb95902019-07-17 08:52:09 +00004220 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
Marco Antogninid36e1302019-07-09 15:04:27 +00004221 LangAS AddrSpaceR =
Marco Antognini9eb95902019-07-17 08:52:09 +00004222 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4223 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4224 "Invalid cast");
Marco Antogninid36e1302019-07-09 15:04:27 +00004225 CastKind Kind =
4226 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4227 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004228 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004229 break;
4230 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004231
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004232 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004233 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004234 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004235 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4236 if (FromRes.isInvalid())
4237 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004238 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004239 assert ((ConvTy == Sema::Compatible) &&
4240 "Improper transparent union conversion");
4241 (void)ConvTy;
4242 break;
4243 }
4244
Guy Benyei259f9f42013-02-07 16:05:33 +00004245 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004246 case ICK_Zero_Queue_Conversion:
4247 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004248 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004249 From->getValueKind()).get();
4250 break;
4251
Douglas Gregor46188682010-05-18 22:42:18 +00004252 case ICK_Lvalue_To_Rvalue:
4253 case ICK_Array_To_Pointer:
4254 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004255 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004256 case ICK_Qualification:
4257 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004258 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004259 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004260 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004261 }
4262
4263 switch (SCS.Third) {
4264 case ICK_Identity:
4265 // Nothing to do.
4266 break;
4267
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004268 case ICK_Function_Conversion:
4269 // If both sides are functions (or pointers/references to them), there could
4270 // be incompatible exception declarations.
4271 if (CheckExceptionSpecCompatibility(From, ToType))
4272 return ExprError();
4273
4274 From = ImpCastExprToType(From, ToType, CK_NoOp,
4275 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4276 break;
4277
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004278 case ICK_Qualification: {
4279 // The qualification keeps the category of the inner expression, unless the
4280 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004281 ExprValueKind VK =
4282 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4283
4284 CastKind CK = CK_NoOp;
4285
4286 if (ToType->isReferenceType() &&
4287 ToType->getPointeeType().getAddressSpace() !=
4288 From->getType().getAddressSpace())
4289 CK = CK_AddressSpaceConversion;
4290
4291 if (ToType->isPointerType() &&
4292 ToType->getPointeeType().getAddressSpace() !=
4293 From->getType()->getPointeeType().getAddressSpace())
4294 CK = CK_AddressSpaceConversion;
4295
4296 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4297 /*BasePath=*/nullptr, CCK)
4298 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004299
Douglas Gregore981bb02011-03-14 16:13:32 +00004300 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004301 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004302 Diag(From->getBeginLoc(),
4303 getLangOpts().CPlusPlus11
4304 ? diag::ext_deprecated_string_literal_conversion
4305 : diag::warn_deprecated_string_literal_conversion)
4306 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004307 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004308
Douglas Gregor39c16d42008-10-24 04:54:22 +00004309 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004310 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004311
Douglas Gregor39c16d42008-10-24 04:54:22 +00004312 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004313 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004314 }
4315
Douglas Gregor298f43d2012-04-12 20:42:30 +00004316 // If this conversion sequence involved a scalar -> atomic conversion, perform
4317 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004318 if (!ToAtomicType.isNull()) {
4319 assert(Context.hasSameType(
4320 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4321 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004322 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004323 }
4324
George Burgess IV8d141e02015-12-14 22:00:49 +00004325 // If this conversion sequence succeeded and involved implicitly converting a
4326 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004327 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004328 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004329 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004330
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004331 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004332}
4333
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004334/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004335///
4336/// If the particular type trait requires a complete type, tries to complete
4337/// it. If completing the type fails, a diagnostic is emitted and false
4338/// returned. If completing the type succeeds or no completion was required,
4339/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004340static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004341 SourceLocation Loc,
4342 QualType ArgTy) {
4343 // C++0x [meta.unary.prop]p3:
4344 // For all of the class templates X declared in this Clause, instantiating
4345 // that template with a template argument that is a class template
4346 // specialization may result in the implicit instantiation of the template
4347 // argument if and only if the semantics of X require that the argument
4348 // must be a complete type.
4349 // We apply this rule to all the type trait expressions used to implement
4350 // these class templates. We also try to follow any GCC documented behavior
4351 // in these expressions to ensure portability of standard libraries.
4352 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004353 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004354 // is_complete_type somewhat obviously cannot require a complete type.
4355 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004356 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004357
4358 // These traits are modeled on the type predicates in C++0x
4359 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4360 // requiring a complete type, as whether or not they return true cannot be
4361 // impacted by the completeness of the type.
4362 case UTT_IsVoid:
4363 case UTT_IsIntegral:
4364 case UTT_IsFloatingPoint:
4365 case UTT_IsArray:
4366 case UTT_IsPointer:
4367 case UTT_IsLvalueReference:
4368 case UTT_IsRvalueReference:
4369 case UTT_IsMemberFunctionPointer:
4370 case UTT_IsMemberObjectPointer:
4371 case UTT_IsEnum:
4372 case UTT_IsUnion:
4373 case UTT_IsClass:
4374 case UTT_IsFunction:
4375 case UTT_IsReference:
4376 case UTT_IsArithmetic:
4377 case UTT_IsFundamental:
4378 case UTT_IsObject:
4379 case UTT_IsScalar:
4380 case UTT_IsCompound:
4381 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004382 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004383
4384 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4385 // which requires some of its traits to have the complete type. However,
4386 // the completeness of the type cannot impact these traits' semantics, and
4387 // so they don't require it. This matches the comments on these traits in
4388 // Table 49.
4389 case UTT_IsConst:
4390 case UTT_IsVolatile:
4391 case UTT_IsSigned:
4392 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004393
4394 // This type trait always returns false, checking the type is moot.
4395 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004396 return true;
4397
David Majnemer213bea32015-11-16 06:58:51 +00004398 // C++14 [meta.unary.prop]:
4399 // If T is a non-union class type, T shall be a complete type.
4400 case UTT_IsEmpty:
4401 case UTT_IsPolymorphic:
4402 case UTT_IsAbstract:
4403 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4404 if (!RD->isUnion())
4405 return !S.RequireCompleteType(
4406 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4407 return true;
4408
4409 // C++14 [meta.unary.prop]:
4410 // If T is a class type, T shall be a complete type.
4411 case UTT_IsFinal:
4412 case UTT_IsSealed:
4413 if (ArgTy->getAsCXXRecordDecl())
4414 return !S.RequireCompleteType(
4415 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4416 return true;
4417
Richard Smithf03e9082017-06-01 00:28:16 +00004418 // C++1z [meta.unary.prop]:
4419 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004420 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004421 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004422 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004423 case UTT_IsStandardLayout:
4424 case UTT_IsPOD:
4425 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004426 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4427 // or an array of unknown bound. But GCC actually imposes the same constraints
4428 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004429 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004430 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004431 case UTT_HasNothrowConstructor:
4432 case UTT_HasNothrowCopy:
4433 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004434 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004435 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004436 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004437 case UTT_HasTrivialCopy:
4438 case UTT_HasTrivialDestructor:
4439 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004440 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4441 LLVM_FALLTHROUGH;
4442
4443 // C++1z [meta.unary.prop]:
4444 // T shall be a complete type, cv void, or an array of unknown bound.
4445 case UTT_IsDestructible:
4446 case UTT_IsNothrowDestructible:
4447 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004448 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004449 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004450 return true;
4451
4452 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004453 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004454 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004455}
4456
Joao Matosc9523d42013-03-27 01:34:16 +00004457static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4458 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004459 bool (CXXRecordDecl::*HasTrivial)() const,
4460 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004461 bool (CXXMethodDecl::*IsDesiredOp)() const)
4462{
4463 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4464 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4465 return true;
4466
4467 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4468 DeclarationNameInfo NameInfo(Name, KeyLoc);
4469 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4470 if (Self.LookupQualifiedName(Res, RD)) {
4471 bool FoundOperator = false;
4472 Res.suppressDiagnostics();
4473 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4474 Op != OpEnd; ++Op) {
4475 if (isa<FunctionTemplateDecl>(*Op))
4476 continue;
4477
4478 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4479 if((Operator->*IsDesiredOp)()) {
4480 FoundOperator = true;
4481 const FunctionProtoType *CPT =
4482 Operator->getType()->getAs<FunctionProtoType>();
4483 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004484 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004485 return false;
4486 }
4487 }
4488 return FoundOperator;
4489 }
4490 return false;
4491}
4492
Alp Toker95e7ff22014-01-01 05:57:51 +00004493static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004494 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004495 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004496
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004497 ASTContext &C = Self.Context;
4498 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004499 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004500 // Type trait expressions corresponding to the primary type category
4501 // predicates in C++0x [meta.unary.cat].
4502 case UTT_IsVoid:
4503 return T->isVoidType();
4504 case UTT_IsIntegral:
4505 return T->isIntegralType(C);
4506 case UTT_IsFloatingPoint:
4507 return T->isFloatingType();
4508 case UTT_IsArray:
4509 return T->isArrayType();
4510 case UTT_IsPointer:
4511 return T->isPointerType();
4512 case UTT_IsLvalueReference:
4513 return T->isLValueReferenceType();
4514 case UTT_IsRvalueReference:
4515 return T->isRValueReferenceType();
4516 case UTT_IsMemberFunctionPointer:
4517 return T->isMemberFunctionPointerType();
4518 case UTT_IsMemberObjectPointer:
4519 return T->isMemberDataPointerType();
4520 case UTT_IsEnum:
4521 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004522 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004523 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004524 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004525 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004526 case UTT_IsFunction:
4527 return T->isFunctionType();
4528
4529 // Type trait expressions which correspond to the convenient composition
4530 // predicates in C++0x [meta.unary.comp].
4531 case UTT_IsReference:
4532 return T->isReferenceType();
4533 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004534 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004535 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004536 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004537 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004538 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004539 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004540 // Note: semantic analysis depends on Objective-C lifetime types to be
4541 // considered scalar types. However, such types do not actually behave
4542 // like scalar types at run time (since they may require retain/release
4543 // operations), so we report them as non-scalar.
4544 if (T->isObjCLifetimeType()) {
4545 switch (T.getObjCLifetime()) {
4546 case Qualifiers::OCL_None:
4547 case Qualifiers::OCL_ExplicitNone:
4548 return true;
4549
4550 case Qualifiers::OCL_Strong:
4551 case Qualifiers::OCL_Weak:
4552 case Qualifiers::OCL_Autoreleasing:
4553 return false;
4554 }
4555 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004556
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004557 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004558 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004559 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004560 case UTT_IsMemberPointer:
4561 return T->isMemberPointerType();
4562
4563 // Type trait expressions which correspond to the type property predicates
4564 // in C++0x [meta.unary.prop].
4565 case UTT_IsConst:
4566 return T.isConstQualified();
4567 case UTT_IsVolatile:
4568 return T.isVolatileQualified();
4569 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004570 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004571 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004572 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004573 case UTT_IsStandardLayout:
4574 return T->isStandardLayoutType();
4575 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004576 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004577 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004578 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004579 case UTT_IsEmpty:
4580 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4581 return !RD->isUnion() && RD->isEmpty();
4582 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004583 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004585 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004586 return false;
4587 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004588 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004589 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004590 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004591 case UTT_IsAggregate:
4592 // Report vector extensions and complex types as aggregates because they
4593 // support aggregate initialization. GCC mirrors this behavior for vectors
4594 // but not _Complex.
4595 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4596 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004597 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4598 // even then only when it is used with the 'interface struct ...' syntax
4599 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004600 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004601 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004602 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004603 case UTT_IsSealed:
4604 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004605 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004606 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004607 case UTT_IsSigned:
4608 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004609 case UTT_IsUnsigned:
4610 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004611
4612 // Type trait expressions which query classes regarding their construction,
4613 // destruction, and copying. Rather than being based directly on the
4614 // related type predicates in the standard, they are specified by both
4615 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4616 // specifications.
4617 //
4618 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4619 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004620 //
4621 // Note that these builtins do not behave as documented in g++: if a class
4622 // has both a trivial and a non-trivial special member of a particular kind,
4623 // they return false! For now, we emulate this behavior.
4624 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4625 // does not correctly compute triviality in the presence of multiple special
4626 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004627 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004628 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4629 // If __is_pod (type) is true then the trait is true, else if type is
4630 // a cv class or union type (or array thereof) with a trivial default
4631 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004632 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004633 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004634 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4635 return RD->hasTrivialDefaultConstructor() &&
4636 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004637 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004638 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004639 // This trait is implemented by MSVC 2012 and needed to parse the
4640 // standard library headers. Specifically this is used as the logic
4641 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004642 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004643 return true;
4644 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4645 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4646 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004647 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004648 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4649 // If __is_pod (type) is true or type is a reference type then
4650 // the trait is true, else if type is a cv class or union type
4651 // with a trivial copy constructor ([class.copy]) then the trait
4652 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004653 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004654 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004655 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4656 return RD->hasTrivialCopyConstructor() &&
4657 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004658 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004659 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004660 // This trait is implemented by MSVC 2012 and needed to parse the
4661 // standard library headers. Specifically it is used as the logic
4662 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004663 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004664 return true;
4665 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4666 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4667 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004668 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004669 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4670 // If type is const qualified or is a reference type then the
4671 // trait is false. Otherwise if __is_pod (type) is true then the
4672 // trait is true, else if type is a cv class or union type with
4673 // a trivial copy assignment ([class.copy]) then the trait is
4674 // true, else it is false.
4675 // Note: the const and reference restrictions are interesting,
4676 // given that const and reference members don't prevent a class
4677 // from having a trivial copy assignment operator (but do cause
4678 // errors if the copy assignment operator is actually used, q.v.
4679 // [class.copy]p12).
4680
Richard Smith92f241f2012-12-08 02:53:02 +00004681 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004682 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004683 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004684 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004685 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4686 return RD->hasTrivialCopyAssignment() &&
4687 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004688 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004689 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004690 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004691 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004692 // C++14 [meta.unary.prop]:
4693 // For reference types, is_destructible<T>::value is true.
4694 if (T->isReferenceType())
4695 return true;
4696
4697 // Objective-C++ ARC: autorelease types don't require destruction.
4698 if (T->isObjCLifetimeType() &&
4699 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4700 return true;
4701
4702 // C++14 [meta.unary.prop]:
4703 // For incomplete types and function types, is_destructible<T>::value is
4704 // false.
4705 if (T->isIncompleteType() || T->isFunctionType())
4706 return false;
4707
Richard Smithf03e9082017-06-01 00:28:16 +00004708 // A type that requires destruction (via a non-trivial destructor or ARC
4709 // lifetime semantics) is not trivially-destructible.
4710 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4711 return false;
4712
David Majnemerac73de92015-08-11 03:03:28 +00004713 // C++14 [meta.unary.prop]:
4714 // For object types and given U equal to remove_all_extents_t<T>, if the
4715 // expression std::declval<U&>().~U() is well-formed when treated as an
4716 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4717 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4718 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4719 if (!Destructor)
4720 return false;
4721 // C++14 [dcl.fct.def.delete]p2:
4722 // A program that refers to a deleted function implicitly or
4723 // explicitly, other than to declare it, is ill-formed.
4724 if (Destructor->isDeleted())
4725 return false;
4726 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4727 return false;
4728 if (UTT == UTT_IsNothrowDestructible) {
4729 const FunctionProtoType *CPT =
4730 Destructor->getType()->getAs<FunctionProtoType>();
4731 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004732 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004733 return false;
4734 }
4735 }
4736 return true;
4737
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004738 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004739 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004740 // If __is_pod (type) is true or type is a reference type
4741 // then the trait is true, else if type is a cv class or union
4742 // type (or array thereof) with a trivial destructor
4743 // ([class.dtor]) then the trait is true, else it is
4744 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004745 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004746 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004747
John McCall31168b02011-06-15 23:02:42 +00004748 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004749 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004750 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4751 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004752
Richard Smith92f241f2012-12-08 02:53:02 +00004753 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4754 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004755 return false;
4756 // TODO: Propagate nothrowness for implicitly declared special members.
4757 case UTT_HasNothrowAssign:
4758 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4759 // If type is const qualified or is a reference type then the
4760 // trait is false. Otherwise if __has_trivial_assign (type)
4761 // is true then the trait is true, else if type is a cv class
4762 // or union type with copy assignment operators that are known
4763 // not to throw an exception then the trait is true, else it is
4764 // false.
4765 if (C.getBaseElementType(T).isConstQualified())
4766 return false;
4767 if (T->isReferenceType())
4768 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004769 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004770 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004771
Joao Matosc9523d42013-03-27 01:34:16 +00004772 if (const RecordType *RT = T->getAs<RecordType>())
4773 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4774 &CXXRecordDecl::hasTrivialCopyAssignment,
4775 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4776 &CXXMethodDecl::isCopyAssignmentOperator);
4777 return false;
4778 case UTT_HasNothrowMoveAssign:
4779 // This trait is implemented by MSVC 2012 and needed to parse the
4780 // standard library headers. Specifically this is used as the logic
4781 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004782 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004783 return true;
4784
4785 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4786 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4787 &CXXRecordDecl::hasTrivialMoveAssignment,
4788 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4789 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004790 return false;
4791 case UTT_HasNothrowCopy:
4792 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4793 // If __has_trivial_copy (type) is true then the trait is true, else
4794 // if type is a cv class or union type with copy constructors that are
4795 // known not to throw an exception then the trait is true, else it is
4796 // false.
John McCall31168b02011-06-15 23:02:42 +00004797 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004798 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004799 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4800 if (RD->hasTrivialCopyConstructor() &&
4801 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004802 return true;
4803
4804 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004805 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004806 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004807 // A template constructor is never a copy constructor.
4808 // FIXME: However, it may actually be selected at the actual overload
4809 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004810 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004811 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004812 // UsingDecl itself is not a constructor
4813 if (isa<UsingDecl>(ND))
4814 continue;
4815 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004816 if (Constructor->isCopyConstructor(FoundTQs)) {
4817 FoundConstructor = true;
4818 const FunctionProtoType *CPT
4819 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004820 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4821 if (!CPT)
4822 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004823 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004824 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004825 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004826 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004827 }
4828 }
4829
Richard Smith938f40b2011-06-11 17:19:42 +00004830 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004831 }
4832 return false;
4833 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004834 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004835 // If __has_trivial_constructor (type) is true then the trait is
4836 // true, else if type is a cv class or union type (or array
4837 // thereof) with a default constructor that is known not to
4838 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004839 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004840 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004841 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4842 if (RD->hasTrivialDefaultConstructor() &&
4843 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004844 return true;
4845
Alp Tokerb4bca412014-01-20 00:23:47 +00004846 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004847 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004848 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004849 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004850 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004851 // UsingDecl itself is not a constructor
4852 if (isa<UsingDecl>(ND))
4853 continue;
4854 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004855 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004856 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004857 const FunctionProtoType *CPT
4858 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004859 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4860 if (!CPT)
4861 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004862 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004863 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004864 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004865 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004866 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004867 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004868 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004869 }
4870 return false;
4871 case UTT_HasVirtualDestructor:
4872 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4873 // If type is a class type with a virtual destructor ([class.dtor])
4874 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004875 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004876 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004877 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004878 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004879
4880 // These type trait expressions are modeled on the specifications for the
4881 // Embarcadero C++0x type trait functions:
4882 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4883 case UTT_IsCompleteType:
4884 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4885 // Returns True if and only if T is a complete type at the point of the
4886 // function call.
4887 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004888 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004889 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004890 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004891}
Sebastian Redl5822f082009-02-07 20:10:22 +00004892
Alp Tokercbb90342013-12-13 20:49:58 +00004893static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4894 QualType RhsT, SourceLocation KeyLoc);
4895
Douglas Gregor29c42f22012-02-24 07:38:34 +00004896static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4897 ArrayRef<TypeSourceInfo *> Args,
4898 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004899 if (Kind <= UTT_Last)
4900 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4901
Eric Fiselier1af6c112018-01-12 00:09:37 +00004902 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4903 // traits to avoid duplication.
4904 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004905 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4906 Args[1]->getType(), RParenLoc);
4907
Douglas Gregor29c42f22012-02-24 07:38:34 +00004908 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004909 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004910 case clang::TT_IsConstructible:
4911 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004912 case clang::TT_IsTriviallyConstructible: {
4913 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004914 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004915 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004916 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004917 // definition for is_constructible, as defined below, is known to call
4918 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004919 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004920 // The predicate condition for a template specialization
4921 // is_constructible<T, Args...> shall be satisfied if and only if the
4922 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004923 // variable t:
4924 //
4925 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004926 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004927
4928 // Precondition: T and all types in the parameter pack Args shall be
4929 // complete types, (possibly cv-qualified) void, or arrays of
4930 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004931 for (const auto *TSI : Args) {
4932 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004933 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004934 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004935
Simon Pilgrim75c26882016-09-30 14:25:09 +00004936 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004937 diag::err_incomplete_type_used_in_type_trait_expr))
4938 return false;
4939 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004940
David Majnemer9658ecc2015-11-13 05:32:43 +00004941 // Make sure the first argument is not incomplete nor a function type.
4942 QualType T = Args[0]->getType();
4943 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004944 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004945
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004946 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004947 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004948 if (RD && RD->isAbstract())
4949 return false;
4950
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004951 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4952 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004953 ArgExprs.reserve(Args.size() - 1);
4954 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004955 QualType ArgTy = Args[I]->getType();
4956 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4957 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004958 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004959 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004960 ArgTy.getNonLValueExprType(S.Context),
4961 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004962 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004963 for (Expr &E : OpaqueArgExprs)
4964 ArgExprs.push_back(&E);
4965
Simon Pilgrim75c26882016-09-30 14:25:09 +00004966 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004967 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004968 EnterExpressionEvaluationContext Unevaluated(
4969 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004970 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4971 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4972 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4973 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4974 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004975 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004976 if (Init.Failed())
4977 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004978
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004979 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004980 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4981 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004982
Alp Toker73287bf2014-01-20 00:24:09 +00004983 if (Kind == clang::TT_IsConstructible)
4984 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004985
Eric Fiselier1af6c112018-01-12 00:09:37 +00004986 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4987 if (!T->isReferenceType())
4988 return false;
4989
4990 return !Init.isDirectReferenceBinding();
4991 }
4992
Alp Toker73287bf2014-01-20 00:24:09 +00004993 if (Kind == clang::TT_IsNothrowConstructible)
4994 return S.canThrow(Result.get()) == CT_Cannot;
4995
4996 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004997 // Under Objective-C ARC and Weak, if the destination has non-trivial
4998 // Objective-C lifetime, this is a non-trivial construction.
4999 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005000 return false;
5001
5002 // The initialization succeeded; now make sure there are no non-trivial
5003 // calls.
5004 return !Result.get()->hasNonTrivialCall(S.Context);
5005 }
5006
5007 llvm_unreachable("unhandled type trait");
5008 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005009 }
Alp Tokercbb90342013-12-13 20:49:58 +00005010 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005011 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005012
Douglas Gregor29c42f22012-02-24 07:38:34 +00005013 return false;
5014}
5015
Simon Pilgrim75c26882016-09-30 14:25:09 +00005016ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5017 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005018 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005019 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005020
Alp Toker95e7ff22014-01-01 05:57:51 +00005021 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5022 *this, Kind, KWLoc, Args[0]->getType()))
5023 return ExprError();
5024
Douglas Gregor29c42f22012-02-24 07:38:34 +00005025 bool Dependent = false;
5026 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5027 if (Args[I]->getType()->isDependentType()) {
5028 Dependent = true;
5029 break;
5030 }
5031 }
Alp Tokercbb90342013-12-13 20:49:58 +00005032
5033 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005034 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005035 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5036
5037 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5038 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005039}
5040
Alp Toker88f64e62013-12-13 21:19:30 +00005041ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5042 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005043 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005044 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005045 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005046
Douglas Gregor29c42f22012-02-24 07:38:34 +00005047 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5048 TypeSourceInfo *TInfo;
5049 QualType T = GetTypeFromParser(Args[I], &TInfo);
5050 if (!TInfo)
5051 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005052
5053 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005054 }
Alp Tokercbb90342013-12-13 20:49:58 +00005055
Douglas Gregor29c42f22012-02-24 07:38:34 +00005056 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5057}
5058
Alp Tokercbb90342013-12-13 20:49:58 +00005059static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5060 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005061 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5062 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005063
5064 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005065 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005066 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005067 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005068 // Base and Derived are not unions and name the same class type without
5069 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005070
John McCall388ef532011-01-28 22:02:36 +00005071 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005072 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005073 if (!rhsRecord || !lhsRecord) {
5074 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5075 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5076 if (!LHSObjTy || !RHSObjTy)
5077 return false;
5078
5079 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5080 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5081 if (!BaseInterface || !DerivedInterface)
5082 return false;
5083
5084 if (Self.RequireCompleteType(
5085 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5086 return false;
5087
5088 return BaseInterface->isSuperClassOf(DerivedInterface);
5089 }
John McCall388ef532011-01-28 22:02:36 +00005090
5091 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5092 == (lhsRecord == rhsRecord));
5093
Marshall Clowce781052019-05-13 19:29:23 +00005094 // Unions are never base classes, and never have base classes.
5095 // It doesn't matter if they are complete or not. See PR#41843
5096 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5097 return false;
5098 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5099 return false;
5100
John McCall388ef532011-01-28 22:02:36 +00005101 if (lhsRecord == rhsRecord)
Marshall Clowce781052019-05-13 19:29:23 +00005102 return true;
John McCall388ef532011-01-28 22:02:36 +00005103
5104 // C++0x [meta.rel]p2:
5105 // If Base and Derived are class types and are different types
5106 // (ignoring possible cv-qualifiers) then Derived shall be a
5107 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005108 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005109 diag::err_incomplete_type_used_in_type_trait_expr))
5110 return false;
5111
5112 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5113 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5114 }
John Wiegley65497cc2011-04-27 23:09:49 +00005115 case BTT_IsSame:
5116 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005117 case BTT_TypeCompatible: {
5118 // GCC ignores cv-qualifiers on arrays for this builtin.
5119 Qualifiers LhsQuals, RhsQuals;
5120 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5121 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5122 return Self.Context.typesAreCompatible(Lhs, Rhs);
5123 }
John Wiegley65497cc2011-04-27 23:09:49 +00005124 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005125 case BTT_IsConvertibleTo: {
5126 // C++0x [meta.rel]p4:
5127 // Given the following function prototype:
5128 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005129 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005130 // typename add_rvalue_reference<T>::type create();
5131 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005132 // the predicate condition for a template specialization
5133 // is_convertible<From, To> shall be satisfied if and only if
5134 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005135 // well-formed, including any implicit conversions to the return
5136 // type of the function:
5137 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005138 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005139 // return create<From>();
5140 // }
5141 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005142 // Access checking is performed as if in a context unrelated to To and
5143 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005144 // of the return-statement (including conversions to the return type)
5145 // is considered.
5146 //
5147 // We model the initialization as a copy-initialization of a temporary
5148 // of the appropriate type, which for this expression is identical to the
5149 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005150
5151 // Functions aren't allowed to return function or array types.
5152 if (RhsT->isFunctionType() || RhsT->isArrayType())
5153 return false;
5154
5155 // A return statement in a void function must have void type.
5156 if (RhsT->isVoidType())
5157 return LhsT->isVoidType();
5158
5159 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005160 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005161 return false;
5162
5163 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005164 if (LhsT->isObjectType() || LhsT->isFunctionType())
5165 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005166
5167 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005168 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005169 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005170 Expr::getValueKindForType(LhsT));
5171 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005172 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005173 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005174
5175 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005176 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005177 EnterExpressionEvaluationContext Unevaluated(
5178 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005179 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5180 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005181 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005182 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005183 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005184
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005185 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005186 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5187 }
Alp Toker73287bf2014-01-20 00:24:09 +00005188
David Majnemerb3d96882016-05-23 17:21:55 +00005189 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005190 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005191 case BTT_IsTriviallyAssignable: {
5192 // C++11 [meta.unary.prop]p3:
5193 // is_trivially_assignable is defined as:
5194 // is_assignable<T, U>::value is true and the assignment, as defined by
5195 // is_assignable, is known to call no operation that is not trivial
5196 //
5197 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005198 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005199 // treated as an unevaluated operand (Clause 5).
5200 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005201 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005202 // void, or arrays of unknown bound.
5203 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005204 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005205 diag::err_incomplete_type_used_in_type_trait_expr))
5206 return false;
5207 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005208 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005209 diag::err_incomplete_type_used_in_type_trait_expr))
5210 return false;
5211
5212 // cv void is never assignable.
5213 if (LhsT->isVoidType() || RhsT->isVoidType())
5214 return false;
5215
Simon Pilgrim75c26882016-09-30 14:25:09 +00005216 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005217 // declval<U>().
5218 if (LhsT->isObjectType() || LhsT->isFunctionType())
5219 LhsT = Self.Context.getRValueReferenceType(LhsT);
5220 if (RhsT->isObjectType() || RhsT->isFunctionType())
5221 RhsT = Self.Context.getRValueReferenceType(RhsT);
5222 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5223 Expr::getValueKindForType(LhsT));
5224 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5225 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005226
5227 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005228 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005229 EnterExpressionEvaluationContext Unevaluated(
5230 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005231 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005232 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005233 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5234 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005235 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5236 return false;
5237
David Majnemerb3d96882016-05-23 17:21:55 +00005238 if (BTT == BTT_IsAssignable)
5239 return true;
5240
Alp Toker73287bf2014-01-20 00:24:09 +00005241 if (BTT == BTT_IsNothrowAssignable)
5242 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005243
Alp Toker73287bf2014-01-20 00:24:09 +00005244 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005245 // Under Objective-C ARC and Weak, if the destination has non-trivial
5246 // Objective-C lifetime, this is a non-trivial assignment.
5247 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005248 return false;
5249
5250 return !Result.get()->hasNonTrivialCall(Self.Context);
5251 }
5252
5253 llvm_unreachable("unhandled type trait");
5254 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005255 }
Alp Tokercbb90342013-12-13 20:49:58 +00005256 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005257 }
5258 llvm_unreachable("Unknown type trait or not implemented");
5259}
5260
John Wiegley6242b6a2011-04-28 00:16:57 +00005261ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5262 SourceLocation KWLoc,
5263 ParsedType Ty,
5264 Expr* DimExpr,
5265 SourceLocation RParen) {
5266 TypeSourceInfo *TSInfo;
5267 QualType T = GetTypeFromParser(Ty, &TSInfo);
5268 if (!TSInfo)
5269 TSInfo = Context.getTrivialTypeSourceInfo(T);
5270
5271 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5272}
5273
5274static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5275 QualType T, Expr *DimExpr,
5276 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005277 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005278
5279 switch(ATT) {
5280 case ATT_ArrayRank:
5281 if (T->isArrayType()) {
5282 unsigned Dim = 0;
5283 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5284 ++Dim;
5285 T = AT->getElementType();
5286 }
5287 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005288 }
John Wiegleyd3522222011-04-28 02:06:46 +00005289 return 0;
5290
John Wiegley6242b6a2011-04-28 00:16:57 +00005291 case ATT_ArrayExtent: {
5292 llvm::APSInt Value;
5293 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005294 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005295 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005296 false).isInvalid())
5297 return 0;
5298 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005299 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5300 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005301 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005302 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005303 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005304
5305 if (T->isArrayType()) {
5306 unsigned D = 0;
5307 bool Matched = false;
5308 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5309 if (Dim == D) {
5310 Matched = true;
5311 break;
5312 }
5313 ++D;
5314 T = AT->getElementType();
5315 }
5316
John Wiegleyd3522222011-04-28 02:06:46 +00005317 if (Matched && T->isArrayType()) {
5318 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5319 return CAT->getSize().getLimitedValue();
5320 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005321 }
John Wiegleyd3522222011-04-28 02:06:46 +00005322 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005323 }
5324 }
5325 llvm_unreachable("Unknown type trait or not implemented");
5326}
5327
5328ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5329 SourceLocation KWLoc,
5330 TypeSourceInfo *TSInfo,
5331 Expr* DimExpr,
5332 SourceLocation RParen) {
5333 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005334
Chandler Carruthc5276e52011-05-01 08:48:21 +00005335 // FIXME: This should likely be tracked as an APInt to remove any host
5336 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005337 uint64_t Value = 0;
5338 if (!T->isDependentType())
5339 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5340
Chandler Carruthc5276e52011-05-01 08:48:21 +00005341 // While the specification for these traits from the Embarcadero C++
5342 // compiler's documentation says the return type is 'unsigned int', Clang
5343 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5344 // compiler, there is no difference. On several other platforms this is an
5345 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005346 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5347 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005348}
5349
John Wiegleyf9f65842011-04-25 06:54:41 +00005350ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005351 SourceLocation KWLoc,
5352 Expr *Queried,
5353 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005354 // If error parsing the expression, ignore.
5355 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005356 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005357
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005358 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005359
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005360 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005361}
5362
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005363static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5364 switch (ET) {
5365 case ET_IsLValueExpr: return E->isLValue();
5366 case ET_IsRValueExpr: return E->isRValue();
5367 }
5368 llvm_unreachable("Expression trait not covered by switch");
5369}
5370
John Wiegleyf9f65842011-04-25 06:54:41 +00005371ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005372 SourceLocation KWLoc,
5373 Expr *Queried,
5374 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005375 if (Queried->isTypeDependent()) {
5376 // Delay type-checking for type-dependent expressions.
5377 } else if (Queried->getType()->isPlaceholderType()) {
5378 ExprResult PE = CheckPlaceholderExpr(Queried);
5379 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005380 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005381 }
5382
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005383 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005384
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005385 return new (Context)
5386 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005387}
5388
Richard Trieu82402a02011-09-15 21:56:47 +00005389QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005390 ExprValueKind &VK,
5391 SourceLocation Loc,
5392 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005393 assert(!LHS.get()->getType()->isPlaceholderType() &&
5394 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005395 "placeholders should have been weeded out by now");
5396
Richard Smith4baaa5a2016-12-03 01:14:32 +00005397 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5398 // temporary materialization conversion otherwise.
5399 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005400 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005401 else if (LHS.get()->isRValue())
5402 LHS = TemporaryMaterializationConversion(LHS.get());
5403 if (LHS.isInvalid())
5404 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005405
5406 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005407 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005408 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005409
Sebastian Redl5822f082009-02-07 20:10:22 +00005410 const char *OpSpelling = isIndirect ? "->*" : ".*";
5411 // C++ 5.5p2
5412 // The binary operator .* [p3: ->*] binds its second operand, which shall
5413 // be of type "pointer to member of T" (where T is a completely-defined
5414 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005415 QualType RHSType = RHS.get()->getType();
5416 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005417 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005418 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005419 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005420 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005421 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005422
Sebastian Redl5822f082009-02-07 20:10:22 +00005423 QualType Class(MemPtr->getClass(), 0);
5424
Douglas Gregord07ba342010-10-13 20:41:14 +00005425 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5426 // member pointer points must be completely-defined. However, there is no
5427 // reason for this semantic distinction, and the rule is not enforced by
5428 // other compilers. Therefore, we do not check this property, as it is
5429 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005430
Sebastian Redl5822f082009-02-07 20:10:22 +00005431 // C++ 5.5p2
5432 // [...] to its first operand, which shall be of class T or of a class of
5433 // which T is an unambiguous and accessible base class. [p3: a pointer to
5434 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005435 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005436 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005437 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5438 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005439 else {
5440 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005441 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005442 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005443 return QualType();
5444 }
5445 }
5446
Richard Trieu82402a02011-09-15 21:56:47 +00005447 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005448 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005449 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5450 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005451 return QualType();
5452 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005453
Richard Smith0f59cb32015-12-18 21:45:41 +00005454 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005455 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005456 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005457 return QualType();
5458 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005459
5460 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005461 if (CheckDerivedToBaseConversion(
5462 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005463 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005464 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005465 return QualType();
5466
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005467 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005468 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5469 if (isIndirect)
5470 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005471 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005472 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005473 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005474 }
5475
Richard Trieu82402a02011-09-15 21:56:47 +00005476 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005477 // Diagnose use of pointer-to-member type which when used as
5478 // the functional cast in a pointer-to-member expression.
5479 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5480 return QualType();
5481 }
John McCall7decc9e2010-11-18 06:31:45 +00005482
Sebastian Redl5822f082009-02-07 20:10:22 +00005483 // C++ 5.5p2
5484 // The result is an object or a function of the type specified by the
5485 // second operand.
5486 // The cv qualifiers are the union of those in the pointer and the left side,
5487 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005488 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005489 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005490
Douglas Gregor1d042092011-01-26 16:40:18 +00005491 // C++0x [expr.mptr.oper]p6:
5492 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493 // ill-formed if the second operand is a pointer to member function with
5494 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5495 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005496 // is a pointer to member function with ref-qualifier &&.
5497 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5498 switch (Proto->getRefQualifier()) {
5499 case RQ_None:
5500 // Do nothing
5501 break;
5502
5503 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005504 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005505 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5506 // is (exactly) 'const'.
5507 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005508 Diag(Loc, getLangOpts().CPlusPlus2a
5509 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5510 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5511 else
5512 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5513 << RHSType << 1 << LHS.get()->getSourceRange();
5514 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005515 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005516
Douglas Gregor1d042092011-01-26 16:40:18 +00005517 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005518 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005519 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005520 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005521 break;
5522 }
5523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
John McCall7decc9e2010-11-18 06:31:45 +00005525 // C++ [expr.mptr.oper]p6:
5526 // The result of a .* expression whose second operand is a pointer
5527 // to a data member is of the same value category as its
5528 // first operand. The result of a .* expression whose second
5529 // operand is a pointer to a member function is a prvalue. The
5530 // result of an ->* expression is an lvalue if its second operand
5531 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005532 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005533 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005534 return Context.BoundMemberTy;
5535 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005536 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005537 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005538 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005539 }
John McCall7decc9e2010-11-18 06:31:45 +00005540
Sebastian Redl5822f082009-02-07 20:10:22 +00005541 return Result;
5542}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005543
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005544/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005545///
5546/// This is part of the parameter validation for the ? operator. If either
5547/// value operand is a class type, the two operands are attempted to be
5548/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005549/// It returns true if the program is ill-formed and has already been diagnosed
5550/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005551static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5552 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005553 bool &HaveConversion,
5554 QualType &ToType) {
5555 HaveConversion = false;
5556 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005557
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005558 InitializationKind Kind =
5559 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005560 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005561 // The process for determining whether an operand expression E1 of type T1
5562 // can be converted to match an operand expression E2 of type T2 is defined
5563 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005564 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5565 // implicitly converted to type "lvalue reference to T2", subject to the
5566 // constraint that in the conversion the reference must bind directly to
5567 // an lvalue.
5568 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005569 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005570 // the constraint that the reference must bind directly.
5571 if (To->isLValue() || To->isXValue()) {
5572 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5573 : Self.Context.getRValueReferenceType(ToType);
5574
Douglas Gregor838fcc32010-03-26 20:14:36 +00005575 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005577 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005578 if (InitSeq.isDirectReferenceBinding()) {
5579 ToType = T;
5580 HaveConversion = true;
5581 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005583
Douglas Gregor838fcc32010-03-26 20:14:36 +00005584 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005585 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005586 }
John McCall65eb8792010-02-25 01:37:24 +00005587
Sebastian Redl1a99f442009-04-16 17:51:27 +00005588 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5589 // -- if E1 and E2 have class type, and the underlying class types are
5590 // the same or one is a base class of the other:
5591 QualType FTy = From->getType();
5592 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005593 const RecordType *FRec = FTy->getAs<RecordType>();
5594 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005596 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5597 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5598 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005599 // E1 can be converted to match E2 if the class of T2 is the
5600 // same type as, or a base class of, the class of T1, and
5601 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005602 if (FRec == TRec || FDerivedFromT) {
5603 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005604 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005605 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005606 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005607 HaveConversion = true;
5608 return false;
5609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610
Douglas Gregor838fcc32010-03-26 20:14:36 +00005611 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005612 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615
Douglas Gregor838fcc32010-03-26 20:14:36 +00005616 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618
Douglas Gregor838fcc32010-03-26 20:14:36 +00005619 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5620 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005622 // an rvalue).
5623 //
5624 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5625 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005626 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627
Douglas Gregor838fcc32010-03-26 20:14:36 +00005628 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005629 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005630 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005631 ToType = TTy;
5632 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005633 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005634
Sebastian Redl1a99f442009-04-16 17:51:27 +00005635 return false;
5636}
5637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005638/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005639///
5640/// This is part of the parameter validation for the ? operator. If either
5641/// value operand is a class type, overload resolution is used to find a
5642/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005643static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005644 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005645 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005646 OverloadCandidateSet CandidateSet(QuestionLoc,
5647 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005648 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005649 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005650
5651 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005652 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005653 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005654 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005655 ExprResult LHSRes = Self.PerformImplicitConversion(
5656 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5657 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005658 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005659 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005660 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005661
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005662 ExprResult RHSRes = Self.PerformImplicitConversion(
5663 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5664 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005665 if (RHSRes.isInvalid())
5666 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005667 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005668 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005669 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005670 return false;
John Wiegley01296292011-04-08 18:41:53 +00005671 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005672
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005673 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005674
5675 // Emit a better diagnostic if one of the expressions is a null pointer
5676 // constant and the other is a pointer type. In this case, the user most
5677 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005678 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005679 return true;
5680
5681 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005682 << LHS.get()->getType() << RHS.get()->getType()
5683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005684 return true;
5685
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005686 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005687 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005688 << LHS.get()->getType() << RHS.get()->getType()
5689 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005690 // FIXME: Print the possible common types by printing the return types of
5691 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005692 break;
5693
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005694 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005695 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005696 }
5697 return true;
5698}
5699
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005700/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005701/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005702static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005703 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005704 InitializationKind Kind =
5705 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005706 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005707 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005708 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005709 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005710 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
John Wiegley01296292011-04-08 18:41:53 +00005712 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005713 return false;
5714}
5715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005716/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005717///
5718/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5719/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005720QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5721 ExprResult &RHS, ExprValueKind &VK,
5722 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005723 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005724 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5725 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005726
Richard Smith45edb702012-08-07 22:06:48 +00005727 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005728 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005729 //
5730 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5731 // a is that of a integer vector with the same number of elements and
5732 // size as the vectors of b and c. If one of either b or c is a scalar
5733 // it is implicitly converted to match the type of the vector.
5734 // Otherwise the expression is ill-formed. If both b and c are scalars,
5735 // then b and c are checked and converted to the type of a if possible.
5736 // Unlike the OpenCL ?: operator, the expression is evaluated as
5737 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005738 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005739 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005740 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005741 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005742 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005743 }
5744
John McCall7decc9e2010-11-18 06:31:45 +00005745 // Assume r-value.
5746 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005747 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005748
Sebastian Redl1a99f442009-04-16 17:51:27 +00005749 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005750 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005751 return Context.DependentTy;
5752
Richard Smith45edb702012-08-07 22:06:48 +00005753 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005754 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005755 QualType LTy = LHS.get()->getType();
5756 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005757 bool LVoid = LTy->isVoidType();
5758 bool RVoid = RTy->isVoidType();
5759 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005760 // ... one of the following shall hold:
5761 // -- The second or the third operand (but not both) is a (possibly
5762 // parenthesized) throw-expression; the result is of the type
5763 // and value category of the other.
5764 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5765 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5766 if (LThrow != RThrow) {
5767 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5768 VK = NonThrow->getValueKind();
5769 // DR (no number yet): the result is a bit-field if the
5770 // non-throw-expression operand is a bit-field.
5771 OK = NonThrow->getObjectKind();
5772 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005773 }
5774
Sebastian Redl1a99f442009-04-16 17:51:27 +00005775 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005776 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005777 if (LVoid && RVoid)
5778 return Context.VoidTy;
5779
5780 // Neither holds, error.
5781 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5782 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005783 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005784 return QualType();
5785 }
5786
5787 // Neither is void.
5788
Richard Smithf2b084f2012-08-08 06:13:49 +00005789 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005790 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005791 // either has (cv) class type [...] an attempt is made to convert each of
5792 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005793 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005794 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005795 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005796 QualType L2RType, R2LType;
5797 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005798 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005799 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005800 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005801 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802
Sebastian Redl1a99f442009-04-16 17:51:27 +00005803 // If both can be converted, [...] the program is ill-formed.
5804 if (HaveL2R && HaveR2L) {
5805 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005806 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005807 return QualType();
5808 }
5809
5810 // If exactly one conversion is possible, that conversion is applied to
5811 // the chosen operand and the converted operands are used in place of the
5812 // original operands for the remainder of this section.
5813 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005814 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005815 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005816 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005817 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005818 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005819 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005820 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005821 }
5822 }
5823
Richard Smithf2b084f2012-08-08 06:13:49 +00005824 // C++11 [expr.cond]p3
5825 // if both are glvalues of the same value category and the same type except
5826 // for cv-qualification, an attempt is made to convert each of those
5827 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005828 // FIXME:
5829 // Resolving a defect in P0012R1: we extend this to cover all cases where
5830 // one of the operands is reference-compatible with the other, in order
5831 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005832 ExprValueKind LVK = LHS.get()->getValueKind();
5833 ExprValueKind RVK = RHS.get()->getValueKind();
5834 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005835 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005836 // DerivedToBase was already handled by the class-specific case above.
5837 // FIXME: Should we allow ObjC conversions here?
5838 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5839 if (CompareReferenceRelationship(
5840 QuestionLoc, LTy, RTy, DerivedToBase,
5841 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005842 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5843 // [...] subject to the constraint that the reference must bind
5844 // directly [...]
5845 !RHS.get()->refersToBitField() &&
5846 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005847 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005848 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005849 } else if (CompareReferenceRelationship(
5850 QuestionLoc, RTy, LTy, DerivedToBase,
5851 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005852 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5853 !LHS.get()->refersToBitField() &&
5854 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005855 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5856 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005857 }
5858 }
5859
5860 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005861 // If the second and third operands are glvalues of the same value
5862 // category and have the same type, the result is of that type and
5863 // value category and it is a bit-field if the second or the third
5864 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005865 // We only extend this to bitfields, not to the crazy other kinds of
5866 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005867 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005868 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005869 LHS.get()->isOrdinaryOrBitFieldObject() &&
5870 RHS.get()->isOrdinaryOrBitFieldObject()) {
5871 VK = LHS.get()->getValueKind();
5872 if (LHS.get()->getObjectKind() == OK_BitField ||
5873 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005874 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005875
5876 // If we have function pointer types, unify them anyway to unify their
5877 // exception specifications, if any.
5878 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5879 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005880 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005881 /*ConvertArgs*/false);
5882 LTy = Context.getQualifiedType(LTy, Qs);
5883
5884 assert(!LTy.isNull() && "failed to find composite pointer type for "
5885 "canonically equivalent function ptr types");
5886 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5887 }
5888
John McCall7decc9e2010-11-18 06:31:45 +00005889 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005890 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005891
Richard Smithf2b084f2012-08-08 06:13:49 +00005892 // C++11 [expr.cond]p5
5893 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005894 // do not have the same type, and either has (cv) class type, ...
5895 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5896 // ... overload resolution is used to determine the conversions (if any)
5897 // to be applied to the operands. If the overload resolution fails, the
5898 // program is ill-formed.
5899 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5900 return QualType();
5901 }
5902
Richard Smithf2b084f2012-08-08 06:13:49 +00005903 // C++11 [expr.cond]p6
5904 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005905 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005906 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5907 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005908 if (LHS.isInvalid() || RHS.isInvalid())
5909 return QualType();
5910 LTy = LHS.get()->getType();
5911 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005912
5913 // After those conversions, one of the following shall hold:
5914 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005915 // is of that type. If the operands have class type, the result
5916 // is a prvalue temporary of the result type, which is
5917 // copy-initialized from either the second operand or the third
5918 // operand depending on the value of the first operand.
5919 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5920 if (LTy->isRecordType()) {
5921 // The operands have class type. Make a temporary copy.
5922 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005923
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005924 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5925 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005926 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005927 if (LHSCopy.isInvalid())
5928 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929
5930 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5931 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005932 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005933 if (RHSCopy.isInvalid())
5934 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935
John Wiegley01296292011-04-08 18:41:53 +00005936 LHS = LHSCopy;
5937 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005938 }
5939
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005940 // If we have function pointer types, unify them anyway to unify their
5941 // exception specifications, if any.
5942 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5943 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5944 assert(!LTy.isNull() && "failed to find composite pointer type for "
5945 "canonically equivalent function ptr types");
5946 }
5947
Sebastian Redl1a99f442009-04-16 17:51:27 +00005948 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005949 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005950
Douglas Gregor46188682010-05-18 22:42:18 +00005951 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005952 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005953 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5954 /*AllowBothBool*/true,
5955 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005956
Sebastian Redl1a99f442009-04-16 17:51:27 +00005957 // -- The second and third operands have arithmetic or enumeration type;
5958 // the usual arithmetic conversions are performed to bring them to a
5959 // common type, and the result is of that type.
5960 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005961 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005962 if (LHS.isInvalid() || RHS.isInvalid())
5963 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005964 if (ResTy.isNull()) {
5965 Diag(QuestionLoc,
5966 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5967 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5968 return QualType();
5969 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005970
5971 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5972 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5973
5974 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005975 }
5976
5977 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005978 // type and the other is a null pointer constant, or both are null
5979 // pointer constants, at least one of which is non-integral; pointer
5980 // conversions and qualification conversions are performed to bring them
5981 // to their composite pointer type. The result is of the composite
5982 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005983 // -- The second and third operands have pointer to member type, or one has
5984 // pointer to member type and the other is a null pointer constant;
5985 // pointer to member conversions and qualification conversions are
5986 // performed to bring them to a common type, whose cv-qualification
5987 // shall match the cv-qualification of either the second or the third
5988 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005989 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5990 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005991 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005992
Douglas Gregor697a3912010-04-01 22:47:07 +00005993 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005994 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5995 if (!Composite.isNull())
5996 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005997
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005998 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005999 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006000 return QualType();
6001
Sebastian Redl1a99f442009-04-16 17:51:27 +00006002 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006003 << LHS.get()->getType() << RHS.get()->getType()
6004 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006005 return QualType();
6006}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006007
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006008static FunctionProtoType::ExceptionSpecInfo
6009mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6010 FunctionProtoType::ExceptionSpecInfo ESI2,
6011 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6012 ExceptionSpecificationType EST1 = ESI1.Type;
6013 ExceptionSpecificationType EST2 = ESI2.Type;
6014
6015 // If either of them can throw anything, that is the result.
6016 if (EST1 == EST_None) return ESI1;
6017 if (EST2 == EST_None) return ESI2;
6018 if (EST1 == EST_MSAny) return ESI1;
6019 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006020 if (EST1 == EST_NoexceptFalse) return ESI1;
6021 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006022
6023 // If either of them is non-throwing, the result is the other.
Erich Keaned02f4a12019-05-30 17:31:54 +00006024 if (EST1 == EST_NoThrow) return ESI2;
6025 if (EST2 == EST_NoThrow) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006026 if (EST1 == EST_DynamicNone) return ESI2;
6027 if (EST2 == EST_DynamicNone) return ESI1;
6028 if (EST1 == EST_BasicNoexcept) return ESI2;
6029 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006030 if (EST1 == EST_NoexceptTrue) return ESI2;
6031 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006032
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006033 // If we're left with value-dependent computed noexcept expressions, we're
6034 // stuck. Before C++17, we can just drop the exception specification entirely,
6035 // since it's not actually part of the canonical type. And this should never
6036 // happen in C++17, because it would mean we were computing the composite
6037 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006038 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006039 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006040 "computing composite pointer type of dependent types");
6041 return FunctionProtoType::ExceptionSpecInfo();
6042 }
6043
6044 // Switch over the possibilities so that people adding new values know to
6045 // update this function.
6046 switch (EST1) {
6047 case EST_None:
6048 case EST_DynamicNone:
6049 case EST_MSAny:
6050 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006051 case EST_DependentNoexcept:
6052 case EST_NoexceptFalse:
6053 case EST_NoexceptTrue:
Erich Keaned02f4a12019-05-30 17:31:54 +00006054 case EST_NoThrow:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006055 llvm_unreachable("handled above");
6056
6057 case EST_Dynamic: {
6058 // This is the fun case: both exception specifications are dynamic. Form
6059 // the union of the two lists.
6060 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6061 llvm::SmallPtrSet<QualType, 8> Found;
6062 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6063 for (QualType E : Exceptions)
6064 if (Found.insert(S.Context.getCanonicalType(E)).second)
6065 ExceptionTypeStorage.push_back(E);
6066
6067 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6068 Result.Exceptions = ExceptionTypeStorage;
6069 return Result;
6070 }
6071
6072 case EST_Unevaluated:
6073 case EST_Uninstantiated:
6074 case EST_Unparsed:
6075 llvm_unreachable("shouldn't see unresolved exception specifications here");
6076 }
6077
6078 llvm_unreachable("invalid ExceptionSpecificationType");
6079}
6080
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006081/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006082///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006083/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006084/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006085/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006086/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006087///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006088/// \param Loc The location of the operator requiring these two expressions to
6089/// be converted to the composite pointer type.
6090///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006091/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006093 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006094 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006095 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006096
6097 // C++1z [expr]p14:
6098 // The composite pointer type of two operands p1 and p2 having types T1
6099 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006100 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006101
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006102 // where at least one is a pointer or pointer to member type or
6103 // std::nullptr_t is:
6104 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6105 T1->isNullPtrType();
6106 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6107 T2->isNullPtrType();
6108 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006109 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006110
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006111 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6112 // This can't actually happen, following the standard, but we also use this
6113 // to implement the end of [expr.conv], which hits this case.
6114 //
6115 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6116 if (T1IsPointerLike &&
6117 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006118 if (ConvertArgs)
6119 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6120 ? CK_NullToMemberPointer
6121 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006122 return T1;
6123 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006124 if (T2IsPointerLike &&
6125 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006126 if (ConvertArgs)
6127 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6128 ? CK_NullToMemberPointer
6129 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006130 return T2;
6131 }
Mike Stump11289f42009-09-09 15:08:12 +00006132
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006133 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006134 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006135 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006136 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6137 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006138
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006139 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6140 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6141 // the union of cv1 and cv2;
6142 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6143 // "pointer to function", where the function types are otherwise the same,
6144 // "pointer to function";
6145 // FIXME: This rule is defective: it should also permit removing noexcept
6146 // from a pointer to member function. As a Clang extension, we also
6147 // permit removing 'noreturn', so we generalize this rule to;
6148 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6149 // "pointer to member function" and the pointee types can be unified
6150 // by a function pointer conversion, that conversion is applied
6151 // before checking the following rules.
6152 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6153 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6154 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6155 // respectively;
6156 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6157 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6158 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6159 // T1 or the cv-combined type of T1 and T2, respectively;
6160 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6161 // T2;
6162 //
6163 // If looked at in the right way, these bullets all do the same thing.
6164 // What we do here is, we build the two possible cv-combined types, and try
6165 // the conversions in both directions. If only one works, or if the two
6166 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006167 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006168 //
6169 // Note that this will fail to find a composite pointer type for "pointer
6170 // to void" and "pointer to function". We can't actually perform the final
6171 // conversion in this case, even though a composite pointer type formally
6172 // exists.
6173 SmallVector<unsigned, 4> QualifierUnion;
6174 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006175 QualType Composite1 = T1;
6176 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006177 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006178 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006179 const PointerType *Ptr1, *Ptr2;
6180 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6181 (Ptr2 = Composite2->getAs<PointerType>())) {
6182 Composite1 = Ptr1->getPointeeType();
6183 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006184
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006185 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006186 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006187 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006188 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006189
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006190 QualifierUnion.push_back(
6191 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006192 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006193 continue;
6194 }
Mike Stump11289f42009-09-09 15:08:12 +00006195
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006196 const MemberPointerType *MemPtr1, *MemPtr2;
6197 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6198 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6199 Composite1 = MemPtr1->getPointeeType();
6200 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006201
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006202 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006203 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006204 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006205 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006207 QualifierUnion.push_back(
6208 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6209 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6210 MemPtr2->getClass()));
6211 continue;
6212 }
Mike Stump11289f42009-09-09 15:08:12 +00006213
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006214 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006215
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006216 // Cannot unwrap any more types.
6217 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006218 }
Mike Stump11289f42009-09-09 15:08:12 +00006219
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006220 // Apply the function pointer conversion to unify the types. We've already
6221 // unwrapped down to the function types, and we want to merge rather than
6222 // just convert, so do this ourselves rather than calling
6223 // IsFunctionConversion.
6224 //
6225 // FIXME: In order to match the standard wording as closely as possible, we
6226 // currently only do this under a single level of pointers. Ideally, we would
6227 // allow this in general, and set NeedConstBefore to the relevant depth on
6228 // the side(s) where we changed anything.
6229 if (QualifierUnion.size() == 1) {
6230 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6231 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6232 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6233 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6234
6235 // The result is noreturn if both operands are.
6236 bool Noreturn =
6237 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6238 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6239 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6240
6241 // The result is nothrow if both operands are.
6242 SmallVector<QualType, 8> ExceptionTypeStorage;
6243 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6244 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6245 ExceptionTypeStorage);
6246
6247 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6248 FPT1->getParamTypes(), EPI1);
6249 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6250 FPT2->getParamTypes(), EPI2);
6251 }
6252 }
6253 }
6254
Richard Smith5e9746f2016-10-21 22:00:42 +00006255 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006256 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006258 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006259 for (unsigned I = 0; I != NeedConstBefore; ++I)
6260 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006261 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006264 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006265 auto MOC = MemberOfClass.rbegin();
6266 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6267 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6268 auto Classes = *MOC++;
6269 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006270 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006271 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006272 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006273 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006274 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006275 } else {
6276 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006277 Composite1 =
6278 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6279 Composite2 =
6280 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006281 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006282 }
6283
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006284 struct Conversion {
6285 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006286 Expr *&E1, *&E2;
6287 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006288 InitializedEntity Entity;
6289 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006290 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006291 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006292
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006293 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6294 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006295 : S(S), E1(E1), E2(E2), Composite(Composite),
6296 Entity(InitializedEntity::InitializeTemporary(Composite)),
6297 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6298 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6299 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006300
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006301 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006302 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6303 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006304 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006305 E1 = E1Result.getAs<Expr>();
6306
6307 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6308 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006309 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006310 E2 = E2Result.getAs<Expr>();
6311
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006312 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006313 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006314 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006315
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006316 // Try to convert to each composite pointer type.
6317 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006318 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6319 if (ConvertArgs && C1.perform())
6320 return QualType();
6321 return C1.Composite;
6322 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006323 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006324
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006325 if (C1.Viable == C2.Viable) {
6326 // Either Composite1 and Composite2 are viable and are different, or
6327 // neither is viable.
6328 // FIXME: How both be viable and different?
6329 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006330 }
6331
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006332 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006333 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6334 return QualType();
6335
6336 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006337}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006338
John McCalldadc5752010-08-24 06:29:42 +00006339ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006340 if (!E)
6341 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006342
John McCall31168b02011-06-15 23:02:42 +00006343 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6344
6345 // If the result is a glvalue, we shouldn't bind it.
6346 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006347 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006348
John McCall31168b02011-06-15 23:02:42 +00006349 // In ARC, calls that return a retainable type can return retained,
6350 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006351 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006352 E->getType()->isObjCRetainableType()) {
6353
6354 bool ReturnsRetained;
6355
6356 // For actual calls, we compute this by examining the type of the
6357 // called value.
6358 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6359 Expr *Callee = Call->getCallee()->IgnoreParens();
6360 QualType T = Callee->getType();
6361
6362 if (T == Context.BoundMemberTy) {
6363 // Handle pointer-to-members.
6364 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6365 T = BinOp->getRHS()->getType();
6366 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6367 T = Mem->getMemberDecl()->getType();
6368 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006369
John McCall31168b02011-06-15 23:02:42 +00006370 if (const PointerType *Ptr = T->getAs<PointerType>())
6371 T = Ptr->getPointeeType();
6372 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6373 T = Ptr->getPointeeType();
6374 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6375 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006376
John McCall31168b02011-06-15 23:02:42 +00006377 const FunctionType *FTy = T->getAs<FunctionType>();
6378 assert(FTy && "call to value not of function type?");
6379 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6380
6381 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6382 // type always produce a +1 object.
6383 } else if (isa<StmtExpr>(E)) {
6384 ReturnsRetained = true;
6385
Ted Kremeneke65b0862012-03-06 20:05:56 +00006386 // We hit this case with the lambda conversion-to-block optimization;
6387 // we don't want any extra casts here.
6388 } else if (isa<CastExpr>(E) &&
6389 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006390 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006391
John McCall31168b02011-06-15 23:02:42 +00006392 // For message sends and property references, we try to find an
6393 // actual method. FIXME: we should infer retention by selector in
6394 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006395 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006396 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006397 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6398 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006399 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6400 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006401 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006402 // Don't do reclaims if we're using the zero-element array
6403 // constant.
6404 if (ArrayLit->getNumElements() == 0 &&
6405 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6406 return E;
6407
Ted Kremeneke65b0862012-03-06 20:05:56 +00006408 D = ArrayLit->getArrayWithObjectsMethod();
6409 } else if (ObjCDictionaryLiteral *DictLit
6410 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006411 // Don't do reclaims if we're using the zero-element dictionary
6412 // constant.
6413 if (DictLit->getNumElements() == 0 &&
6414 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6415 return E;
6416
Ted Kremeneke65b0862012-03-06 20:05:56 +00006417 D = DictLit->getDictWithObjectsMethod();
6418 }
John McCall31168b02011-06-15 23:02:42 +00006419
6420 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006421
6422 // Don't do reclaims on performSelector calls; despite their
6423 // return type, the invoked method doesn't necessarily actually
6424 // return an object.
6425 if (!ReturnsRetained &&
6426 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006427 return E;
John McCall31168b02011-06-15 23:02:42 +00006428 }
6429
John McCall16de4d22011-11-14 19:53:16 +00006430 // Don't reclaim an object of Class type.
6431 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006432 return E;
John McCall16de4d22011-11-14 19:53:16 +00006433
Tim Shen4a05bb82016-06-21 20:29:17 +00006434 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006435
John McCall2d637d22011-09-10 06:18:15 +00006436 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6437 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006438 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6439 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006440 }
6441
David Blaikiebbafb8a2012-03-11 07:00:24 +00006442 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006443 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006444
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006445 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6446 // a fast path for the common case that the type is directly a RecordType.
6447 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006448 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006449 while (!RT) {
6450 switch (T->getTypeClass()) {
6451 case Type::Record:
6452 RT = cast<RecordType>(T);
6453 break;
6454 case Type::ConstantArray:
6455 case Type::IncompleteArray:
6456 case Type::VariableArray:
6457 case Type::DependentSizedArray:
6458 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6459 break;
6460 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006461 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006462 }
6463 }
Mike Stump11289f42009-09-09 15:08:12 +00006464
Richard Smithfd555f62012-02-22 02:04:18 +00006465 // That should be enough to guarantee that this type is complete, if we're
6466 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006467 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006468 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006469 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006470
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006471 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6472 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006473 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006474
John McCall31168b02011-06-15 23:02:42 +00006475 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006476 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006477 CheckDestructorAccess(E->getExprLoc(), Destructor,
6478 PDiag(diag::err_access_dtor_temp)
6479 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006480 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6481 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006482
Richard Smithfd555f62012-02-22 02:04:18 +00006483 // If destructor is trivial, we can avoid the extra copy.
6484 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006485 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006486
John McCall28fc7092011-11-10 05:35:25 +00006487 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006488 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006489 }
Richard Smitheec915d62012-02-18 04:13:32 +00006490
6491 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006492 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6493
6494 if (IsDecltype)
6495 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6496
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006497 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006498}
6499
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500ExprResult
John McCall5d413782010-12-06 08:20:24 +00006501Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006502 if (SubExpr.isInvalid())
6503 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006504
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006505 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006506}
6507
John McCall28fc7092011-11-10 05:35:25 +00006508Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006509 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006510
Eli Friedman3bda6b12012-02-02 23:15:15 +00006511 CleanupVarDeclMarking();
6512
John McCall28fc7092011-11-10 05:35:25 +00006513 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6514 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006515 assert(Cleanup.exprNeedsCleanups() ||
6516 ExprCleanupObjects.size() == FirstCleanup);
6517 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006518 return SubExpr;
6519
Craig Topper5fc8fc22014-08-27 06:28:36 +00006520 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6521 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006522
Tim Shen4a05bb82016-06-21 20:29:17 +00006523 auto *E = ExprWithCleanups::Create(
6524 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006525 DiscardCleanupsInEvaluationContext();
6526
6527 return E;
6528}
6529
John McCall5d413782010-12-06 08:20:24 +00006530Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006531 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006532
Eli Friedman3bda6b12012-02-02 23:15:15 +00006533 CleanupVarDeclMarking();
6534
Tim Shen4a05bb82016-06-21 20:29:17 +00006535 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006536 return SubStmt;
6537
6538 // FIXME: In order to attach the temporaries, wrap the statement into
6539 // a StmtExpr; currently this is only used for asm statements.
6540 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6541 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006542 CompoundStmt *CompStmt = CompoundStmt::Create(
6543 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006544 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6545 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006546 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006547}
6548
Richard Smithfd555f62012-02-22 02:04:18 +00006549/// Process the expression contained within a decltype. For such expressions,
6550/// certain semantic checks on temporaries are delayed until this point, and
6551/// are omitted for the 'topmost' call in the decltype expression. If the
6552/// topmost call bound a temporary, strip that temporary off the expression.
6553ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006554 assert(ExprEvalContexts.back().ExprContext ==
6555 ExpressionEvaluationContextRecord::EK_Decltype &&
6556 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006557
Akira Hatanaka0a848562019-01-10 20:12:16 +00006558 ExprResult Result = CheckPlaceholderExpr(E);
6559 if (Result.isInvalid())
6560 return ExprError();
6561 E = Result.get();
6562
Richard Smithfd555f62012-02-22 02:04:18 +00006563 // C++11 [expr.call]p11:
6564 // If a function call is a prvalue of object type,
6565 // -- if the function call is either
6566 // -- the operand of a decltype-specifier, or
6567 // -- the right operand of a comma operator that is the operand of a
6568 // decltype-specifier,
6569 // a temporary object is not introduced for the prvalue.
6570
6571 // Recursively rebuild ParenExprs and comma expressions to strip out the
6572 // outermost CXXBindTemporaryExpr, if any.
6573 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6574 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6575 if (SubExpr.isInvalid())
6576 return ExprError();
6577 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006578 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006579 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006580 }
6581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6582 if (BO->getOpcode() == BO_Comma) {
6583 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6584 if (RHS.isInvalid())
6585 return ExprError();
6586 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006587 return E;
6588 return new (Context) BinaryOperator(
6589 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006590 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006591 }
6592 }
6593
6594 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006595 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6596 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006597 if (TopCall)
6598 E = TopCall;
6599 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006600 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006601
6602 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006603 ExprEvalContexts.back().ExprContext =
6604 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006605
Richard Smithf86b0ae2012-07-28 19:54:11 +00006606 // In MS mode, don't perform any extra checking of call return types within a
6607 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006608 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006609 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006610
Richard Smithfd555f62012-02-22 02:04:18 +00006611 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006612 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6613 I != N; ++I) {
6614 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006615 if (Call == TopCall)
6616 continue;
6617
David Majnemerced8bdf2015-02-25 17:36:15 +00006618 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006619 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006620 return ExprError();
6621 }
6622
6623 // Now all relevant types are complete, check the destructors are accessible
6624 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006625 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6626 I != N; ++I) {
6627 CXXBindTemporaryExpr *Bind =
6628 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006629 if (Bind == TopBind)
6630 continue;
6631
6632 CXXTemporary *Temp = Bind->getTemporary();
6633
6634 CXXRecordDecl *RD =
6635 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6636 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6637 Temp->setDestructor(Destructor);
6638
Richard Smith7d847b12012-05-11 22:20:10 +00006639 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6640 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006641 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006642 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006643 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6644 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006645
6646 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006647 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006648 }
6649
6650 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006651 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006652}
6653
Richard Smith79c927b2013-11-06 19:31:51 +00006654/// Note a set of 'operator->' functions that were used for a member access.
6655static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006656 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006657 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6658 // FIXME: Make this configurable?
6659 unsigned Limit = 9;
6660 if (OperatorArrows.size() > Limit) {
6661 // Produce Limit-1 normal notes and one 'skipping' note.
6662 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6663 SkipCount = OperatorArrows.size() - (Limit - 1);
6664 }
6665
6666 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6667 if (I == SkipStart) {
6668 S.Diag(OperatorArrows[I]->getLocation(),
6669 diag::note_operator_arrows_suppressed)
6670 << SkipCount;
6671 I += SkipCount;
6672 } else {
6673 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6674 << OperatorArrows[I]->getCallResultType();
6675 ++I;
6676 }
6677 }
6678}
6679
Nico Weber964d3322015-02-16 22:35:45 +00006680ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6681 SourceLocation OpLoc,
6682 tok::TokenKind OpKind,
6683 ParsedType &ObjectType,
6684 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006685 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006686 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006687 if (Result.isInvalid()) return ExprError();
6688 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006689
John McCall526ab472011-10-25 17:37:35 +00006690 Result = CheckPlaceholderExpr(Base);
6691 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006692 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006693
John McCallb268a282010-08-23 23:25:46 +00006694 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006695 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006696 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006697 // If we have a pointer to a dependent type and are using the -> operator,
6698 // the object type is the type that the pointer points to. We might still
6699 // have enough information about that type to do something useful.
6700 if (OpKind == tok::arrow)
6701 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6702 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703
John McCallba7bf592010-08-24 05:47:05 +00006704 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006705 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006706 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006707 }
Mike Stump11289f42009-09-09 15:08:12 +00006708
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006709 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006710 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006711 // returned, with the original second operand.
6712 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006713 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006714 bool NoArrowOperatorFound = false;
6715 bool FirstIteration = true;
6716 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006717 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006718 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006719 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006720 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006722 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006723 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6724 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006725 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006726 noteOperatorArrows(*this, OperatorArrows);
6727 Diag(OpLoc, diag::note_operator_arrow_depth)
6728 << getLangOpts().ArrowDepth;
6729 return ExprError();
6730 }
6731
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006732 Result = BuildOverloadedArrowExpr(
6733 S, Base, OpLoc,
6734 // When in a template specialization and on the first loop iteration,
6735 // potentially give the default diagnostic (with the fixit in a
6736 // separate note) instead of having the error reported back to here
6737 // and giving a diagnostic with a fixit attached to the error itself.
6738 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006739 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006740 : &NoArrowOperatorFound);
6741 if (Result.isInvalid()) {
6742 if (NoArrowOperatorFound) {
6743 if (FirstIteration) {
6744 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006745 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006746 << FixItHint::CreateReplacement(OpLoc, ".");
6747 OpKind = tok::period;
6748 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006749 }
6750 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6751 << BaseType << Base->getSourceRange();
6752 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006753 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006754 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006755 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006756 }
6757 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006758 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006759 }
John McCallb268a282010-08-23 23:25:46 +00006760 Base = Result.get();
6761 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006762 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006763 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006764 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006765 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006766 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6767 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006768 return ExprError();
6769 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006770 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
Richard Smith89009442019-05-09 22:22:48 +00006773 if (OpKind == tok::arrow) {
6774 if (BaseType->isPointerType())
6775 BaseType = BaseType->getPointeeType();
6776 else if (auto *AT = Context.getAsArrayType(BaseType))
6777 BaseType = AT->getElementType();
6778 }
Douglas Gregore4f764f2009-11-20 19:58:21 +00006779 }
Mike Stump11289f42009-09-09 15:08:12 +00006780
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006781 // Objective-C properties allow "." access on Objective-C pointer types,
6782 // so adjust the base type to the object type itself.
6783 if (BaseType->isObjCObjectPointerType())
6784 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006785
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006786 // C++ [basic.lookup.classref]p2:
6787 // [...] If the type of the object expression is of pointer to scalar
6788 // type, the unqualified-id is looked up in the context of the complete
6789 // postfix-expression.
6790 //
6791 // This also indicates that we could be parsing a pseudo-destructor-name.
6792 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006793 // expressions or normal member (ivar or property) access expressions, and
6794 // it's legal for the type to be incomplete if this is a pseudo-destructor
6795 // call. We'll do more incomplete-type checks later in the lookup process,
6796 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006797 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006798 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006799 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006800 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006801 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006802 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006803 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006804 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006805 }
Mike Stump11289f42009-09-09 15:08:12 +00006806
Douglas Gregor3024f072012-04-16 07:05:22 +00006807 // The object type must be complete (or dependent), or
6808 // C++11 [expr.prim.general]p3:
6809 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006810 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006811 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006812 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006813 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006814 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006815 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006816
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006817 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006818 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006819 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006820 // type C (or of pointer to a class type C), the unqualified-id is looked
6821 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006822 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006823 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006824}
6825
Simon Pilgrim75c26882016-09-30 14:25:09 +00006826static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006827 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006828 if (Base->hasPlaceholderType()) {
6829 ExprResult result = S.CheckPlaceholderExpr(Base);
6830 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006831 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006832 }
6833 ObjectType = Base->getType();
6834
David Blaikie1d578782011-12-16 16:03:09 +00006835 // C++ [expr.pseudo]p2:
6836 // The left-hand side of the dot operator shall be of scalar type. The
6837 // left-hand side of the arrow operator shall be of pointer to scalar type.
6838 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006839 // Note that this is rather different from the normal handling for the
6840 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006841 if (OpKind == tok::arrow) {
6842 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6843 ObjectType = Ptr->getPointeeType();
6844 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006845 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006846 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6847 << ObjectType << true
6848 << FixItHint::CreateReplacement(OpLoc, ".");
6849 if (S.isSFINAEContext())
6850 return true;
6851
6852 OpKind = tok::period;
6853 }
6854 }
6855
6856 return false;
6857}
6858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006859/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006860/// pointer objects.
6861static bool
6862canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6863 QualType DestructedType) {
6864 // If this is a record type, check if its destructor is callable.
6865 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00006866 if (RD->hasDefinition())
6867 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6868 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006869 return false;
6870 }
6871
6872 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6873 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6874 DestructedType->isVectorType();
6875}
6876
John McCalldadc5752010-08-24 06:29:42 +00006877ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006878 SourceLocation OpLoc,
6879 tok::TokenKind OpKind,
6880 const CXXScopeSpec &SS,
6881 TypeSourceInfo *ScopeTypeInfo,
6882 SourceLocation CCLoc,
6883 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006884 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006885 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886
Eli Friedman0ce4de42012-01-25 04:35:06 +00006887 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006888 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6889 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890
Douglas Gregorc5c57342012-09-10 14:57:06 +00006891 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6892 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006893 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006894 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006895 else {
Nico Weber58829272012-01-23 05:50:57 +00006896 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6897 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006898 return ExprError();
6899 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006900 }
6901
6902 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006904 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006905 if (DestructedTypeInfo) {
6906 QualType DestructedType = DestructedTypeInfo->getType();
6907 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006908 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006909 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6910 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006911 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6912 // Foo *foo;
6913 // foo.~Foo();
6914 if (OpKind == tok::period && ObjectType->isPointerType() &&
6915 Context.hasSameUnqualifiedType(DestructedType,
6916 ObjectType->getPointeeType())) {
6917 auto Diagnostic =
6918 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6919 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006921 // Issue a fixit only when the destructor is valid.
6922 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6923 *this, DestructedType))
6924 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6925
6926 // Recover by setting the object type to the destructed type and the
6927 // operator to '->'.
6928 ObjectType = DestructedType;
6929 OpKind = tok::arrow;
6930 } else {
6931 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6932 << ObjectType << DestructedType << Base->getSourceRange()
6933 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6934
6935 // Recover by setting the destructed type to the object type.
6936 DestructedType = ObjectType;
6937 DestructedTypeInfo =
6938 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6939 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6940 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006941 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006942 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006943
John McCall31168b02011-06-15 23:02:42 +00006944 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6945 // Okay: just pretend that the user provided the correctly-qualified
6946 // type.
6947 } else {
6948 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6949 << ObjectType << DestructedType << Base->getSourceRange()
6950 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6951 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006952
John McCall31168b02011-06-15 23:02:42 +00006953 // Recover by setting the destructed type to the object type.
6954 DestructedType = ObjectType;
6955 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6956 DestructedTypeStart);
6957 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6958 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006959 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006962 // C++ [expr.pseudo]p2:
6963 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6964 // form
6965 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006966 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006967 //
6968 // shall designate the same scalar type.
6969 if (ScopeTypeInfo) {
6970 QualType ScopeType = ScopeTypeInfo->getType();
6971 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006972 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006973
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006974 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006975 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006976 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006977 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006978
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006979 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006980 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006981 }
6982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983
John McCallb268a282010-08-23 23:25:46 +00006984 Expr *Result
6985 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6986 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006987 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006988 ScopeTypeInfo,
6989 CCLoc,
6990 TildeLoc,
6991 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992
David Majnemerced8bdf2015-02-25 17:36:15 +00006993 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006994}
6995
John McCalldadc5752010-08-24 06:29:42 +00006996ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006997 SourceLocation OpLoc,
6998 tok::TokenKind OpKind,
6999 CXXScopeSpec &SS,
7000 UnqualifiedId &FirstTypeName,
7001 SourceLocation CCLoc,
7002 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007003 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007004 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7005 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007006 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00007007 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7008 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007009 "Invalid second type name in pseudo-destructor");
7010
Eli Friedman0ce4de42012-01-25 04:35:06 +00007011 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007012 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7013 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007014
7015 // Compute the object type that we should use for name lookup purposes. Only
7016 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007017 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007018 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007019 if (ObjectType->isRecordType())
7020 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007021 else if (ObjectType->isDependentType())
7022 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024
7025 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007026 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007027 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007028 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007029 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007030 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007031 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007032 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007033 S, &SS, true, false, ObjectTypePtrForLookup,
7034 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007036 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7037 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007039 // couldn't find anything useful in scope. Just store the identifier and
7040 // it's location, and we'll perform (qualified) name lookup again at
7041 // template instantiation time.
7042 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7043 SecondTypeName.StartLocation);
7044 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007045 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007046 diag::err_pseudo_dtor_destructor_non_type)
7047 << SecondTypeName.Identifier << ObjectType;
7048 if (isSFINAEContext())
7049 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007050
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007051 // Recover by assuming we had the right type all along.
7052 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007053 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007054 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007055 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007056 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007057 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007058 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007059 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007060 TypeResult T = ActOnTemplateIdType(S,
7061 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007062 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007063 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007064 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007065 TemplateId->TemplateNameLoc,
7066 TemplateId->LAngleLoc,
7067 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007068 TemplateId->RAngleLoc,
7069 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007070 if (T.isInvalid() || !T.get()) {
7071 // Recover by assuming we had the right type all along.
7072 DestructedType = ObjectType;
7073 } else
7074 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
7077 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007078 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007079 if (!DestructedType.isNull()) {
7080 if (!DestructedTypeInfo)
7081 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007082 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007083 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007085
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007086 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007087 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007088 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007089 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007090 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007091 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007092 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007093 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007094 S, &SS, true, false, ObjectTypePtrForLookup,
7095 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007096 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007098 diag::err_pseudo_dtor_destructor_non_type)
7099 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007101 if (isSFINAEContext())
7102 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007104 // Just drop this type. It's unnecessary anyway.
7105 ScopeType = QualType();
7106 } else
7107 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007108 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007109 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007110 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007111 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007112 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007113 TypeResult T = ActOnTemplateIdType(S,
7114 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007115 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007116 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007117 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007118 TemplateId->TemplateNameLoc,
7119 TemplateId->LAngleLoc,
7120 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007121 TemplateId->RAngleLoc,
7122 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007123 if (T.isInvalid() || !T.get()) {
7124 // Recover by dropping this type.
7125 ScopeType = QualType();
7126 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007127 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007128 }
7129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130
Douglas Gregor90ad9222010-02-24 23:02:30 +00007131 if (!ScopeType.isNull() && !ScopeTypeInfo)
7132 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7133 FirstTypeName.StartLocation);
7134
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135
John McCallb268a282010-08-23 23:25:46 +00007136 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007137 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007138 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007139}
7140
David Blaikie1d578782011-12-16 16:03:09 +00007141ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7142 SourceLocation OpLoc,
7143 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007144 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007145 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007146 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007147 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7148 return ExprError();
7149
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007150 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7151 false);
David Blaikie1d578782011-12-16 16:03:09 +00007152
7153 TypeLocBuilder TLB;
7154 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7155 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7156 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7157 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7158
7159 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007160 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007161 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007162}
7163
John Wiegley01296292011-04-08 18:41:53 +00007164ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007165 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007166 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007167 // Convert the expression to match the conversion function's implicit object
7168 // parameter.
7169 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7170 FoundDecl, Method);
7171 if (Exp.isInvalid())
7172 return true;
7173
Eli Friedman98b01ed2012-03-01 04:01:32 +00007174 if (Method->getParent()->isLambda() &&
7175 Method->getConversionType()->isBlockPointerType()) {
Jan Korouse72321f2019-07-23 16:54:11 +00007176 // This is a lambda conversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007177 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007178 Expr *SubE = E;
7179 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7180 if (CE && CE->getCastKind() == CK_NoOp)
7181 SubE = CE->getSubExpr();
7182 SubE = SubE->IgnoreParens();
7183 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7184 SubE = BE->getSubExpr();
7185 if (isa<LambdaExpr>(SubE)) {
7186 // For the conversion to block pointer on a lambda expression, we
7187 // construct a special BlockLiteral instead; this doesn't really make
7188 // a difference in ARC, but outside of ARC the resulting block literal
7189 // follows the normal lifetime rules for block literals instead of being
7190 // autoreleased.
7191 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007192 PushExpressionEvaluationContext(
7193 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007194 ExprResult BlockExp = BuildBlockForLambdaConversion(
7195 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007196 PopExpressionEvaluationContext();
7197
Richard Smith7ed5fb22018-07-27 17:13:18 +00007198 if (BlockExp.isInvalid())
7199 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7200 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007201 }
7202 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007203
Richard Smith84be9982019-06-06 23:24:18 +00007204 MemberExpr *ME =
7205 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7206 NestedNameSpecifierLoc(), SourceLocation(), Method,
7207 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7208 HadMultipleCandidates, DeclarationNameInfo(),
7209 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007210
Alp Toker314cc812014-01-25 16:55:45 +00007211 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007212 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7213 ResultType = ResultType.getNonLValueExprType(Context);
7214
Bruno Riccic5885cf2018-12-21 15:20:32 +00007215 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7216 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007217
7218 if (CheckFunctionCall(Method, CE,
7219 Method->getType()->castAs<FunctionProtoType>()))
7220 return ExprError();
7221
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007222 return CE;
7223}
7224
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007225ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7226 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007227 // If the operand is an unresolved lookup expression, the expression is ill-
7228 // formed per [over.over]p1, because overloaded function names cannot be used
7229 // without arguments except in explicit contexts.
7230 ExprResult R = CheckPlaceholderExpr(Operand);
7231 if (R.isInvalid())
7232 return R;
7233
7234 // The operand may have been modified when checking the placeholder type.
7235 Operand = R.get();
7236
Richard Smith51ec0cf2017-02-21 01:17:38 +00007237 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007238 // The expression operand for noexcept is in an unevaluated expression
7239 // context, so side effects could result in unintended consequences.
7240 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7241 }
7242
Richard Smithf623c962012-04-17 00:58:00 +00007243 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007244 return new (Context)
7245 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007246}
7247
7248ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7249 Expr *Operand, SourceLocation RParen) {
7250 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007251}
7252
Eli Friedmanf798f652012-05-24 22:04:19 +00007253static bool IsSpecialDiscardedValue(Expr *E) {
7254 // In C++11, discarded-value expressions of a certain form are special,
7255 // according to [expr]p10:
7256 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7257 // expression is an lvalue of volatile-qualified type and it has
7258 // one of the following forms:
7259 E = E->IgnoreParens();
7260
Eli Friedmanc49c2262012-05-24 22:36:31 +00007261 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007262 if (isa<DeclRefExpr>(E))
7263 return true;
7264
Eli Friedmanc49c2262012-05-24 22:36:31 +00007265 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007266 if (isa<ArraySubscriptExpr>(E))
7267 return true;
7268
Eli Friedmanc49c2262012-05-24 22:36:31 +00007269 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007270 if (isa<MemberExpr>(E))
7271 return true;
7272
Eli Friedmanc49c2262012-05-24 22:36:31 +00007273 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007274 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7275 if (UO->getOpcode() == UO_Deref)
7276 return true;
7277
7278 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007279 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007280 if (BO->isPtrMemOp())
7281 return true;
7282
Eli Friedmanc49c2262012-05-24 22:36:31 +00007283 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007284 if (BO->getOpcode() == BO_Comma)
7285 return IsSpecialDiscardedValue(BO->getRHS());
7286 }
7287
Eli Friedmanc49c2262012-05-24 22:36:31 +00007288 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007289 // operands are one of the above, or
7290 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7291 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7292 IsSpecialDiscardedValue(CO->getFalseExpr());
7293 // The related edge case of "*x ?: *x".
7294 if (BinaryConditionalOperator *BCO =
7295 dyn_cast<BinaryConditionalOperator>(E)) {
7296 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7297 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7298 IsSpecialDiscardedValue(BCO->getFalseExpr());
7299 }
7300
7301 // Objective-C++ extensions to the rule.
7302 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7303 return true;
7304
7305 return false;
7306}
7307
John McCall34376a62010-12-04 03:47:34 +00007308/// Perform the conversions required for an expression used in a
7309/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007310ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007311 if (E->hasPlaceholderType()) {
7312 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007313 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007314 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007315 }
7316
John McCallfee942d2010-12-02 02:07:15 +00007317 // C99 6.3.2.1:
7318 // [Except in specific positions,] an lvalue that does not have
7319 // array type is converted to the value stored in the
7320 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007321 if (E->isRValue()) {
7322 // In C, function designators (i.e. expressions of function type)
7323 // are r-values, but we still want to do function-to-pointer decay
7324 // on them. This is both technically correct and convenient for
7325 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007326 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007327 return DefaultFunctionArrayConversion(E);
7328
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007329 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007330 }
John McCallfee942d2010-12-02 02:07:15 +00007331
Eli Friedmanf798f652012-05-24 22:04:19 +00007332 if (getLangOpts().CPlusPlus) {
7333 // The C++11 standard defines the notion of a discarded-value expression;
7334 // normally, we don't need to do anything to handle it, but if it is a
7335 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7336 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007337 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007338 E->getType().isVolatileQualified() &&
7339 IsSpecialDiscardedValue(E)) {
7340 ExprResult Res = DefaultLvalueConversion(E);
7341 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007342 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007343 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007344 }
Richard Smith122f88d2016-12-06 23:52:28 +00007345
7346 // C++1z:
7347 // If the expression is a prvalue after this optional conversion, the
7348 // temporary materialization conversion is applied.
7349 //
7350 // We skip this step: IR generation is able to synthesize the storage for
7351 // itself in the aggregate case, and adding the extra node to the AST is
7352 // just clutter.
7353 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7354 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007355 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007356 }
John McCall34376a62010-12-04 03:47:34 +00007357
7358 // GCC seems to also exclude expressions of incomplete enum type.
7359 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7360 if (!T->getDecl()->isComplete()) {
7361 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007362 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007363 return E;
John McCall34376a62010-12-04 03:47:34 +00007364 }
7365 }
7366
John Wiegley01296292011-04-08 18:41:53 +00007367 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7368 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007369 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007370 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007371
John McCallca61b652010-12-04 12:29:11 +00007372 if (!E->getType()->isVoidType())
7373 RequireCompleteType(E->getExprLoc(), E->getType(),
7374 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007375 return E;
John McCall34376a62010-12-04 03:47:34 +00007376}
7377
Faisal Valia17d19f2013-11-07 05:17:06 +00007378// If we can unambiguously determine whether Var can never be used
7379// in a constant expression, return true.
7380// - if the variable and its initializer are non-dependent, then
7381// we can unambiguously check if the variable is a constant expression.
7382// - if the initializer is not value dependent - we can determine whether
7383// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007384// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007385// never be a constant expression.
7386// - FXIME: if the initializer is dependent, we can still do some analysis and
7387// identify certain cases unambiguously as non-const by using a Visitor:
7388// - such as those that involve odr-use of a ParmVarDecl, involve a new
7389// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007390static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007391 ASTContext &Context) {
7392 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007393 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007394
7395 // If there is no initializer - this can not be a constant expression.
7396 if (!Var->getAnyInitializer(DefVD)) return true;
7397 assert(DefVD);
7398 if (DefVD->isWeak()) return false;
7399 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007400
Faisal Valia17d19f2013-11-07 05:17:06 +00007401 Expr *Init = cast<Expr>(Eval->Value);
7402
7403 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007404 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7405 // of value-dependent expressions, and use it here to determine whether the
7406 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007407 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007408 }
7409
Richard Smith715f7a12019-06-11 17:50:32 +00007410 return !Var->isUsableInConstantExpressions(Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007411}
7412
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007413/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007414/// that must be captured by any of its enclosing lambdas that are ready to
7415/// capture. If there is a lambda that can capture a nested
7416/// potential-capture, go ahead and do so. Also, check to see if any
7417/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007418/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007419
Faisal Valiab3d6462013-12-07 20:22:44 +00007420static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7421 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7422
Simon Pilgrim75c26882016-09-30 14:25:09 +00007423 assert(!S.isUnevaluatedContext());
7424 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007425#ifndef NDEBUG
7426 DeclContext *DC = S.CurContext;
7427 while (DC && isa<CapturedDecl>(DC))
7428 DC = DC->getParent();
7429 assert(
7430 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007431 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007432#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007433
7434 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7435
Faisal Valiab3d6462013-12-07 20:22:44 +00007436 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007437 // lambda (within a generic outer lambda), must be captured by an
7438 // outer lambda that is enclosed within a non-dependent context.
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007439 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007440 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007441 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007442 // need to check enclosing lambda's for speculative captures.
7443 // For e.g.:
7444 // Even though 'x' is not odr-used, it should be captured.
7445 // int test() {
7446 // const int x = 10;
7447 // auto L = [=](auto a) {
7448 // (void) +x + a;
7449 // };
7450 // }
7451 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007452 !IsFullExprInstantiationDependent)
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007453 return;
Faisal Valiab3d6462013-12-07 20:22:44 +00007454
7455 // If we have a capture-capable lambda for the variable, go ahead and
7456 // capture the variable in that lambda (and all its enclosing lambdas).
7457 if (const Optional<unsigned> Index =
7458 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Richard Smith94ef6862019-05-28 23:09:42 +00007459 S.FunctionScopes, Var, S))
7460 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7461 Index.getValue());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007462 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007463 VariableCanNeverBeAConstantExpression(Var, S.Context);
7464 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7465 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007466 // can not be used in a constant expression - which means
7467 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007468 // capture violation early, if the variable is un-captureable.
7469 // This is purely for diagnosing errors early. Otherwise, this
7470 // error would get diagnosed when the lambda becomes capture ready.
7471 QualType CaptureType, DeclRefType;
7472 SourceLocation ExprLoc = VarExpr->getExprLoc();
7473 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007474 /*EllipsisLoc*/ SourceLocation(),
7475 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007476 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007477 // We will never be able to capture this variable, and we need
7478 // to be able to in any and all instantiations, so diagnose it.
7479 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007480 /*EllipsisLoc*/ SourceLocation(),
7481 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007482 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007483 }
7484 }
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007485 });
Faisal Valia17d19f2013-11-07 05:17:06 +00007486
Faisal Valiab3d6462013-12-07 20:22:44 +00007487 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007488 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007489 // If we have a capture-capable lambda for 'this', go ahead and capture
7490 // 'this' in that lambda (and all its enclosing lambdas).
7491 if (const Optional<unsigned> Index =
7492 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007493 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007494 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7495 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7496 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7497 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007498 }
7499 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007500
7501 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007502 CurrentLSI->clearPotentialCaptures();
7503}
7504
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007505static ExprResult attemptRecovery(Sema &SemaRef,
7506 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007507 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007508 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7509 Consumer.getLookupResult().getLookupKind());
7510 const CXXScopeSpec *SS = Consumer.getSS();
7511 CXXScopeSpec NewSS;
7512
7513 // Use an approprate CXXScopeSpec for building the expr.
7514 if (auto *NNS = TC.getCorrectionSpecifier())
7515 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7516 else if (SS && !TC.WillReplaceSpecifier())
7517 NewSS = *SS;
7518
Richard Smithde6d6c42015-12-29 19:43:10 +00007519 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007520 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007521 R.addDecl(ND);
7522 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007523 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007524 CXXRecordDecl *Record = nullptr;
7525 if (auto *NNS = TC.getCorrectionSpecifier())
7526 Record = NNS->getAsType()->getAsCXXRecordDecl();
7527 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007528 Record =
7529 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7530 if (Record)
7531 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007532
7533 // Detect and handle the case where the decl might be an implicit
7534 // member.
7535 bool MightBeImplicitMember;
7536 if (!Consumer.isAddressOfOperand())
7537 MightBeImplicitMember = true;
7538 else if (!NewSS.isEmpty())
7539 MightBeImplicitMember = false;
7540 else if (R.isOverloadedResult())
7541 MightBeImplicitMember = false;
7542 else if (R.isUnresolvableResult())
7543 MightBeImplicitMember = true;
7544 else
7545 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7546 isa<IndirectFieldDecl>(ND) ||
7547 isa<MSPropertyDecl>(ND);
7548
7549 if (MightBeImplicitMember)
7550 return SemaRef.BuildPossibleImplicitMemberExpr(
7551 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007552 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007553 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7554 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7555 Ivar->getIdentifier());
7556 }
7557 }
7558
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007559 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7560 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007561}
7562
Kaelyn Takata6c759512014-10-27 18:07:37 +00007563namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007564class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7565 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7566
7567public:
7568 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7569 : TypoExprs(TypoExprs) {}
7570 bool VisitTypoExpr(TypoExpr *TE) {
7571 TypoExprs.insert(TE);
7572 return true;
7573 }
7574};
7575
Kaelyn Takata6c759512014-10-27 18:07:37 +00007576class TransformTypos : public TreeTransform<TransformTypos> {
7577 typedef TreeTransform<TransformTypos> BaseTransform;
7578
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007579 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7580 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007581 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007582 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007583 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007584 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007586 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007587 /// If the TypoExprs were successfully corrected, then the diagnostics should
7588 /// suggest the corrections. Otherwise the diagnostics will not suggest
7589 /// anything (having been passed an empty TypoCorrection).
7590 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007591 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007592 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007593 if (State.DiagHandler) {
7594 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7595 ExprResult Replacement = TransformCache[TE];
7596
7597 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7598 // TypoCorrection, replacing the existing decls. This ensures the right
7599 // NamedDecl is used in diagnostics e.g. in the case where overload
7600 // resolution was used to select one from several possible decls that
7601 // had been stored in the TypoCorrection.
7602 if (auto *ND = getDeclFromExpr(
7603 Replacement.isInvalid() ? nullptr : Replacement.get()))
7604 TC.setCorrectionDecl(ND);
7605
7606 State.DiagHandler(TC);
7607 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007608 SemaRef.clearDelayedTypo(TE);
7609 }
7610 }
7611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007612 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007613 /// given combination of the other TypoExprs, retry those corrections against
7614 /// the next combination of substitutions for the other TypoExprs by advancing
7615 /// to the next potential correction of the second TypoExpr. For the second
7616 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7617 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7618 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7619 /// TransformCache). Returns true if there is still any untried combinations
7620 /// of corrections.
7621 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7622 for (auto TE : TypoExprs) {
7623 auto &State = SemaRef.getTypoExprState(TE);
7624 TransformCache.erase(TE);
7625 if (!State.Consumer->finished())
7626 return true;
7627 State.Consumer->resetCorrectionStream();
7628 }
7629 return false;
7630 }
7631
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007632 NamedDecl *getDeclFromExpr(Expr *E) {
7633 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7634 E = OverloadResolution[OE];
7635
7636 if (!E)
7637 return nullptr;
7638 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007639 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007640 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007641 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007642 // FIXME: Add any other expr types that could be be seen by the delayed typo
7643 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007644 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007645 return nullptr;
7646 }
7647
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007648 ExprResult TryTransform(Expr *E) {
7649 Sema::SFINAETrap Trap(SemaRef);
7650 ExprResult Res = TransformExpr(E);
7651 if (Trap.hasErrorOccurred() || Res.isInvalid())
7652 return ExprError();
7653
7654 return ExprFilter(Res.get());
7655 }
7656
Kaelyn Takata6c759512014-10-27 18:07:37 +00007657public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007658 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7659 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007660
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007661 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7662 MultiExprArg Args,
7663 SourceLocation RParenLoc,
7664 Expr *ExecConfig = nullptr) {
7665 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7666 RParenLoc, ExecConfig);
7667 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007668 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007669 Expr *ResultCall = Result.get();
7670 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7671 ResultCall = BE->getSubExpr();
7672 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7673 OverloadResolution[OE] = CE->getCallee();
7674 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007675 }
7676 return Result;
7677 }
7678
Kaelyn Takata6c759512014-10-27 18:07:37 +00007679 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7680
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007681 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7682
Kaelyn Takata6c759512014-10-27 18:07:37 +00007683 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007684 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007685 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007686 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007687
Kaelyn Takata6c759512014-10-27 18:07:37 +00007688 // Exit if either the transform was valid or if there were no TypoExprs
7689 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007690 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007691 !CheckAndAdvanceTypoExprCorrectionStreams())
7692 break;
7693 }
7694
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007695 // Ensure none of the TypoExprs have multiple typo correction candidates
7696 // with the same edit length that pass all the checks and filters.
7697 // TODO: Properly handle various permutations of possible corrections when
7698 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007699 // Also, disable typo correction while attempting the transform when
7700 // handling potentially ambiguous typo corrections as any new TypoExprs will
7701 // have been introduced by the application of one of the correction
7702 // candidates and add little to no value if corrected.
7703 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007704 while (!AmbiguousTypoExprs.empty()) {
7705 auto TE = AmbiguousTypoExprs.back();
7706 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007707 auto &State = SemaRef.getTypoExprState(TE);
7708 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007709 TransformCache.erase(TE);
7710 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007711 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007712 TransformCache.erase(TE);
7713 Res = ExprError();
7714 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007715 }
7716 AmbiguousTypoExprs.remove(TE);
7717 State.Consumer->restoreSavedPosition();
7718 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007719 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007720 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007721
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007722 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007723 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007724 FindTypoExprs(TypoExprs).TraverseStmt(E);
7725
Kaelyn Takata6c759512014-10-27 18:07:37 +00007726 EmitAllDiagnostics();
7727
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007728 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007729 }
7730
7731 ExprResult TransformTypoExpr(TypoExpr *E) {
7732 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7733 // cached transformation result if there is one and the TypoExpr isn't the
7734 // first one that was encountered.
7735 auto &CacheEntry = TransformCache[E];
7736 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7737 return CacheEntry;
7738 }
7739
7740 auto &State = SemaRef.getTypoExprState(E);
7741 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7742
7743 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7744 // typo correction and return it.
7745 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007746 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007747 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007748 // FIXME: If we would typo-correct to an invalid declaration, it's
7749 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007750 ExprResult NE = State.RecoveryHandler ?
7751 State.RecoveryHandler(SemaRef, E, TC) :
7752 attemptRecovery(SemaRef, *State.Consumer, TC);
7753 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007754 // Check whether there may be a second viable correction with the same
7755 // edit distance; if so, remember this TypoExpr may have an ambiguous
7756 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007757 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007758 if ((Next = State.Consumer->peekNextCorrection()) &&
7759 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7760 AmbiguousTypoExprs.insert(E);
7761 } else {
7762 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007763 }
7764 assert(!NE.isUnset() &&
7765 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007766 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007767 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007768 }
7769 return CacheEntry = ExprError();
7770 }
7771};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007772}
Faisal Valia17d19f2013-11-07 05:17:06 +00007773
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007774ExprResult
7775Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7776 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007777 // If the current evaluation context indicates there are uncorrected typos
7778 // and the current expression isn't guaranteed to not have typos, try to
7779 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007780 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007781 (E->isTypeDependent() || E->isValueDependent() ||
7782 E->isInstantiationDependent())) {
7783 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007784 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007785 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007786 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007787 ExprEvalContexts.back().NumTypos -= TyposResolved;
7788 return Result;
7789 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007790 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007791 }
7792 return E;
7793}
7794
Richard Smith945f8d32013-01-14 22:39:08 +00007795ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007796 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00007797 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007798 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007799
7800 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007801 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007802
Richard Smithb3d203f2018-10-19 19:01:34 +00007803 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007804 return ExprError();
7805
Richard Smith945f8d32013-01-14 22:39:08 +00007806 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00007807 // Top-level expressions default to 'id' when we're in a debugger.
7808 if (getLangOpts().DebuggerCastResultToId &&
7809 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7810 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7811 if (FullExpr.isInvalid())
7812 return ExprError();
7813 }
7814
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007815 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007816 if (FullExpr.isInvalid())
7817 return ExprError();
7818
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007819 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007820 if (FullExpr.isInvalid())
7821 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007822
7823 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007824 }
John Wiegley01296292011-04-08 18:41:53 +00007825
Kaelyn Takata49d84322014-11-11 23:26:56 +00007826 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7827 if (FullExpr.isInvalid())
7828 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007829
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007830 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007831
Simon Pilgrim75c26882016-09-30 14:25:09 +00007832 // At the end of this full expression (which could be a deeply nested
7833 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007834 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007835 // Consider the following code:
7836 // void f(int, int);
7837 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007838 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007839 // const int x = 10, y = 20;
7840 // auto L = [=](auto a) {
7841 // auto M = [=](auto b) {
7842 // f(x, b); <-- requires x to be captured by L and M
7843 // f(y, a); <-- requires y to be captured by L, but not all Ms
7844 // };
7845 // };
7846 // }
7847
Simon Pilgrim75c26882016-09-30 14:25:09 +00007848 // FIXME: Also consider what happens for something like this that involves
7849 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007850 // void f() {
7851 // const int n = 0;
7852 // auto L = [&](auto a) {
7853 // +n + ({ 0; a; });
7854 // };
7855 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007856 //
7857 // Here, we see +n, and then the full-expression 0; ends, so we don't
7858 // capture n (and instead remove it from our list of potential captures),
7859 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007860 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007861
Alexey Bataev31939e32016-11-11 12:36:20 +00007862 LambdaScopeInfo *const CurrentLSI =
7863 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007864 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007865 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007866 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007867 // By ensuring we are in the context of a lambda's call operator
7868 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007869 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007870 // PR, a proper fix would entail :
7871 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007872 // - Add to Sema an integer holding the smallest (outermost) scope
7873 // index that we are *lexically* within, and save/restore/set to
7874 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007875 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007876 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007877 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007878 DeclContext *DC = CurContext;
7879 while (DC && isa<CapturedDecl>(DC))
7880 DC = DC->getParent();
7881 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007882 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007883 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007884 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7885 *this);
John McCall5d413782010-12-06 08:20:24 +00007886 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007887}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007888
7889StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7890 if (!FullStmt) return StmtError();
7891
John McCall5d413782010-12-06 08:20:24 +00007892 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007893}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007894
Simon Pilgrim75c26882016-09-30 14:25:09 +00007895Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007896Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7897 CXXScopeSpec &SS,
7898 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007899 DeclarationName TargetName = TargetNameInfo.getName();
7900 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007901 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007902
Douglas Gregor43edb322011-10-24 22:31:10 +00007903 // If the name itself is dependent, then the result is dependent.
7904 if (TargetName.isDependentName())
7905 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007906
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007907 // Do the redeclaration lookup in the current scope.
7908 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7909 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007910 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007911 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007912
Douglas Gregor43edb322011-10-24 22:31:10 +00007913 switch (R.getResultKind()) {
7914 case LookupResult::Found:
7915 case LookupResult::FoundOverloaded:
7916 case LookupResult::FoundUnresolvedValue:
7917 case LookupResult::Ambiguous:
7918 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007919
Douglas Gregor43edb322011-10-24 22:31:10 +00007920 case LookupResult::NotFound:
7921 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007922
Douglas Gregor43edb322011-10-24 22:31:10 +00007923 case LookupResult::NotFoundInCurrentInstantiation:
7924 return IER_Dependent;
7925 }
David Blaikie8a40f702012-01-17 06:56:22 +00007926
7927 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007928}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007929
Simon Pilgrim75c26882016-09-30 14:25:09 +00007930Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007931Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7932 bool IsIfExists, CXXScopeSpec &SS,
7933 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007934 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007935
Richard Smith151c4562016-12-20 21:35:28 +00007936 // Check for an unexpanded parameter pack.
7937 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7938 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7939 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007940 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007941
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007942 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7943}