blob: 5ac248d36b413c60b93874b2504a9953e4aed5df [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.
93 if (CurClass->isDependentContext() && !EnteringContext) {
94 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) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000532 // OpenCL C++ 1.0 s2.9: typeid is not supported.
533 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 Bataev1ab34572018-05-02 16:52:07 +0000753 !getSourceManager().isInSystemHeader(OpLoc) &&
754 (!getLangOpts().OpenMPIsDevice ||
755 !getLangOpts().OpenMPHostCXXExceptions ||
756 isInOpenMPTargetExecutionDirective() ||
757 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000758 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000759
Justin Lebar2a8db342016-09-28 22:45:54 +0000760 // Exceptions aren't allowed in CUDA device code.
761 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000762 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
763 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000764
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000765 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
766 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
767
John Wiegley01296292011-04-08 18:41:53 +0000768 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000769 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
770 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000771 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000772
773 // Initialize the exception result. This implicitly weeds out
774 // abstract types or types with inaccessible copy constructors.
775
776 // C++0x [class.copymove]p31:
777 // When certain criteria are met, an implementation is allowed to omit the
778 // copy/move construction of a class object [...]
779 //
780 // - in a throw-expression, when the operand is the name of a
781 // non-volatile automatic object (other than a function or
782 // catch-clause
783 // parameter) whose scope does not extend beyond the end of the
784 // innermost enclosing try-block (if there is one), the copy/move
785 // operation from the operand to the exception object (15.1) can be
786 // omitted by constructing the automatic object directly into the
787 // exception object
788 const VarDecl *NRVOVariable = nullptr;
789 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000790 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000791
792 InitializedEntity Entity = InitializedEntity::InitializeException(
793 OpLoc, ExceptionObjectTy,
794 /*NRVO=*/NRVOVariable != nullptr);
795 ExprResult Res = PerformMoveOrCopyInitialization(
796 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
797 if (Res.isInvalid())
798 return ExprError();
799 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000800 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000801
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000802 return new (Context)
803 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000804}
805
David Majnemere7a818f2015-03-06 18:53:55 +0000806static void
807collectPublicBases(CXXRecordDecl *RD,
808 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
809 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
810 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
811 bool ParentIsPublic) {
812 for (const CXXBaseSpecifier &BS : RD->bases()) {
813 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
814 bool NewSubobject;
815 // Virtual bases constitute the same subobject. Non-virtual bases are
816 // always distinct subobjects.
817 if (BS.isVirtual())
818 NewSubobject = VBases.insert(BaseDecl).second;
819 else
820 NewSubobject = true;
821
822 if (NewSubobject)
823 ++SubobjectsSeen[BaseDecl];
824
825 // Only add subobjects which have public access throughout the entire chain.
826 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
827 if (PublicPath)
828 PublicSubobjectsSeen.insert(BaseDecl);
829
830 // Recurse on to each base subobject.
831 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
832 PublicPath);
833 }
834}
835
836static void getUnambiguousPublicSubobjects(
837 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
838 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
839 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
840 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
841 SubobjectsSeen[RD] = 1;
842 PublicSubobjectsSeen.insert(RD);
843 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
844 /*ParentIsPublic=*/true);
845
846 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
847 // Skip ambiguous objects.
848 if (SubobjectsSeen[PublicSubobject] > 1)
849 continue;
850
851 Objects.push_back(PublicSubobject);
852 }
853}
854
Sebastian Redl4de47b42009-04-27 20:27:31 +0000855/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000856bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
857 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000858 // If the type of the exception would be an incomplete type or a pointer
859 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000860 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000861 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000862 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000863 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000864 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000865 }
866 if (!isPointer || !Ty->isVoidType()) {
867 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000868 isPointer ? diag::err_throw_incomplete_ptr
869 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000870 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000871 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000872
David Majnemerd09a51c2015-03-03 01:50:05 +0000873 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000874 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000875 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000876 }
877
Eli Friedman91a3d272010-06-03 20:39:03 +0000878 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000879 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
880 if (!RD)
881 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000882
Douglas Gregor88d292c2010-05-13 16:44:06 +0000883 // If we are throwing a polymorphic class type or pointer thereof,
884 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000885 MarkVTableUsed(ThrowLoc, RD);
886
Eli Friedman36ebbec2010-10-12 20:32:36 +0000887 // If a pointer is thrown, the referenced object will not be destroyed.
888 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000889 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000890
Richard Smitheec915d62012-02-18 04:13:32 +0000891 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000892 if (!RD->hasIrrelevantDestructor()) {
893 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
894 MarkFunctionReferenced(E->getExprLoc(), Destructor);
895 CheckDestructorAccess(E->getExprLoc(), Destructor,
896 PDiag(diag::err_access_dtor_exception) << Ty);
897 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000898 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000899 }
900 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000901
David Majnemerdfa6d202015-03-11 18:36:39 +0000902 // The MSVC ABI creates a list of all types which can catch the exception
903 // object. This list also references the appropriate copy constructor to call
904 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000905 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000906 // We are only interested in the public, unambiguous bases contained within
907 // the exception object. Bases which are ambiguous or otherwise
908 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000909 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
910 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000911
David Majnemere7a818f2015-03-06 18:53:55 +0000912 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000913 // Attempt to lookup the copy constructor. Various pieces of machinery
914 // will spring into action, like template instantiation, which means this
915 // cannot be a simple walk of the class's decls. Instead, we must perform
916 // lookup and overload resolution.
917 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
918 if (!CD)
919 continue;
920
921 // Mark the constructor referenced as it is used by this throw expression.
922 MarkFunctionReferenced(E->getExprLoc(), CD);
923
924 // Skip this copy constructor if it is trivial, we don't need to record it
925 // in the catchable type data.
926 if (CD->isTrivial())
927 continue;
928
929 // The copy constructor is non-trivial, create a mapping from this class
930 // type to this constructor.
931 // N.B. The selection of copy constructor is not sensitive to this
932 // particular throw-site. Lookup will be performed at the catch-site to
933 // ensure that the copy constructor is, in fact, accessible (via
934 // friendship or any other means).
935 Context.addCopyConstructorForExceptionObject(Subobject, CD);
936
937 // We don't keep the instantiated default argument expressions around so
938 // we must rebuild them here.
939 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000940 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
941 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000942 }
943 }
944 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000945
David Majnemerba3e5ec2015-03-13 18:26:17 +0000946 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000947}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000948
Faisal Vali67b04462016-06-11 16:41:54 +0000949static QualType adjustCVQualifiersForCXXThisWithinLambda(
950 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
951 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
952
953 QualType ClassType = ThisTy->getPointeeType();
954 LambdaScopeInfo *CurLSI = nullptr;
955 DeclContext *CurDC = CurSemaContext;
956
957 // Iterate through the stack of lambdas starting from the innermost lambda to
958 // the outermost lambda, checking if '*this' is ever captured by copy - since
959 // that could change the cv-qualifiers of the '*this' object.
960 // The object referred to by '*this' starts out with the cv-qualifiers of its
961 // member function. We then start with the innermost lambda and iterate
962 // outward checking to see if any lambda performs a by-copy capture of '*this'
963 // - and if so, any nested lambda must respect the 'constness' of that
964 // capturing lamdbda's call operator.
965 //
966
Faisal Vali999f27e2017-05-02 20:56:34 +0000967 // Since the FunctionScopeInfo stack is representative of the lexical
968 // nesting of the lambda expressions during initial parsing (and is the best
969 // place for querying information about captures about lambdas that are
970 // partially processed) and perhaps during instantiation of function templates
971 // that contain lambda expressions that need to be transformed BUT not
972 // necessarily during instantiation of a nested generic lambda's function call
973 // operator (which might even be instantiated at the end of the TU) - at which
974 // time the DeclContext tree is mature enough to query capture information
975 // reliably - we use a two pronged approach to walk through all the lexically
976 // enclosing lambda expressions:
977 //
978 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
979 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
980 // enclosed by the call-operator of the LSI below it on the stack (while
981 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
982 // the stack represents the innermost lambda.
983 //
984 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
985 // represents a lambda's call operator. If it does, we must be instantiating
986 // a generic lambda's call operator (represented by the Current LSI, and
987 // should be the only scenario where an inconsistency between the LSI and the
988 // DeclContext should occur), so climb out the DeclContexts if they
989 // represent lambdas, while querying the corresponding closure types
990 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000991
Faisal Vali999f27e2017-05-02 20:56:34 +0000992 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000993 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000994 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
995 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
996 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000997 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
998 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000999
1000 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001001 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001002
Faisal Vali67b04462016-06-11 16:41:54 +00001003 auto C = CurLSI->getCXXThisCapture();
1004
1005 if (C.isCopyCapture()) {
1006 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1007 if (CurLSI->CallOperator->isConst())
1008 ClassType.addConst();
1009 return ASTCtx.getPointerType(ClassType);
1010 }
1011 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001012
1013 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1014 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001015 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001016 assert(CurLSI && "While computing 'this' capture-type for a generic "
1017 "lambda, we must have a corresponding LambdaScopeInfo");
1018 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1019 "While computing 'this' capture-type for a generic lambda, when we "
1020 "run out of enclosing LSI's, yet the enclosing DC is a "
1021 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1022 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001023 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001024
Faisal Vali67b04462016-06-11 16:41:54 +00001025 auto IsThisCaptured =
1026 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1027 IsConst = false;
1028 IsByCopy = false;
1029 for (auto &&C : Closure->captures()) {
1030 if (C.capturesThis()) {
1031 if (C.getCaptureKind() == LCK_StarThis)
1032 IsByCopy = true;
1033 if (Closure->getLambdaCallOperator()->isConst())
1034 IsConst = true;
1035 return true;
1036 }
1037 }
1038 return false;
1039 };
1040
1041 bool IsByCopyCapture = false;
1042 bool IsConstCapture = false;
1043 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1044 while (Closure &&
1045 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1046 if (IsByCopyCapture) {
1047 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1048 if (IsConstCapture)
1049 ClassType.addConst();
1050 return ASTCtx.getPointerType(ClassType);
1051 }
1052 Closure = isLambdaCallOperator(Closure->getParent())
1053 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1054 : nullptr;
1055 }
1056 }
1057 return ASTCtx.getPointerType(ClassType);
1058}
1059
Eli Friedman73a04092012-01-07 04:59:52 +00001060QualType Sema::getCurrentThisType() {
1061 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001062 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001063
Richard Smith938f40b2011-06-11 17:19:42 +00001064 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1065 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001066 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001067 }
Faisal Validc6b5962016-03-21 09:25:37 +00001068
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001069 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001070 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001071
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001072 assert(isa<CXXRecordDecl>(DC) &&
1073 "Trying to get 'this' type from static method?");
1074
1075 // This is a lambda call operator that is being instantiated as a default
1076 // initializer. DC must point to the enclosing class type, so we can recover
1077 // the 'this' type from it.
1078
1079 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1080 // There are no cv-qualifiers for 'this' within default initializers,
1081 // per [expr.prim.general]p4.
1082 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001083 }
Faisal Vali67b04462016-06-11 16:41:54 +00001084
1085 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1086 // might need to be adjusted if the lambda or any of its enclosing lambda's
1087 // captures '*this' by copy.
1088 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1089 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1090 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001091 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001092}
1093
Simon Pilgrim75c26882016-09-30 14:25:09 +00001094Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001095 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001096 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001097 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001098 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1099{
1100 if (!Enabled || !ContextDecl)
1101 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001102
1103 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001104 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1105 Record = Template->getTemplatedDecl();
1106 else
1107 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001108
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001109 QualType T = S.Context.getRecordType(Record);
1110 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1111
1112 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001113
Douglas Gregor3024f072012-04-16 07:05:22 +00001114 this->Enabled = true;
1115}
1116
1117
1118Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1119 if (Enabled) {
1120 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1121 }
1122}
1123
Faisal Validc6b5962016-03-21 09:25:37 +00001124static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1125 QualType ThisTy, SourceLocation Loc,
1126 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001127
Faisal Vali67b04462016-06-11 16:41:54 +00001128 QualType AdjustedThisTy = ThisTy;
1129 // The type of the corresponding data member (not a 'this' pointer if 'by
1130 // copy').
1131 QualType CaptureThisFieldTy = ThisTy;
1132 if (ByCopy) {
1133 // If we are capturing the object referred to by '*this' by copy, ignore any
1134 // cv qualifiers inherited from the type of the member function for the type
1135 // of the closure-type's corresponding data member and any use of 'this'.
1136 CaptureThisFieldTy = ThisTy->getPointeeType();
1137 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1138 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1139 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001140
Faisal Vali67b04462016-06-11 16:41:54 +00001141 FieldDecl *Field = FieldDecl::Create(
1142 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1143 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1144 ICIS_NoInit);
1145
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001146 Field->setImplicit(true);
1147 Field->setAccess(AS_private);
1148 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001149 Expr *This =
1150 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001151 if (ByCopy) {
1152 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1153 UO_Deref,
1154 This).get();
1155 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001156 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001157 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1158 InitializationSequence Init(S, Entity, InitKind, StarThis);
1159 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1160 if (ER.isInvalid()) return nullptr;
1161 return ER.get();
1162 }
1163 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001164}
1165
Simon Pilgrim75c26882016-09-30 14:25:09 +00001166bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001167 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1168 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001169 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001170 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001171 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001172
Faisal Validc6b5962016-03-21 09:25:37 +00001173 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001174
Reid Kleckner87a31802018-03-12 21:43:02 +00001175 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1176 ? *FunctionScopeIndexToStopAt
1177 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001178
Simon Pilgrim75c26882016-09-30 14:25:09 +00001179 // Check that we can capture the *enclosing object* (referred to by '*this')
1180 // by the capturing-entity/closure (lambda/block/etc) at
1181 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1182
1183 // Note: The *enclosing object* can only be captured by-value by a
1184 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001185 // [*this] { ... }.
1186 // Every other capture of the *enclosing object* results in its by-reference
1187 // capture.
1188
1189 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1190 // stack), we can capture the *enclosing object* only if:
1191 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1192 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001193 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001194 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001195 // -- or, there is some enclosing closure 'E' that has already captured the
1196 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001197 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001198 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001199 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001200
1201
Faisal Validc6b5962016-03-21 09:25:37 +00001202 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001203 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001204 if (CapturingScopeInfo *CSI =
1205 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1206 if (CSI->CXXThisCaptureIndex != 0) {
1207 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001208 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001209 break;
1210 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001211 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1212 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1213 // This context can't implicitly capture 'this'; fail out.
1214 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001215 Diag(Loc, diag::err_this_capture)
1216 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001217 return true;
1218 }
Eli Friedman20139d32012-01-11 02:36:31 +00001219 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001220 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001221 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001222 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001223 (Explicit && idx == MaxFunctionScopesIndex)) {
1224 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1225 // iteration through can be an explicit capture, all enclosing closures,
1226 // if any, must perform implicit captures.
1227
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001228 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001229 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001230 continue;
1231 }
Eli Friedman20139d32012-01-11 02:36:31 +00001232 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001233 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001234 Diag(Loc, diag::err_this_capture)
1235 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001236 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001237 }
Eli Friedman73a04092012-01-07 04:59:52 +00001238 break;
1239 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001240 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001241
1242 // If we got here, then the closure at MaxFunctionScopesIndex on the
1243 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1244 // (including implicit by-reference captures in any enclosing closures).
1245
1246 // In the loop below, respect the ByCopy flag only for the closure requesting
1247 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001248 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001249 // implicitly capturing the *enclosing object* by reference (see loop
1250 // above)).
1251 assert((!ByCopy ||
1252 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1253 "Only a lambda can capture the enclosing object (referred to by "
1254 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001255 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1256 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001257 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001258 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1259 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001260 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001261 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001262
Faisal Validc6b5962016-03-21 09:25:37 +00001263 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1264 // For lambda expressions, build a field and an initializing expression,
1265 // and capture the *enclosing object* by copy only if this is the first
1266 // iteration.
1267 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1268 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001269
Faisal Validc6b5962016-03-21 09:25:37 +00001270 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001271 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001272 ThisExpr =
1273 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1274 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001275
Faisal Validc6b5962016-03-21 09:25:37 +00001276 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001277 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001278 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001279 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001280}
1281
Richard Smith938f40b2011-06-11 17:19:42 +00001282ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001283 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1284 /// is a non-lvalue expression whose value is the address of the object for
1285 /// which the function is called.
1286
Douglas Gregor09deffa2011-10-18 16:47:30 +00001287 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001288 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001289
Eli Friedman73a04092012-01-07 04:59:52 +00001290 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001291 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001292}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001293
Douglas Gregor3024f072012-04-16 07:05:22 +00001294bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1295 // If we're outside the body of a member function, then we'll have a specified
1296 // type for 'this'.
1297 if (CXXThisTypeOverride.isNull())
1298 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001299
Douglas Gregor3024f072012-04-16 07:05:22 +00001300 // Determine whether we're looking into a class that's currently being
1301 // defined.
1302 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1303 return Class && Class->isBeingDefined();
1304}
1305
Vedant Kumara14a1f92018-01-17 18:53:51 +00001306/// Parse construction of a specified type.
1307/// Can be interpreted either as function-style casting ("int(x)")
1308/// or class type construction ("ClassType(x,y,z)")
1309/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001310ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001311Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001312 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001313 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001314 SourceLocation RParenOrBraceLoc,
1315 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001316 if (!TypeRep)
1317 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
John McCall97513962010-01-15 18:39:57 +00001319 TypeSourceInfo *TInfo;
1320 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1321 if (!TInfo)
1322 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001323
Vedant Kumara14a1f92018-01-17 18:53:51 +00001324 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1325 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001326 // Avoid creating a non-type-dependent expression that contains typos.
1327 // Non-type-dependent expressions are liable to be discarded without
1328 // checking for embedded typos.
1329 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1330 !Result.get()->isTypeDependent())
1331 Result = CorrectDelayedTyposInExpr(Result.get());
1332 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001333}
1334
Douglas Gregor2b88c112010-09-08 00:15:04 +00001335ExprResult
1336Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001337 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001338 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001339 SourceLocation RParenOrBraceLoc,
1340 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001341 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001342 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001343
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001344 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001345 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1346 // directly. We work around this by dropping the locations of the braces.
1347 SourceRange Locs = ListInitialization
1348 ? SourceRange()
1349 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1350 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1351 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001352 }
1353
Richard Smith600b5262017-01-26 20:40:47 +00001354 assert((!ListInitialization ||
1355 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1356 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001357 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001358
Richard Smith60437622017-02-09 19:17:44 +00001359 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1360 InitializationKind Kind =
1361 Exprs.size()
1362 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001363 ? InitializationKind::CreateDirectList(
1364 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1365 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1366 RParenOrBraceLoc)
1367 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1368 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001369
1370 // C++1z [expr.type.conv]p1:
1371 // If the type is a placeholder for a deduced class type, [...perform class
1372 // template argument deduction...]
1373 DeducedType *Deduced = Ty->getContainedDeducedType();
1374 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1375 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1376 Kind, Exprs);
1377 if (Ty.isNull())
1378 return ExprError();
1379 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1380 }
1381
Douglas Gregordd04d332009-01-16 18:33:17 +00001382 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001383 // If the expression list is a parenthesized single expression, the type
1384 // conversion expression is equivalent (in definedness, and if defined in
1385 // meaning) to the corresponding cast expression.
1386 if (Exprs.size() == 1 && !ListInitialization &&
1387 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001388 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001389 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1390 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001391 }
1392
Richard Smith49a6b6e2017-03-24 01:14:25 +00001393 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001394 QualType ElemTy = Ty;
1395 if (Ty->isArrayType()) {
1396 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001397 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1398 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001399 ElemTy = Context.getBaseElementType(Ty);
1400 }
1401
Richard Smith49a6b6e2017-03-24 01:14:25 +00001402 // There doesn't seem to be an explicit rule against this but sanity demands
1403 // we only construct objects with object types.
1404 if (Ty->isFunctionType())
1405 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1406 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001407
Richard Smith49a6b6e2017-03-24 01:14:25 +00001408 // C++17 [expr.type.conv]p2:
1409 // If the type is cv void and the initializer is (), the expression is a
1410 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001411 if (!Ty->isVoidType() &&
1412 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001413 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001414 return ExprError();
1415
Richard Smith49a6b6e2017-03-24 01:14:25 +00001416 // Otherwise, the expression is a prvalue of the specified type whose
1417 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001418 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1419 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001420
Richard Smith49a6b6e2017-03-24 01:14:25 +00001421 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001422 return Result;
1423
1424 Expr *Inner = Result.get();
1425 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1426 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001427 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1428 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001429 // If we created a CXXTemporaryObjectExpr, that node also represents the
1430 // functional cast. Otherwise, create an explicit cast to represent
1431 // the syntactic form of a functional-style cast that was used here.
1432 //
1433 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1434 // would give a more consistent AST representation than using a
1435 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1436 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001437 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001438 SourceRange Locs = ListInitialization
1439 ? SourceRange()
1440 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001441 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001442 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1443 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001444 }
1445
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001446 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001447}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001448
Artem Belevich78929ef2018-09-21 17:29:33 +00001449bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1450 // [CUDA] Ignore this function, if we can't call it.
1451 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1452 if (getLangOpts().CUDA &&
1453 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1454 return false;
1455
1456 SmallVector<const FunctionDecl*, 4> PreventedBy;
1457 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1458
1459 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1460 return Result;
1461
1462 // In case of CUDA, return true if none of the 1-argument deallocator
1463 // functions are actually callable.
1464 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1465 assert(FD->getNumParams() == 1 &&
1466 "Only single-operand functions should be in PreventedBy");
1467 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1468 });
1469}
1470
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001471/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001472/// deallocation function.
1473static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001474 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001475 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001476
1477 if (FD->getOverloadedOperator() != OO_Delete &&
1478 FD->getOverloadedOperator() != OO_Array_Delete)
1479 return false;
1480
1481 unsigned UsualParams = 1;
1482
1483 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1484 S.Context.hasSameUnqualifiedType(
1485 FD->getParamDecl(UsualParams)->getType(),
1486 S.Context.getSizeType()))
1487 ++UsualParams;
1488
1489 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1490 S.Context.hasSameUnqualifiedType(
1491 FD->getParamDecl(UsualParams)->getType(),
1492 S.Context.getTypeDeclType(S.getStdAlignValT())))
1493 ++UsualParams;
1494
1495 return UsualParams == FD->getNumParams();
1496}
1497
1498namespace {
1499 struct UsualDeallocFnInfo {
1500 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001501 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001502 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001503 Destroying(false), HasSizeT(false), HasAlignValT(false),
1504 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001505 // A function template declaration is never a usual deallocation function.
1506 if (!FD)
1507 return;
Richard Smith5b349582017-10-13 01:55:36 +00001508 unsigned NumBaseParams = 1;
1509 if (FD->isDestroyingOperatorDelete()) {
1510 Destroying = true;
1511 ++NumBaseParams;
1512 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001513
1514 if (NumBaseParams < FD->getNumParams() &&
1515 S.Context.hasSameUnqualifiedType(
1516 FD->getParamDecl(NumBaseParams)->getType(),
1517 S.Context.getSizeType())) {
1518 ++NumBaseParams;
1519 HasSizeT = true;
1520 }
1521
1522 if (NumBaseParams < FD->getNumParams() &&
1523 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1524 ++NumBaseParams;
1525 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001526 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001527
1528 // In CUDA, determine how much we'd like / dislike to call this.
1529 if (S.getLangOpts().CUDA)
1530 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1531 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001532 }
1533
Eric Fiselierfa752f22018-03-21 19:19:48 +00001534 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001535
Richard Smithf75dcbe2016-10-11 00:21:10 +00001536 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1537 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001538 // C++ P0722:
1539 // A destroying operator delete is preferred over a non-destroying
1540 // operator delete.
1541 if (Destroying != Other.Destroying)
1542 return Destroying;
1543
Richard Smithf75dcbe2016-10-11 00:21:10 +00001544 // C++17 [expr.delete]p10:
1545 // If the type has new-extended alignment, a function with a parameter
1546 // of type std::align_val_t is preferred; otherwise a function without
1547 // such a parameter is preferred
1548 if (HasAlignValT != Other.HasAlignValT)
1549 return HasAlignValT == WantAlign;
1550
1551 if (HasSizeT != Other.HasSizeT)
1552 return HasSizeT == WantSize;
1553
1554 // Use CUDA call preference as a tiebreaker.
1555 return CUDAPref > Other.CUDAPref;
1556 }
1557
Richard Smithb2f0f052016-10-10 18:54:32 +00001558 DeclAccessPair Found;
1559 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001560 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001561 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001562 };
1563}
1564
1565/// Determine whether a type has new-extended alignment. This may be called when
1566/// the type is incomplete (for a delete-expression with an incomplete pointee
1567/// type), in which case it will conservatively return false if the alignment is
1568/// not known.
1569static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1570 return S.getLangOpts().AlignedAllocation &&
1571 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1572 S.getASTContext().getTargetInfo().getNewAlign();
1573}
1574
1575/// Select the correct "usual" deallocation function to use from a selection of
1576/// deallocation functions (either global or class-scope).
1577static UsualDeallocFnInfo resolveDeallocationOverload(
1578 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1579 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1580 UsualDeallocFnInfo Best;
1581
Richard Smithb2f0f052016-10-10 18:54:32 +00001582 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001583 UsualDeallocFnInfo Info(S, I.getPair());
1584 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1585 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001586 continue;
1587
1588 if (!Best) {
1589 Best = Info;
1590 if (BestFns)
1591 BestFns->push_back(Info);
1592 continue;
1593 }
1594
Richard Smithf75dcbe2016-10-11 00:21:10 +00001595 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001596 continue;
1597
1598 // If more than one preferred function is found, all non-preferred
1599 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001600 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001601 BestFns->clear();
1602
1603 Best = Info;
1604 if (BestFns)
1605 BestFns->push_back(Info);
1606 }
1607
1608 return Best;
1609}
1610
1611/// Determine whether a given type is a class for which 'delete[]' would call
1612/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1613/// we need to store the array size (even if the type is
1614/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001615static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1616 QualType allocType) {
1617 const RecordType *record =
1618 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1619 if (!record) return false;
1620
1621 // Try to find an operator delete[] in class scope.
1622
1623 DeclarationName deleteName =
1624 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1625 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1626 S.LookupQualifiedName(ops, record->getDecl());
1627
1628 // We're just doing this for information.
1629 ops.suppressDiagnostics();
1630
1631 // Very likely: there's no operator delete[].
1632 if (ops.empty()) return false;
1633
1634 // If it's ambiguous, it should be illegal to call operator delete[]
1635 // on this thing, so it doesn't matter if we allocate extra space or not.
1636 if (ops.isAmbiguous()) return false;
1637
Richard Smithb2f0f052016-10-10 18:54:32 +00001638 // C++17 [expr.delete]p10:
1639 // If the deallocation functions have class scope, the one without a
1640 // parameter of type std::size_t is selected.
1641 auto Best = resolveDeallocationOverload(
1642 S, ops, /*WantSize*/false,
1643 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1644 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001645}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001646
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001647/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001648///
Sebastian Redld74dd492012-02-12 18:41:05 +00001649/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001650/// @code new (memory) int[size][4] @endcode
1651/// or
1652/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001653///
1654/// \param StartLoc The first location of the expression.
1655/// \param UseGlobal True if 'new' was prefixed with '::'.
1656/// \param PlacementLParen Opening paren of the placement arguments.
1657/// \param PlacementArgs Placement new arguments.
1658/// \param PlacementRParen Closing paren of the placement arguments.
1659/// \param TypeIdParens If the type is in parens, the source range.
1660/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001661/// \param Initializer The initializing expression or initializer-list, or null
1662/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001663ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001664Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001665 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001667 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001668 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001669 // If the specified type is an array, unwrap it and save the expression.
1670 if (D.getNumTypeObjects() > 0 &&
1671 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001672 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001673 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001674 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1675 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001676 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001677 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1678 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001679 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001680 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1681 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001682
Sebastian Redl351bb782008-12-02 14:43:59 +00001683 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001684 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001685 }
1686
Douglas Gregor73341c42009-09-11 00:18:58 +00001687 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001688 if (ArraySize) {
1689 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001690 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1691 break;
1692
1693 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1694 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001695 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001696 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001697 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1698 // shall be a converted constant expression (5.19) of type std::size_t
1699 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001700 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1701 assert(IntWidth && "Builtin type of size 0?");
1702 llvm::APSInt Value(IntWidth);
1703 Array.NumElts
1704 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1705 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001706 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001707 } else {
1708 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001709 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001710 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001711 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001712 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001713 if (!Array.NumElts)
1714 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001715 }
1716 }
1717 }
1718 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001719
Craig Topperc3ec1492014-05-26 06:22:03 +00001720 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001721 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001722 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001723 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001724
Sebastian Redl6047f072012-02-16 12:22:20 +00001725 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001726 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001727 DirectInitRange = List->getSourceRange();
1728
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001729 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1730 PlacementLParen, PlacementArgs, PlacementRParen,
1731 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001732 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001733}
1734
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001735static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1736 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001737 if (!Init)
1738 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001739 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1740 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001741 if (isa<ImplicitValueInitExpr>(Init))
1742 return true;
1743 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1744 return !CCE->isListInitialization() &&
1745 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001746 else if (Style == CXXNewExpr::ListInit) {
1747 assert(isa<InitListExpr>(Init) &&
1748 "Shouldn't create list CXXConstructExprs for arrays.");
1749 return true;
1750 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001751 return false;
1752}
1753
Akira Hatanaka71645c22018-12-21 07:05:36 +00001754bool
1755Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1756 if (!getLangOpts().AlignedAllocationUnavailable)
1757 return false;
1758 if (FD.isDefined())
1759 return false;
1760 bool IsAligned = false;
1761 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1762 return true;
1763 return false;
1764}
1765
Akira Hatanakacae83f72017-06-29 18:48:40 +00001766// Emit a diagnostic if an aligned allocation/deallocation function that is not
1767// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001768void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1769 SourceLocation Loc) {
1770 if (isUnavailableAlignedAllocationFunction(FD)) {
1771 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001772 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001773 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001774
Akira Hatanaka71645c22018-12-21 07:05:36 +00001775 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1776 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1777 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001778 << IsDelete << FD.getType().getAsString() << OSName
1779 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001780 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001781 }
1782}
1783
John McCalldadc5752010-08-24 06:29:42 +00001784ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001785Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001786 SourceLocation PlacementLParen,
1787 MultiExprArg PlacementArgs,
1788 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001789 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001790 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001791 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001792 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001793 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001794 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001795 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001796 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001797
Sebastian Redl6047f072012-02-16 12:22:20 +00001798 CXXNewExpr::InitializationStyle initStyle;
1799 if (DirectInitRange.isValid()) {
1800 assert(Initializer && "Have parens but no initializer.");
1801 initStyle = CXXNewExpr::CallInit;
1802 } else if (Initializer && isa<InitListExpr>(Initializer))
1803 initStyle = CXXNewExpr::ListInit;
1804 else {
1805 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1806 isa<CXXConstructExpr>(Initializer)) &&
1807 "Initializer expression that cannot have been implicitly created.");
1808 initStyle = CXXNewExpr::NoInit;
1809 }
1810
1811 Expr **Inits = &Initializer;
1812 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001813 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1814 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1815 Inits = List->getExprs();
1816 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001817 }
1818
Richard Smith60437622017-02-09 19:17:44 +00001819 // C++11 [expr.new]p15:
1820 // A new-expression that creates an object of type T initializes that
1821 // object as follows:
1822 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001823 // - If the new-initializer is omitted, the object is default-
1824 // initialized (8.5); if no initialization is performed,
1825 // the object has indeterminate value
1826 = initStyle == CXXNewExpr::NoInit
1827 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1828 // - Otherwise, the new-initializer is interpreted according to
1829 // the
1830 // initialization rules of 8.5 for direct-initialization.
1831 : initStyle == CXXNewExpr::ListInit
1832 ? InitializationKind::CreateDirectList(
1833 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001834 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001835 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1836 DirectInitRange.getBegin(),
1837 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001838
Richard Smith60437622017-02-09 19:17:44 +00001839 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1840 auto *Deduced = AllocType->getContainedDeducedType();
1841 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1842 if (ArraySize)
1843 return ExprError(Diag(ArraySize->getExprLoc(),
1844 diag::err_deduced_class_template_compound_type)
1845 << /*array*/ 2 << ArraySize->getSourceRange());
1846
1847 InitializedEntity Entity
1848 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1849 AllocType = DeduceTemplateSpecializationFromInitializer(
1850 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1851 if (AllocType.isNull())
1852 return ExprError();
1853 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001854 bool Braced = (initStyle == CXXNewExpr::ListInit);
1855 if (NumInits == 1) {
1856 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1857 Inits = p->getInits();
1858 NumInits = p->getNumInits();
1859 Braced = true;
1860 }
1861 }
1862
Sebastian Redl6047f072012-02-16 12:22:20 +00001863 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001864 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1865 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001866 if (NumInits > 1) {
1867 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001868 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001869 diag::err_auto_new_ctor_multiple_expressions)
1870 << AllocType << TypeRange);
1871 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001872 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001873 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001874 << AllocType << TypeRange;
Richard Smith061f1e22013-04-30 21:23:01 +00001875 QualType DeducedType;
Akira Hatanakad458ced2019-01-11 04:57:34 +00001876 if (DeduceAutoType(AllocTypeInfo, Inits[0], DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001877 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Akira Hatanakad458ced2019-01-11 04:57:34 +00001878 << AllocType << Inits[0]->getType()
1879 << TypeRange << Inits[0]->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001880 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001881 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001882 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001883 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001884
Douglas Gregorcda95f42010-05-16 16:01:03 +00001885 // Per C++0x [expr.new]p5, the type being constructed may be a
1886 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001887 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001888 if (const ConstantArrayType *Array
1889 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001890 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1891 Context.getSizeType(),
1892 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001893 AllocType = Array->getElementType();
1894 }
1895 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001896
Douglas Gregor3999e152010-10-06 16:00:31 +00001897 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1898 return ExprError();
1899
Simon Pilgrim75c26882016-09-30 14:25:09 +00001900 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001902 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1903 AllocType->isObjCLifetimeType()) {
1904 AllocType = Context.getLifetimeQualifiedType(AllocType,
1905 AllocType->getObjCARCImplicitLifetime());
1906 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001907
John McCall31168b02011-06-15 23:02:42 +00001908 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001909
John McCall5e77d762013-04-16 07:28:30 +00001910 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1911 ExprResult result = CheckPlaceholderExpr(ArraySize);
1912 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001913 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001914 }
Richard Smith8dd34252012-02-04 07:07:42 +00001915 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1916 // integral or enumeration type with a non-negative value."
1917 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1918 // enumeration type, or a class type for which a single non-explicit
1919 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001920 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001921 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001922 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001923 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001924 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001925 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001926 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1927
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001928 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001929 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001930
Simon Pilgrim75c26882016-09-30 14:25:09 +00001931 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001932 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001933 // Diagnose the compatibility of this conversion.
1934 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1935 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001936 } else {
1937 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1938 protected:
1939 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001940
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001941 public:
1942 SizeConvertDiagnoser(Expr *ArraySize)
1943 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1944 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001945
1946 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1947 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001948 return S.Diag(Loc, diag::err_array_size_not_integral)
1949 << S.getLangOpts().CPlusPlus11 << T;
1950 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001951
1952 SemaDiagnosticBuilder diagnoseIncomplete(
1953 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001954 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1955 << T << ArraySize->getSourceRange();
1956 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001957
1958 SemaDiagnosticBuilder diagnoseExplicitConv(
1959 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001960 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1961 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001962
1963 SemaDiagnosticBuilder noteExplicitConv(
1964 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001965 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1966 << ConvTy->isEnumeralType() << ConvTy;
1967 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001968
1969 SemaDiagnosticBuilder diagnoseAmbiguous(
1970 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001971 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1972 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001973
1974 SemaDiagnosticBuilder noteAmbiguous(
1975 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001976 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1977 << ConvTy->isEnumeralType() << ConvTy;
1978 }
Richard Smithccc11812013-05-21 19:05:48 +00001979
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001980 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1981 QualType T,
1982 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001983 return S.Diag(Loc,
1984 S.getLangOpts().CPlusPlus11
1985 ? diag::warn_cxx98_compat_array_size_conversion
1986 : diag::ext_array_size_conversion)
1987 << T << ConvTy->isEnumeralType() << ConvTy;
1988 }
1989 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001990
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001991 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1992 SizeDiagnoser);
1993 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001994 if (ConvertedSize.isInvalid())
1995 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001997 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001998 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001999
Douglas Gregor0bf31402010-10-08 23:50:27 +00002000 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00002001 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002003 // C++98 [expr.new]p7:
2004 // The expression in a direct-new-declarator shall have integral type
2005 // with a non-negative value.
2006 //
Richard Smith0511d232016-10-05 22:41:02 +00002007 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2008 // per CWG1464. Otherwise, if it's not a constant, we must have an
2009 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002010 if (!ArraySize->isValueDependent()) {
2011 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002012 // We've already performed any required implicit conversion to integer or
2013 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002014 // FIXME: Per CWG1464, we are required to check the value prior to
2015 // converting to size_t. This will never find a negative array size in
2016 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002017 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002018 if (Value.isSigned() && Value.isNegative()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002019 return ExprError(Diag(ArraySize->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002020 diag::err_typecheck_negative_array_size)
2021 << ArraySize->getSourceRange());
2022 }
2023
2024 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002025 unsigned ActiveSizeBits =
2026 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002027 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002028 return ExprError(
2029 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2030 << Value.toString(10) << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002031 }
Richard Smith0511d232016-10-05 22:41:02 +00002032
2033 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002034 } else if (TypeIdParens.isValid()) {
2035 // Can't have dynamic array size when the type-id is in parentheses.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002036 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2037 << ArraySize->getSourceRange()
2038 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2039 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040
Douglas Gregorf2753b32010-07-13 15:54:32 +00002041 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002042 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002044
John McCall036f2f62011-05-15 07:14:44 +00002045 // Note that we do *not* convert the argument in any way. It can
2046 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002047 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002048
Craig Topperc3ec1492014-05-26 06:22:03 +00002049 FunctionDecl *OperatorNew = nullptr;
2050 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002051 unsigned Alignment =
2052 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2053 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2054 bool PassAlignment = getLangOpts().AlignedAllocation &&
2055 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056
Brian Gesiakcb024022018-04-01 22:59:22 +00002057 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002058 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002059 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002060 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002061 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002062 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002063 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002064 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002065
2066 // If this is an array allocation, compute whether the usual array
2067 // deallocation function for the type has a size_t parameter.
2068 bool UsualArrayDeleteWantsSize = false;
2069 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002070 UsualArrayDeleteWantsSize =
2071 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002072
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002073 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002074 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002076 OperatorNew->getType()->getAs<FunctionProtoType>();
2077 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2078 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Richard Smithd6f9e732014-05-13 19:56:21 +00002080 // We've already converted the placement args, just fill in any default
2081 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002082 // argument. Skip the second parameter too if we're passing in the
2083 // alignment; we've already filled it in.
2084 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2085 PassAlignment ? 2 : 1, PlacementArgs,
2086 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002087 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002088
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002089 if (!AllPlaceArgs.empty())
2090 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002091
Richard Smithd6f9e732014-05-13 19:56:21 +00002092 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002093 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002094
2095 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096
Richard Smithb2f0f052016-10-10 18:54:32 +00002097 // Warn if the type is over-aligned and is being allocated by (unaligned)
2098 // global operator new.
2099 if (PlacementArgs.empty() && !PassAlignment &&
2100 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002101 (OperatorNew->getBeginLoc().isValid() &&
2102 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002103 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002104 Diag(StartLoc, diag::warn_overaligned_type)
2105 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002106 << unsigned(Alignment / Context.getCharWidth())
2107 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002108 }
2109 }
2110
Sebastian Redl6047f072012-02-16 12:22:20 +00002111 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002112 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2113 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002114 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002115 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002116 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002117 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2118 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002119 }
2120
Richard Smithdd2ca572012-11-26 08:32:48 +00002121 // If we can perform the initialization, and we've not already done so,
2122 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002123 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002124 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002125 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002126 // The type we initialize is the complete type, including the array bound.
2127 QualType InitType;
2128 if (KnownArraySize)
2129 InitType = Context.getConstantArrayType(
2130 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2131 *KnownArraySize),
2132 ArrayType::Normal, 0);
2133 else if (ArraySize)
2134 InitType =
2135 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2136 else
2137 InitType = AllocType;
2138
Douglas Gregor85dabae2009-12-16 01:38:02 +00002139 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002140 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002141 InitializationSequence InitSeq(*this, Entity, Kind,
2142 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002144 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002145 if (FullInit.isInvalid())
2146 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
Sebastian Redl6047f072012-02-16 12:22:20 +00002148 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2149 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002150 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002151 if (CXXBindTemporaryExpr *Binder =
2152 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002153 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002155 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
Douglas Gregor6642ca22010-02-26 05:06:18 +00002158 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002159 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002160 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2161 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002162 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002163 }
2164 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002165 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2166 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002167 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002168 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002169
John McCall928a2572011-07-13 20:12:57 +00002170 // C++0x [expr.new]p17:
2171 // If the new expression creates an array of objects of class type,
2172 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002173 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2174 if (ArraySize && !BaseAllocType->isDependentType()) {
2175 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2176 if (CXXDestructorDecl *dtor = LookupDestructor(
2177 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2178 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002179 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002180 PDiag(diag::err_access_dtor)
2181 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002182 if (DiagnoseUseOfDecl(dtor, StartLoc))
2183 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002184 }
John McCall928a2572011-07-13 20:12:57 +00002185 }
2186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002187
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002188 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2189 PassAlignment, UsualArrayDeleteWantsSize,
2190 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2191 Initializer, ResultType, AllocTypeInfo, Range,
2192 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002193}
2194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002195/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002196/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002197bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002198 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002199 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2200 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002201 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002202 return Diag(Loc, diag::err_bad_new_type)
2203 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002204 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002205 return Diag(Loc, diag::err_bad_new_type)
2206 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002207 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002208 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002209 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002210 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002211 diag::err_allocation_of_abstract_type))
2212 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002213 else if (AllocType->isVariablyModifiedType())
2214 return Diag(Loc, diag::err_variably_modified_new_type)
2215 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002216 else if (AllocType.getAddressSpace() != LangAS::Default &&
2217 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002218 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002219 << AllocType.getUnqualifiedType()
2220 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002221 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002222 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2223 QualType BaseAllocType = Context.getBaseElementType(AT);
2224 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2225 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002226 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002227 << BaseAllocType;
2228 }
2229 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002230
Sebastian Redlbd150f42008-11-21 19:14:01 +00002231 return false;
2232}
2233
Brian Gesiak87412d92018-02-15 20:09:25 +00002234static bool resolveAllocationOverload(
2235 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2236 bool &PassAlignment, FunctionDecl *&Operator,
2237 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002238 OverloadCandidateSet Candidates(R.getNameLoc(),
2239 OverloadCandidateSet::CSK_Normal);
2240 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2241 Alloc != AllocEnd; ++Alloc) {
2242 // Even member operator new/delete are implicitly treated as
2243 // static, so don't use AddMemberCandidate.
2244 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2245
2246 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2247 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2248 /*ExplicitTemplateArgs=*/nullptr, Args,
2249 Candidates,
2250 /*SuppressUserConversions=*/false);
2251 continue;
2252 }
2253
2254 FunctionDecl *Fn = cast<FunctionDecl>(D);
2255 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2256 /*SuppressUserConversions=*/false);
2257 }
2258
2259 // Do the resolution.
2260 OverloadCandidateSet::iterator Best;
2261 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2262 case OR_Success: {
2263 // Got one!
2264 FunctionDecl *FnDecl = Best->Function;
2265 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2266 Best->FoundDecl) == Sema::AR_inaccessible)
2267 return true;
2268
2269 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002270 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002271 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002272
Richard Smithb2f0f052016-10-10 18:54:32 +00002273 case OR_No_Viable_Function:
2274 // C++17 [expr.new]p13:
2275 // If no matching function is found and the allocated object type has
2276 // new-extended alignment, the alignment argument is removed from the
2277 // argument list, and overload resolution is performed again.
2278 if (PassAlignment) {
2279 PassAlignment = false;
2280 AlignArg = Args[1];
2281 Args.erase(Args.begin() + 1);
2282 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002283 Operator, &Candidates, AlignArg,
2284 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002285 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002286
Richard Smithb2f0f052016-10-10 18:54:32 +00002287 // MSVC will fall back on trying to find a matching global operator new
2288 // if operator new[] cannot be found. Also, MSVC will leak by not
2289 // generating a call to operator delete or operator delete[], but we
2290 // will not replicate that bug.
2291 // FIXME: Find out how this interacts with the std::align_val_t fallback
2292 // once MSVC implements it.
2293 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2294 S.Context.getLangOpts().MSVCCompat) {
2295 R.clear();
2296 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2297 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2298 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2299 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002300 Operator, /*Candidates=*/nullptr,
2301 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002302 }
Richard Smith1cdec012013-09-29 04:40:38 +00002303
Brian Gesiak87412d92018-02-15 20:09:25 +00002304 if (Diagnose) {
2305 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2306 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002307
Brian Gesiak87412d92018-02-15 20:09:25 +00002308 // If we have aligned candidates, only note the align_val_t candidates
2309 // from AlignedCandidates and the non-align_val_t candidates from
2310 // Candidates.
2311 if (AlignedCandidates) {
2312 auto IsAligned = [](OverloadCandidate &C) {
2313 return C.Function->getNumParams() > 1 &&
2314 C.Function->getParamDecl(1)->getType()->isAlignValT();
2315 };
2316 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002317
Brian Gesiak87412d92018-02-15 20:09:25 +00002318 // This was an overaligned allocation, so list the aligned candidates
2319 // first.
2320 Args.insert(Args.begin() + 1, AlignArg);
2321 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2322 R.getNameLoc(), IsAligned);
2323 Args.erase(Args.begin() + 1);
2324 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2325 IsUnaligned);
2326 } else {
2327 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2328 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002329 }
Richard Smith1cdec012013-09-29 04:40:38 +00002330 return true;
2331
Richard Smithb2f0f052016-10-10 18:54:32 +00002332 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002333 if (Diagnose) {
2334 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2335 << R.getLookupName() << Range;
2336 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2337 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002338 return true;
2339
2340 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002341 if (Diagnose) {
2342 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2343 << Best->Function->isDeleted() << R.getLookupName()
2344 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2345 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2346 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002347 return true;
2348 }
2349 }
2350 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002351}
2352
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002353bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002354 AllocationFunctionScope NewScope,
2355 AllocationFunctionScope DeleteScope,
2356 QualType AllocType, bool IsArray,
2357 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002358 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002359 FunctionDecl *&OperatorDelete,
2360 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002361 // --- Choosing an allocation function ---
2362 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002363 // 1) If looking in AFS_Global scope for allocation functions, only look in
2364 // the global scope. Else, if AFS_Class, only look in the scope of the
2365 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002366 // 2) If an array size is given, look for operator new[], else look for
2367 // operator new.
2368 // 3) The first argument is always size_t. Append the arguments from the
2369 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002370
Richard Smithb2f0f052016-10-10 18:54:32 +00002371 SmallVector<Expr*, 8> AllocArgs;
2372 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2373
2374 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002375 // FIXME: Should the Sema create the expression and embed it in the syntax
2376 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002377 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002378 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002379 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002380 Context.getSizeType(),
2381 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002382 AllocArgs.push_back(&Size);
2383
2384 QualType AlignValT = Context.VoidTy;
2385 if (PassAlignment) {
2386 DeclareGlobalNewDelete();
2387 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2388 }
2389 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2390 if (PassAlignment)
2391 AllocArgs.push_back(&Align);
2392
2393 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002394
Douglas Gregor6642ca22010-02-26 05:06:18 +00002395 // C++ [expr.new]p8:
2396 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002397 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002398 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002399 // type, the allocation function's name is operator new[] and the
2400 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002401 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002402 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002403
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002404 QualType AllocElemType = Context.getBaseElementType(AllocType);
2405
Richard Smithb2f0f052016-10-10 18:54:32 +00002406 // Find the allocation function.
2407 {
2408 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2409
2410 // C++1z [expr.new]p9:
2411 // If the new-expression begins with a unary :: operator, the allocation
2412 // function's name is looked up in the global scope. Otherwise, if the
2413 // allocated type is a class type T or array thereof, the allocation
2414 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002415 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002416 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2417
2418 // We can see ambiguity here if the allocation function is found in
2419 // multiple base classes.
2420 if (R.isAmbiguous())
2421 return true;
2422
2423 // If this lookup fails to find the name, or if the allocated type is not
2424 // a class type, the allocation function's name is looked up in the
2425 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002426 if (R.empty()) {
2427 if (NewScope == AFS_Class)
2428 return true;
2429
Richard Smithb2f0f052016-10-10 18:54:32 +00002430 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002431 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002432
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002433 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2434 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2435 return true;
2436 }
2437
Richard Smithb2f0f052016-10-10 18:54:32 +00002438 assert(!R.empty() && "implicitly declared allocation functions not found");
2439 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2440
2441 // We do our own custom access checks below.
2442 R.suppressDiagnostics();
2443
2444 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002445 OperatorNew, /*Candidates=*/nullptr,
2446 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002447 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002448 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002449
Richard Smithb2f0f052016-10-10 18:54:32 +00002450 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002451 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002452 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002453 return false;
2454 }
2455
Richard Smithb2f0f052016-10-10 18:54:32 +00002456 // Note, the name of OperatorNew might have been changed from array to
2457 // non-array by resolveAllocationOverload.
2458 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2459 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2460 ? OO_Array_Delete
2461 : OO_Delete);
2462
Douglas Gregor6642ca22010-02-26 05:06:18 +00002463 // C++ [expr.new]p19:
2464 //
2465 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002466 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002467 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002468 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002469 // the scope of T. If this lookup fails to find the name, or if
2470 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002471 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002472 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002473 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002474 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002475 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002476 LookupQualifiedName(FoundDelete, RD);
2477 }
John McCallfb6f5262010-03-18 08:19:33 +00002478 if (FoundDelete.isAmbiguous())
2479 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002480
Richard Smithb2f0f052016-10-10 18:54:32 +00002481 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002482 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002483 if (DeleteScope == AFS_Class)
2484 return true;
2485
Douglas Gregor6642ca22010-02-26 05:06:18 +00002486 DeclareGlobalNewDelete();
2487 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2488 }
2489
2490 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002491
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002492 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002493
John McCalld3be2c82010-09-14 21:34:24 +00002494 // Whether we're looking for a placement operator delete is dictated
2495 // by whether we selected a placement operator new, not by whether
2496 // we had explicit placement arguments. This matters for things like
2497 // struct A { void *operator new(size_t, int = 0); ... };
2498 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002499 //
2500 // We don't have any definition for what a "placement allocation function"
2501 // is, but we assume it's any allocation function whose
2502 // parameter-declaration-clause is anything other than (size_t).
2503 //
2504 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2505 // This affects whether an exception from the constructor of an overaligned
2506 // type uses the sized or non-sized form of aligned operator delete.
2507 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2508 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002509
2510 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002511 // C++ [expr.new]p20:
2512 // A declaration of a placement deallocation function matches the
2513 // declaration of a placement allocation function if it has the
2514 // same number of parameters and, after parameter transformations
2515 // (8.3.5), all parameter types except the first are
2516 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002518 // To perform this comparison, we compute the function type that
2519 // the deallocation function should have, and use that type both
2520 // for template argument deduction and for comparison purposes.
2521 QualType ExpectedFunctionType;
2522 {
2523 const FunctionProtoType *Proto
2524 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002525
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002526 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002527 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002528 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2529 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002530
John McCalldb40c7f2010-12-14 08:05:40 +00002531 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002532 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002533 EPI.Variadic = Proto->isVariadic();
2534
Douglas Gregor6642ca22010-02-26 05:06:18 +00002535 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002536 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002537 }
2538
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002540 DEnd = FoundDelete.end();
2541 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002542 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002543 if (FunctionTemplateDecl *FnTmpl =
2544 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002545 // Perform template argument deduction to try to match the
2546 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002547 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002548 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2549 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002550 continue;
2551 } else
2552 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2553
Richard Smithbaa47832016-12-01 02:11:49 +00002554 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2555 ExpectedFunctionType,
2556 /*AdjustExcpetionSpec*/true),
2557 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002558 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002559 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002560
Richard Smithb2f0f052016-10-10 18:54:32 +00002561 if (getLangOpts().CUDA)
2562 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2563 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002564 // C++1y [expr.new]p22:
2565 // For a non-placement allocation function, the normal deallocation
2566 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002567 //
2568 // Per [expr.delete]p10, this lookup prefers a member operator delete
2569 // without a size_t argument, but prefers a non-member operator delete
2570 // with a size_t where possible (which it always is in this case).
2571 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2572 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2573 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2574 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2575 &BestDeallocFns);
2576 if (Selected)
2577 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2578 else {
2579 // If we failed to select an operator, all remaining functions are viable
2580 // but ambiguous.
2581 for (auto Fn : BestDeallocFns)
2582 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002583 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002584 }
2585
2586 // C++ [expr.new]p20:
2587 // [...] If the lookup finds a single matching deallocation
2588 // function, that function will be called; otherwise, no
2589 // deallocation function will be called.
2590 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002591 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002592
Richard Smithb2f0f052016-10-10 18:54:32 +00002593 // C++1z [expr.new]p23:
2594 // If the lookup finds a usual deallocation function (3.7.4.2)
2595 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002596 // as a placement deallocation function, would have been
2597 // selected as a match for the allocation function, the program
2598 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002599 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002600 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002601 UsualDeallocFnInfo Info(*this,
2602 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002603 // Core issue, per mail to core reflector, 2016-10-09:
2604 // If this is a member operator delete, and there is a corresponding
2605 // non-sized member operator delete, this isn't /really/ a sized
2606 // deallocation function, it just happens to have a size_t parameter.
2607 bool IsSizedDelete = Info.HasSizeT;
2608 if (IsSizedDelete && !FoundGlobalDelete) {
2609 auto NonSizedDelete =
2610 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2611 /*WantAlign*/Info.HasAlignValT);
2612 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2613 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2614 IsSizedDelete = false;
2615 }
2616
2617 if (IsSizedDelete) {
2618 SourceRange R = PlaceArgs.empty()
2619 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002620 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002621 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002622 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2623 if (!OperatorDelete->isImplicit())
2624 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2625 << DeleteName;
2626 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002627 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002628
2629 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2630 Matches[0].first);
2631 } else if (!Matches.empty()) {
2632 // We found multiple suitable operators. Per [expr.new]p20, that means we
2633 // call no 'operator delete' function, but we should at least warn the user.
2634 // FIXME: Suppress this warning if the construction cannot throw.
2635 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2636 << DeleteName << AllocElemType;
2637
2638 for (auto &Match : Matches)
2639 Diag(Match.second->getLocation(),
2640 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002641 }
2642
Sebastian Redlfaf68082008-12-03 20:26:15 +00002643 return false;
2644}
2645
2646/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2647/// delete. These are:
2648/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002649/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002650/// void* operator new(std::size_t) throw(std::bad_alloc);
2651/// void* operator new[](std::size_t) throw(std::bad_alloc);
2652/// void operator delete(void *) throw();
2653/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002654/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002655/// void* operator new(std::size_t);
2656/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002657/// void operator delete(void *) noexcept;
2658/// void operator delete[](void *) noexcept;
2659/// // C++1y:
2660/// void* operator new(std::size_t);
2661/// void* operator new[](std::size_t);
2662/// void operator delete(void *) noexcept;
2663/// void operator delete[](void *) noexcept;
2664/// void operator delete(void *, std::size_t) noexcept;
2665/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002666/// @endcode
2667/// Note that the placement and nothrow forms of new are *not* implicitly
2668/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002669void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002670 if (GlobalNewDeleteDeclared)
2671 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002673 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2674 // are not supported.
2675 if (getLangOpts().OpenCLCPlusPlus)
2676 return;
2677
Douglas Gregor87f54062009-09-15 22:30:29 +00002678 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679 // [...] The following allocation and deallocation functions (18.4) are
2680 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002681 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682 //
Sebastian Redl37588092011-03-14 18:08:30 +00002683 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002684 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002685 // void* operator new[](std::size_t) throw(std::bad_alloc);
2686 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002687 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002688 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002689 // void* operator new(std::size_t);
2690 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002691 // void operator delete(void*) noexcept;
2692 // void operator delete[](void*) noexcept;
2693 // C++1y:
2694 // void* operator new(std::size_t);
2695 // void* operator new[](std::size_t);
2696 // void operator delete(void*) noexcept;
2697 // void operator delete[](void*) noexcept;
2698 // void operator delete(void*, std::size_t) noexcept;
2699 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002700 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002702 // new, operator new[], operator delete, operator delete[].
2703 //
2704 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2705 // "std" or "bad_alloc" as necessary to form the exception specification.
2706 // However, we do not make these implicit declarations visible to name
2707 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002708 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002709 // The "std::bad_alloc" class has not yet been declared, so build it
2710 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2712 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002713 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002714 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002715 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002716 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002717 }
Richard Smith59139022016-09-30 22:41:36 +00002718 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002719 // The "std::align_val_t" enum class has not yet been declared, so build it
2720 // implicitly.
2721 auto *AlignValT = EnumDecl::Create(
2722 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2723 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2724 AlignValT->setIntegerType(Context.getSizeType());
2725 AlignValT->setPromotionType(Context.getSizeType());
2726 AlignValT->setImplicit(true);
2727 StdAlignValT = AlignValT;
2728 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002729
Sebastian Redlfaf68082008-12-03 20:26:15 +00002730 GlobalNewDeleteDeclared = true;
2731
2732 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2733 QualType SizeT = Context.getSizeType();
2734
Richard Smith96269c52016-09-29 22:49:46 +00002735 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2736 QualType Return, QualType Param) {
2737 llvm::SmallVector<QualType, 3> Params;
2738 Params.push_back(Param);
2739
2740 // Create up to four variants of the function (sized/aligned).
2741 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2742 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002743 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002744
2745 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2746 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2747 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002748 if (Sized)
2749 Params.push_back(SizeT);
2750
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002751 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002752 if (Aligned)
2753 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2754
2755 DeclareGlobalAllocationFunction(
2756 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2757
2758 if (Aligned)
2759 Params.pop_back();
2760 }
2761 }
2762 };
2763
2764 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2765 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2766 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2767 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002768}
2769
2770/// DeclareGlobalAllocationFunction - Declares a single implicit global
2771/// allocation function if it doesn't already exist.
2772void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002773 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002774 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002775 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2776
2777 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002778 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2779 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2780 Alloc != AllocEnd; ++Alloc) {
2781 // Only look at non-template functions, as it is the predefined,
2782 // non-templated allocation function we are trying to declare here.
2783 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002784 if (Func->getNumParams() == Params.size()) {
2785 llvm::SmallVector<QualType, 3> FuncParams;
2786 for (auto *P : Func->parameters())
2787 FuncParams.push_back(
2788 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2789 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002790 // Make the function visible to name lookup, even if we found it in
2791 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002792 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002793 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002794 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002795 }
Chandler Carruth93538422010-02-03 11:02:14 +00002796 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002797 }
2798 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002799
Richard Smithc015bc22014-02-07 22:39:53 +00002800 FunctionProtoType::ExtProtoInfo EPI;
2801
Richard Smithf8b417c2014-02-08 00:42:45 +00002802 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002804 = (Name.getCXXOverloadedOperator() == OO_New ||
2805 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002806 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002807 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002808 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002809 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002810 EPI.ExceptionSpec.Type = EST_Dynamic;
2811 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002812 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002813 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002814 EPI.ExceptionSpec =
2815 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817
Artem Belevich07db5cf2016-10-21 20:34:05 +00002818 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2819 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2820 FunctionDecl *Alloc = FunctionDecl::Create(
2821 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2822 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2823 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002824 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002825 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002826
Petr Hosek821b38f2018-12-04 03:25:25 +00002827 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2828 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2829 ? VisibilityAttr::Hidden
2830 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831
Artem Belevich07db5cf2016-10-21 20:34:05 +00002832 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2833 for (QualType T : Params) {
2834 ParamDecls.push_back(ParmVarDecl::Create(
2835 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2836 /*TInfo=*/nullptr, SC_None, nullptr));
2837 ParamDecls.back()->setImplicit();
2838 }
2839 Alloc->setParams(ParamDecls);
2840 if (ExtraAttr)
2841 Alloc->addAttr(ExtraAttr);
2842 Context.getTranslationUnitDecl()->addDecl(Alloc);
2843 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2844 };
2845
2846 if (!LangOpts.CUDA)
2847 CreateAllocationFunctionDecl(nullptr);
2848 else {
2849 // Host and device get their own declaration so each can be
2850 // defined or re-declared independently.
2851 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2852 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002853 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002854}
2855
Richard Smith1cdec012013-09-29 04:40:38 +00002856FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2857 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002858 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002859 DeclarationName Name) {
2860 DeclareGlobalNewDelete();
2861
2862 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2863 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2864
Richard Smithb2f0f052016-10-10 18:54:32 +00002865 // FIXME: It's possible for this to result in ambiguity, through a
2866 // user-declared variadic operator delete or the enable_if attribute. We
2867 // should probably not consider those cases to be usual deallocation
2868 // functions. But for now we just make an arbitrary choice in that case.
2869 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2870 Overaligned);
2871 assert(Result.FD && "operator delete missing from global scope?");
2872 return Result.FD;
2873}
Richard Smith1cdec012013-09-29 04:40:38 +00002874
Richard Smithb2f0f052016-10-10 18:54:32 +00002875FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2876 CXXRecordDecl *RD) {
2877 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002878
Richard Smithb2f0f052016-10-10 18:54:32 +00002879 FunctionDecl *OperatorDelete = nullptr;
2880 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2881 return nullptr;
2882 if (OperatorDelete)
2883 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002884
Richard Smithb2f0f052016-10-10 18:54:32 +00002885 // If there's no class-specific operator delete, look up the global
2886 // non-array delete.
2887 return FindUsualDeallocationFunction(
2888 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2889 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002890}
2891
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002892bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2893 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002894 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002895 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002896 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002897 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898
John McCall27b18f82009-11-17 02:14:36 +00002899 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002900 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002901
Chandler Carruthb6f99172010-06-28 00:30:51 +00002902 Found.suppressDiagnostics();
2903
Richard Smithb2f0f052016-10-10 18:54:32 +00002904 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002905
Richard Smithb2f0f052016-10-10 18:54:32 +00002906 // C++17 [expr.delete]p10:
2907 // If the deallocation functions have class scope, the one without a
2908 // parameter of type std::size_t is selected.
2909 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2910 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2911 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002912
Richard Smithb2f0f052016-10-10 18:54:32 +00002913 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002914 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002915 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002916
Richard Smithb2f0f052016-10-10 18:54:32 +00002917 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002918 if (Operator->isDeleted()) {
2919 if (Diagnose) {
2920 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002921 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002922 }
2923 return true;
2924 }
2925
Richard Smith921bd202012-02-26 09:11:52 +00002926 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002927 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002928 return true;
2929
John McCall66a87592010-08-04 00:31:26 +00002930 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002931 }
John McCall66a87592010-08-04 00:31:26 +00002932
Richard Smithb2f0f052016-10-10 18:54:32 +00002933 // We found multiple suitable operators; complain about the ambiguity.
2934 // FIXME: The standard doesn't say to do this; it appears that the intent
2935 // is that this should never happen.
2936 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002937 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002938 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2939 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002940 for (auto &Match : Matches)
2941 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002942 }
John McCall66a87592010-08-04 00:31:26 +00002943 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002944 }
2945
2946 // We did find operator delete/operator delete[] declarations, but
2947 // none of them were suitable.
2948 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002949 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002950 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2951 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
Richard Smithb2f0f052016-10-10 18:54:32 +00002953 for (NamedDecl *D : Found)
2954 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002955 diag::note_member_declared_here) << Name;
2956 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002957 return true;
2958 }
2959
Craig Topperc3ec1492014-05-26 06:22:03 +00002960 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002961 return false;
2962}
2963
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002964namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002965/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002966/// initializing deletee have the same array form.
2967class MismatchingNewDeleteDetector {
2968public:
2969 enum MismatchResult {
2970 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2971 NoMismatch,
2972 /// Indicates that variable is initialized with mismatching form of \a new.
2973 VarInitMismatches,
2974 /// Indicates that member is initialized with mismatching form of \a new.
2975 MemberInitMismatches,
2976 /// Indicates that 1 or more constructors' definitions could not been
2977 /// analyzed, and they will be checked again at the end of translation unit.
2978 AnalyzeLater
2979 };
2980
2981 /// \param EndOfTU True, if this is the final analysis at the end of
2982 /// translation unit. False, if this is the initial analysis at the point
2983 /// delete-expression was encountered.
2984 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002985 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002986 HasUndefinedConstructors(false) {}
2987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002988 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002989 /// matching form of new-expression.
2990 ///
2991 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2992 /// point where delete-expression is encountered, then a warning will be
2993 /// issued immediately. If return value is \c AnalyzeLater at the point where
2994 /// delete-expression is seen, then member will be analyzed at the end of
2995 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2996 /// couldn't be analyzed. If at least one constructor initializes the member
2997 /// with matching type of new, the return value is \c NoMismatch.
2998 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002999 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003000 /// \param Field Class member to analyze.
3001 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3002 /// for deleting the \p Field.
3003 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003004 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003005 /// List of mismatching new-expressions used for initialization of the pointee
3006 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3007 /// Indicates whether delete-expression was in array form.
3008 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003009
3010private:
3011 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003012 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003013 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003014 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003015 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003016 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003017 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003018 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003019 /// \c new either by the member initializer or in-class initialization.
3020 ///
3021 /// If bodies of all constructors are not visible at the end of translation
3022 /// unit or at least one constructor initializes member with the matching
3023 /// form of \c new, mismatch cannot be proven, and this function will return
3024 /// \c NoMismatch.
3025 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003026 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003027 /// \c new.
3028 ///
3029 /// If variable is initialized with matching form of \c new or variable is not
3030 /// initialized with a \c new expression, this function will return true.
3031 /// If variable is initialized with mismatching form of \c new, returns false.
3032 /// \param D Variable to analyze.
3033 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003034 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003035 /// form of \c new.
3036 ///
3037 /// Returns true, if member is initialized with matching form of \c new in
3038 /// member initializer list. Returns false, if member is initialized with the
3039 /// matching form of \c new in this constructor's initializer or given
3040 /// constructor isn't defined at the point where delete-expression is seen, or
3041 /// member isn't initialized by the constructor.
3042 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003043 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003044 /// \c new in member initializer list.
3045 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3046 /// Checks whether member is initialized with mismatching form of \c new by
3047 /// in-class initializer.
3048 MismatchResult analyzeInClassInitializer();
3049};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003050}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003051
3052MismatchingNewDeleteDetector::MismatchResult
3053MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3054 NewExprs.clear();
3055 assert(DE && "Expected delete-expression");
3056 IsArrayForm = DE->isArrayForm();
3057 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3058 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3059 return analyzeMemberExpr(ME);
3060 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3061 if (!hasMatchingVarInit(D))
3062 return VarInitMismatches;
3063 }
3064 return NoMismatch;
3065}
3066
3067const CXXNewExpr *
3068MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3069 assert(E != nullptr && "Expected a valid initializer expression");
3070 E = E->IgnoreParenImpCasts();
3071 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3072 if (ILE->getNumInits() == 1)
3073 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3074 }
3075
3076 return dyn_cast_or_null<const CXXNewExpr>(E);
3077}
3078
3079bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3080 const CXXCtorInitializer *CI) {
3081 const CXXNewExpr *NE = nullptr;
3082 if (Field == CI->getMember() &&
3083 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3084 if (NE->isArray() == IsArrayForm)
3085 return true;
3086 else
3087 NewExprs.push_back(NE);
3088 }
3089 return false;
3090}
3091
3092bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3093 const CXXConstructorDecl *CD) {
3094 if (CD->isImplicit())
3095 return false;
3096 const FunctionDecl *Definition = CD;
3097 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3098 HasUndefinedConstructors = true;
3099 return EndOfTU;
3100 }
3101 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3102 if (hasMatchingNewInCtorInit(CI))
3103 return true;
3104 }
3105 return false;
3106}
3107
3108MismatchingNewDeleteDetector::MismatchResult
3109MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3110 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003111 const Expr *InitExpr = Field->getInClassInitializer();
3112 if (!InitExpr)
3113 return EndOfTU ? NoMismatch : AnalyzeLater;
3114 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003115 if (NE->isArray() != IsArrayForm) {
3116 NewExprs.push_back(NE);
3117 return MemberInitMismatches;
3118 }
3119 }
3120 return NoMismatch;
3121}
3122
3123MismatchingNewDeleteDetector::MismatchResult
3124MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3125 bool DeleteWasArrayForm) {
3126 assert(Field != nullptr && "Analysis requires a valid class member.");
3127 this->Field = Field;
3128 IsArrayForm = DeleteWasArrayForm;
3129 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3130 for (const auto *CD : RD->ctors()) {
3131 if (hasMatchingNewInCtor(CD))
3132 return NoMismatch;
3133 }
3134 if (HasUndefinedConstructors)
3135 return EndOfTU ? NoMismatch : AnalyzeLater;
3136 if (!NewExprs.empty())
3137 return MemberInitMismatches;
3138 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3139 : NoMismatch;
3140}
3141
3142MismatchingNewDeleteDetector::MismatchResult
3143MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3144 assert(ME != nullptr && "Expected a member expression");
3145 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3146 return analyzeField(F, IsArrayForm);
3147 return NoMismatch;
3148}
3149
3150bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3151 const CXXNewExpr *NE = nullptr;
3152 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3153 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3154 NE->isArray() != IsArrayForm) {
3155 NewExprs.push_back(NE);
3156 }
3157 }
3158 return NewExprs.empty();
3159}
3160
3161static void
3162DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3163 const MismatchingNewDeleteDetector &Detector) {
3164 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3165 FixItHint H;
3166 if (!Detector.IsArrayForm)
3167 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3168 else {
3169 SourceLocation RSquare = Lexer::findLocationAfterToken(
3170 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3171 SemaRef.getLangOpts(), true);
3172 if (RSquare.isValid())
3173 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3174 }
3175 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3176 << Detector.IsArrayForm << H;
3177
3178 for (const auto *NE : Detector.NewExprs)
3179 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3180 << Detector.IsArrayForm;
3181}
3182
3183void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3184 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3185 return;
3186 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3187 switch (Detector.analyzeDeleteExpr(DE)) {
3188 case MismatchingNewDeleteDetector::VarInitMismatches:
3189 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003190 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003191 break;
3192 }
3193 case MismatchingNewDeleteDetector::AnalyzeLater: {
3194 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003195 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003196 break;
3197 }
3198 case MismatchingNewDeleteDetector::NoMismatch:
3199 break;
3200 }
3201}
3202
3203void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3204 bool DeleteWasArrayForm) {
3205 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3206 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3207 case MismatchingNewDeleteDetector::VarInitMismatches:
3208 llvm_unreachable("This analysis should have been done for class members.");
3209 case MismatchingNewDeleteDetector::AnalyzeLater:
3210 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3211 "translation unit.");
3212 case MismatchingNewDeleteDetector::MemberInitMismatches:
3213 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3214 break;
3215 case MismatchingNewDeleteDetector::NoMismatch:
3216 break;
3217 }
3218}
3219
Sebastian Redlbd150f42008-11-21 19:14:01 +00003220/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3221/// @code ::delete ptr; @endcode
3222/// or
3223/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003224ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003225Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003226 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003227 // C++ [expr.delete]p1:
3228 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003229 // non-explicit conversion function to a pointer type. The result has type
3230 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003231 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003232 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3233
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003234 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003235 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003236 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003237 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003238
John Wiegley01296292011-04-08 18:41:53 +00003239 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003240 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003241 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003242 if (Ex.isInvalid())
3243 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003244
John Wiegley01296292011-04-08 18:41:53 +00003245 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003246
Richard Smithccc11812013-05-21 19:05:48 +00003247 class DeleteConverter : public ContextualImplicitConverter {
3248 public:
3249 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250
Craig Toppere14c0f82014-03-12 04:55:44 +00003251 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003252 // FIXME: If we have an operator T* and an operator void*, we must pick
3253 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003254 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003255 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003256 return true;
3257 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003258 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003259
Richard Smithccc11812013-05-21 19:05:48 +00003260 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003261 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003262 return S.Diag(Loc, diag::err_delete_operand) << T;
3263 }
3264
3265 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003266 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003267 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3268 }
3269
3270 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003271 QualType T,
3272 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003273 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3274 }
3275
3276 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003277 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003278 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3279 << ConvTy;
3280 }
3281
3282 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003283 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003284 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3285 }
3286
3287 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003288 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003289 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3290 << ConvTy;
3291 }
3292
3293 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003294 QualType T,
3295 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003296 llvm_unreachable("conversion functions are permitted");
3297 }
3298 } Converter;
3299
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003300 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003301 if (Ex.isInvalid())
3302 return ExprError();
3303 Type = Ex.get()->getType();
3304 if (!Converter.match(Type))
3305 // FIXME: PerformContextualImplicitConversion should return ExprError
3306 // itself in this case.
3307 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003308
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003309 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003310 QualType PointeeElem = Context.getBaseElementType(Pointee);
3311
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003312 if (Pointee.getAddressSpace() != LangAS::Default &&
3313 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003314 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003315 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003316 << Pointee.getUnqualifiedType()
3317 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003318
Craig Topperc3ec1492014-05-26 06:22:03 +00003319 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003320 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003322 // effectively bans deletion of "void*". However, most compilers support
3323 // this, so we treat it as a warning unless we're in a SFINAE context.
3324 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003325 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003326 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003327 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003328 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003329 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003330 // FIXME: This can result in errors if the definition was imported from a
3331 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003332 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003333 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003334 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3335 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3336 }
3337 }
3338
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003339 if (Pointee->isArrayType() && !ArrayForm) {
3340 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003341 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003342 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003343 ArrayForm = true;
3344 }
3345
Anders Carlssona471db02009-08-16 20:29:29 +00003346 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3347 ArrayForm ? OO_Array_Delete : OO_Delete);
3348
Eli Friedmanae4280f2011-07-26 22:25:31 +00003349 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003351 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3352 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003353 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354
John McCall284c48f2011-01-27 09:37:56 +00003355 // If we're allocating an array of records, check whether the
3356 // usual operator delete[] has a size_t parameter.
3357 if (ArrayForm) {
3358 // If the user specifically asked to use the global allocator,
3359 // we'll need to do the lookup into the class.
3360 if (UseGlobal)
3361 UsualArrayDeleteWantsSize =
3362 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3363
3364 // Otherwise, the usual operator delete[] should be the
3365 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003366 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003367 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003368 UsualDeallocFnInfo(*this,
3369 DeclAccessPair::make(OperatorDelete, AS_public))
3370 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003371 }
3372
Richard Smitheec915d62012-02-18 04:13:32 +00003373 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003374 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003375 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003376 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003377 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3378 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003379 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003380
Nico Weber5a9259c2016-01-15 21:45:31 +00003381 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3382 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3383 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3384 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386
Richard Smithb2f0f052016-10-10 18:54:32 +00003387 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003388 if (getLangOpts().OpenCLCPlusPlus) {
3389 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3390 return ExprError();
3391 }
3392
Richard Smithb2f0f052016-10-10 18:54:32 +00003393 bool IsComplete = isCompleteType(StartLoc, Pointee);
3394 bool CanProvideSize =
3395 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3396 Pointee.isDestructedType());
3397 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3398
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003399 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003400 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3401 Overaligned, DeleteName);
3402 }
Mike Stump11289f42009-09-09 15:08:12 +00003403
Eli Friedmanfa0df832012-02-02 03:46:19 +00003404 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003405
Richard Smith5b349582017-10-13 01:55:36 +00003406 // Check access and ambiguity of destructor if we're going to call it.
3407 // Note that this is required even for a virtual delete.
3408 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003409 if (PointeeRD) {
3410 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003411 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3412 PDiag(diag::err_access_dtor) << PointeeElem);
3413 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003414 }
3415 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003416
Akira Hatanaka71645c22018-12-21 07:05:36 +00003417 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003418
3419 // Convert the operand to the type of the first parameter of operator
3420 // delete. This is only necessary if we selected a destroying operator
3421 // delete that we are going to call (non-virtually); converting to void*
3422 // is trivial and left to AST consumers to handle.
3423 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3424 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003425 Qualifiers Qs = Pointee.getQualifiers();
3426 if (Qs.hasCVRQualifiers()) {
3427 // Qualifiers are irrelevant to this conversion; we're only looking
3428 // for access and ambiguity.
3429 Qs.removeCVRQualifiers();
3430 QualType Unqual = Context.getPointerType(
3431 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3432 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3433 }
Richard Smith5b349582017-10-13 01:55:36 +00003434 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3435 if (Ex.isInvalid())
3436 return ExprError();
3437 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003438 }
3439
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003440 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003441 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3442 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003443 AnalyzeDeleteExprMismatch(Result);
3444 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003445}
3446
Eric Fiselierfa752f22018-03-21 19:19:48 +00003447static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3448 bool IsDelete,
3449 FunctionDecl *&Operator) {
3450
3451 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3452 IsDelete ? OO_Delete : OO_New);
3453
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003454 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003455 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3456 assert(!R.empty() && "implicitly declared allocation functions not found");
3457 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3458
3459 // We do our own custom access checks below.
3460 R.suppressDiagnostics();
3461
3462 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3463 OverloadCandidateSet Candidates(R.getNameLoc(),
3464 OverloadCandidateSet::CSK_Normal);
3465 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3466 FnOvl != FnOvlEnd; ++FnOvl) {
3467 // Even member operator new/delete are implicitly treated as
3468 // static, so don't use AddMemberCandidate.
3469 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3470
3471 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3472 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3473 /*ExplicitTemplateArgs=*/nullptr, Args,
3474 Candidates,
3475 /*SuppressUserConversions=*/false);
3476 continue;
3477 }
3478
3479 FunctionDecl *Fn = cast<FunctionDecl>(D);
3480 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3481 /*SuppressUserConversions=*/false);
3482 }
3483
3484 SourceRange Range = TheCall->getSourceRange();
3485
3486 // Do the resolution.
3487 OverloadCandidateSet::iterator Best;
3488 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3489 case OR_Success: {
3490 // Got one!
3491 FunctionDecl *FnDecl = Best->Function;
3492 assert(R.getNamingClass() == nullptr &&
3493 "class members should not be considered");
3494
3495 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3496 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3497 << (IsDelete ? 1 : 0) << Range;
3498 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3499 << R.getLookupName() << FnDecl->getSourceRange();
3500 return true;
3501 }
3502
3503 Operator = FnDecl;
3504 return false;
3505 }
3506
3507 case OR_No_Viable_Function:
3508 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3509 << R.getLookupName() << Range;
3510 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3511 return true;
3512
3513 case OR_Ambiguous:
3514 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3515 << R.getLookupName() << Range;
3516 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3517 return true;
3518
3519 case OR_Deleted: {
3520 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3521 << Best->Function->isDeleted() << R.getLookupName()
3522 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3523 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3524 return true;
3525 }
3526 }
3527 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3528}
3529
3530ExprResult
3531Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3532 bool IsDelete) {
3533 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3534 if (!getLangOpts().CPlusPlus) {
3535 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3536 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3537 << "C++";
3538 return ExprError();
3539 }
3540 // CodeGen assumes it can find the global new and delete to call,
3541 // so ensure that they are declared.
3542 DeclareGlobalNewDelete();
3543
3544 FunctionDecl *OperatorNewOrDelete = nullptr;
3545 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3546 OperatorNewOrDelete))
3547 return ExprError();
3548 assert(OperatorNewOrDelete && "should be found");
3549
Akira Hatanaka71645c22018-12-21 07:05:36 +00003550 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3551 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3552
Eric Fiselierfa752f22018-03-21 19:19:48 +00003553 TheCall->setType(OperatorNewOrDelete->getReturnType());
3554 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3555 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3556 InitializedEntity Entity =
3557 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3558 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003559 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003560 if (Arg.isInvalid())
3561 return ExprError();
3562 TheCall->setArg(i, Arg.get());
3563 }
3564 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3565 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3566 "Callee expected to be implicit cast to a builtin function pointer");
3567 Callee->setType(OperatorNewOrDelete->getType());
3568
3569 return TheCallResult;
3570}
3571
Nico Weber5a9259c2016-01-15 21:45:31 +00003572void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3573 bool IsDelete, bool CallCanBeVirtual,
3574 bool WarnOnNonAbstractTypes,
3575 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003576 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003577 return;
3578
3579 // C++ [expr.delete]p3:
3580 // In the first alternative (delete object), if the static type of the
3581 // object to be deleted is different from its dynamic type, the static
3582 // type shall be a base class of the dynamic type of the object to be
3583 // deleted and the static type shall have a virtual destructor or the
3584 // behavior is undefined.
3585 //
3586 const CXXRecordDecl *PointeeRD = dtor->getParent();
3587 // Note: a final class cannot be derived from, no issue there
3588 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3589 return;
3590
Nico Weberbf2260c2017-08-31 06:17:08 +00003591 // If the superclass is in a system header, there's nothing that can be done.
3592 // The `delete` (where we emit the warning) can be in a system header,
3593 // what matters for this warning is where the deleted type is defined.
3594 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3595 return;
3596
Brian Gesiak5488ab42019-01-11 01:54:53 +00003597 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003598 if (PointeeRD->isAbstract()) {
3599 // If the class is abstract, we warn by default, because we're
3600 // sure the code has undefined behavior.
3601 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3602 << ClassType;
3603 } else if (WarnOnNonAbstractTypes) {
3604 // Otherwise, if this is not an array delete, it's a bit suspect,
3605 // but not necessarily wrong.
3606 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3607 << ClassType;
3608 }
3609 if (!IsDelete) {
3610 std::string TypeStr;
3611 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3612 Diag(DtorLoc, diag::note_delete_non_virtual)
3613 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3614 }
3615}
3616
Richard Smith03a4aa32016-06-23 19:02:52 +00003617Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3618 SourceLocation StmtLoc,
3619 ConditionKind CK) {
3620 ExprResult E =
3621 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3622 if (E.isInvalid())
3623 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003624 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3625 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003626}
3627
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003628/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003629/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003630ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003631 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003632 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003633 if (ConditionVar->isInvalidDecl())
3634 return ExprError();
3635
Douglas Gregor633caca2009-11-23 23:44:04 +00003636 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637
Douglas Gregor633caca2009-11-23 23:44:04 +00003638 // C++ [stmt.select]p2:
3639 // The declarator shall not specify a function or an array.
3640 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003642 diag::err_invalid_use_of_function_type)
3643 << ConditionVar->getSourceRange());
3644 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003646 diag::err_invalid_use_of_array_type)
3647 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003648
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003649 ExprResult Condition = DeclRefExpr::Create(
3650 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3651 /*enclosing*/ false, ConditionVar->getLocation(),
3652 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003653
Eli Friedmanfa0df832012-02-02 03:46:19 +00003654 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003655
Richard Smith03a4aa32016-06-23 19:02:52 +00003656 switch (CK) {
3657 case ConditionKind::Boolean:
3658 return CheckBooleanCondition(StmtLoc, Condition.get());
3659
Richard Smithb130fe72016-06-23 19:16:49 +00003660 case ConditionKind::ConstexprIf:
3661 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3662
Richard Smith03a4aa32016-06-23 19:02:52 +00003663 case ConditionKind::Switch:
3664 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003665 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666
Richard Smith03a4aa32016-06-23 19:02:52 +00003667 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003668}
3669
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003670/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003671ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003672 // C++ 6.4p4:
3673 // The value of a condition that is an initialized declaration in a statement
3674 // other than a switch statement is the value of the declared variable
3675 // implicitly converted to type bool. If that conversion is ill-formed, the
3676 // program is ill-formed.
3677 // The value of a condition that is an expression is the value of the
3678 // expression, implicitly converted to bool.
3679 //
Richard Smithb130fe72016-06-23 19:16:49 +00003680 // FIXME: Return this value to the caller so they don't need to recompute it.
3681 llvm::APSInt Value(/*BitWidth*/1);
3682 return (IsConstexpr && !CondExpr->isValueDependent())
3683 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3684 CCEK_ConstexprIf)
3685 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003686}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003687
3688/// Helper function to determine whether this is the (deprecated) C++
3689/// conversion from a string literal to a pointer to non-const char or
3690/// non-const wchar_t (for narrow and wide string literals,
3691/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003692bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003693Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3694 // Look inside the implicit cast, if it exists.
3695 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3696 From = Cast->getSubExpr();
3697
3698 // A string literal (2.13.4) that is not a wide string literal can
3699 // be converted to an rvalue of type "pointer to char"; a wide
3700 // string literal can be converted to an rvalue of type "pointer
3701 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003702 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003703 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003704 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003705 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003706 // This conversion is considered only when there is an
3707 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003708 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3709 switch (StrLit->getKind()) {
3710 case StringLiteral::UTF8:
3711 case StringLiteral::UTF16:
3712 case StringLiteral::UTF32:
3713 // We don't allow UTF literals to be implicitly converted
3714 break;
3715 case StringLiteral::Ascii:
3716 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3717 ToPointeeType->getKind() == BuiltinType::Char_S);
3718 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003719 return Context.typesAreCompatible(Context.getWideCharType(),
3720 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003721 }
3722 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003723 }
3724
3725 return false;
3726}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003729 SourceLocation CastLoc,
3730 QualType Ty,
3731 CastKind Kind,
3732 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003733 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003734 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003735 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003736 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003737 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003738 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003739 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003740 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741
Richard Smith72d74052013-07-20 19:41:36 +00003742 if (S.RequireNonAbstractType(CastLoc, Ty,
3743 diag::err_allocation_of_abstract_type))
3744 return ExprError();
3745
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003746 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003747 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748
Richard Smith5179eb72016-06-28 19:03:57 +00003749 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3750 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003751 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003752 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003753
Richard Smithf8adcdc2014-07-17 05:12:35 +00003754 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003755 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003756 ConstructorArgs, HadMultipleCandidates,
3757 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3758 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003759 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003760 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003762 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
John McCalle3027922010-08-25 11:45:40 +00003765 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003766 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
Richard Smithd3f2d322015-02-24 21:16:19 +00003768 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003769 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003770 return ExprError();
3771
Douglas Gregora4253922010-04-16 22:17:36 +00003772 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003773 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3774 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003775 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003776 if (Result.isInvalid())
3777 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003778 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003779 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3780 CK_UserDefinedConversion, Result.get(),
3781 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782
Douglas Gregor668443e2011-01-20 00:18:04 +00003783 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003784 }
3785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786}
Douglas Gregora4253922010-04-16 22:17:36 +00003787
Douglas Gregor5fb53972009-01-14 15:45:31 +00003788/// PerformImplicitConversion - Perform an implicit conversion of the
3789/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003790/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003791/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003792/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003793ExprResult
3794Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003795 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003796 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003797 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003798 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3799 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3800 return From;
3801
John McCall0d1da222010-01-12 00:44:57 +00003802 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003803 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003804 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3805 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003806 if (Res.isInvalid())
3807 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003808 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003809 break;
John Wiegley01296292011-04-08 18:41:53 +00003810 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003811
Anders Carlsson110b07b2009-09-15 06:28:28 +00003812 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003814 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003815 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003816 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003817 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003818 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003819 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Anders Carlsson110b07b2009-09-15 06:28:28 +00003821 // If the user-defined conversion is specified by a conversion function,
3822 // the initial standard conversion sequence converts the source type to
3823 // the implicit object parameter of the conversion function.
3824 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003825 } else {
3826 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003827 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003828 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003829 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003831 // initial standard conversion sequence converts the source type to
3832 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003833 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835 }
Richard Smith72d74052013-07-20 19:41:36 +00003836 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003837 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003838 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003839 PerformImplicitConversion(From, BeforeToType,
3840 ICS.UserDefined.Before, AA_Converting,
3841 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003842 if (Res.isInvalid())
3843 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003844 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003847 ExprResult CastArg = BuildCXXCastArgument(
3848 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3849 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3850 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003851
3852 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003853 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003854
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003855 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003856
Richard Smith1ef75542018-06-27 20:30:34 +00003857 // C++ [over.match.oper]p7:
3858 // [...] the second standard conversion sequence of a user-defined
3859 // conversion sequence is not applied.
3860 if (CCK == CCK_ForBuiltinOverloadedOp)
3861 return From;
3862
Richard Smith507840d2011-11-29 22:48:16 +00003863 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3864 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003865 }
John McCall0d1da222010-01-12 00:44:57 +00003866
3867 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003868 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003869 PDiag(diag::err_typecheck_ambiguous_condition)
3870 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003871 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003872
Douglas Gregor39c16d42008-10-24 04:54:22 +00003873 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003874 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003875
3876 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003877 bool Diagnosed =
3878 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3879 From->getType(), From, Action);
3880 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003881 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003882 }
3883
3884 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003885 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003886}
3887
Richard Smith507840d2011-11-29 22:48:16 +00003888/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003889/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003890/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003891/// expression. Flavor is the context in which we're performing this
3892/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003893ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003894Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003895 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003896 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003897 CheckedConversionKind CCK) {
3898 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003899
Mike Stump87c57ac2009-05-16 07:39:55 +00003900 // Overall FIXME: we are recomputing too many types here and doing far too
3901 // much extra work. What this means is that we need to keep track of more
3902 // information that is computed when we try the implicit conversion initially,
3903 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003904 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003905
Douglas Gregor2fe98832008-11-03 19:09:14 +00003906 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003907 // FIXME: When can ToType be a reference type?
3908 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003909 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003910 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003911 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003912 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003913 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003914 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003915 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003916 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3917 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003918 ConstructorArgs, /*HadMultipleCandidates*/ false,
3919 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3920 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003921 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003922 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003923 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3924 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003925 From, /*HadMultipleCandidates*/ false,
3926 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3927 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003928 }
3929
Douglas Gregor980fb162010-04-29 18:24:40 +00003930 // Resolve overloaded function references.
3931 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3932 DeclAccessPair Found;
3933 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3934 true, Found);
3935 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003936 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003937
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003938 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003939 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940
Douglas Gregor980fb162010-04-29 18:24:40 +00003941 From = FixOverloadedFunctionReference(From, Found, Fn);
3942 FromType = From->getType();
3943 }
3944
Richard Smitha23ab512013-05-23 00:30:41 +00003945 // If we're converting to an atomic type, first convert to the corresponding
3946 // non-atomic type.
3947 QualType ToAtomicType;
3948 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3949 ToAtomicType = ToType;
3950 ToType = ToAtomic->getValueType();
3951 }
3952
George Burgess IV8d141e02015-12-14 22:00:49 +00003953 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003954 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003955 switch (SCS.First) {
3956 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003957 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3958 FromType = FromAtomic->getValueType().getUnqualifiedType();
3959 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3960 From, /*BasePath=*/nullptr, VK_RValue);
3961 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003962 break;
3963
Eli Friedman946b7b52012-01-24 22:51:26 +00003964 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003965 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003966 ExprResult FromRes = DefaultLvalueConversion(From);
3967 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003968 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003969 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003970 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003971 }
John McCall34376a62010-12-04 03:47:34 +00003972
Douglas Gregor39c16d42008-10-24 04:54:22 +00003973 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003974 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003975 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003976 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003977 break;
3978
3979 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003980 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003981 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003982 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003983 break;
3984
3985 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003986 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003987 }
3988
Richard Smith507840d2011-11-29 22:48:16 +00003989 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003990 switch (SCS.Second) {
3991 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003992 // C++ [except.spec]p5:
3993 // [For] assignment to and initialization of pointers to functions,
3994 // pointers to member functions, and references to functions: the
3995 // target entity shall allow at least the exceptions allowed by the
3996 // source value in the assignment or initialization.
3997 switch (Action) {
3998 case AA_Assigning:
3999 case AA_Initializing:
4000 // Note, function argument passing and returning are initialization.
4001 case AA_Passing:
4002 case AA_Returning:
4003 case AA_Sending:
4004 case AA_Passing_CFAudited:
4005 if (CheckExceptionSpecCompatibility(From, ToType))
4006 return ExprError();
4007 break;
4008
4009 case AA_Casting:
4010 case AA_Converting:
4011 // Casts and implicit conversions are not initialization, so are not
4012 // checked for exception specification mismatches.
4013 break;
4014 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004015 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004016 break;
4017
4018 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004019 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004020 if (ToType->isBooleanType()) {
4021 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4022 SCS.Second == ICK_Integral_Promotion &&
4023 "only enums with fixed underlying type can promote to bool");
4024 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004025 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004026 } else {
4027 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004028 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004029 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004030 break;
4031
4032 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004033 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004034 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004035 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004036 break;
4037
4038 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004039 case ICK_Complex_Conversion: {
4040 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4041 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4042 CastKind CK;
4043 if (FromEl->isRealFloatingType()) {
4044 if (ToEl->isRealFloatingType())
4045 CK = CK_FloatingComplexCast;
4046 else
4047 CK = CK_FloatingComplexToIntegralComplex;
4048 } else if (ToEl->isRealFloatingType()) {
4049 CK = CK_IntegralComplexToFloatingComplex;
4050 } else {
4051 CK = CK_IntegralComplexCast;
4052 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004053 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004054 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004055 break;
John McCall8cb679e2010-11-15 09:13:47 +00004056 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004057
Douglas Gregor39c16d42008-10-24 04:54:22 +00004058 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004059 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004060 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004061 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004062 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004063 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004064 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004065 break;
4066
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004067 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004068 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004069 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004070 break;
4071
John McCall31168b02011-06-15 23:02:42 +00004072 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004073 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004074 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004075 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004076 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004077 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004078 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004079 << ToType << From->getType() << Action << From->getSourceRange()
4080 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004081 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004082 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004083 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004084 << From->getType() << ToType << Action << From->getSourceRange()
4085 << 0;
John McCall31168b02011-06-15 23:02:42 +00004086
Douglas Gregor33823722011-06-11 01:09:30 +00004087 if (From->getType()->isObjCObjectPointerType() &&
4088 ToType->isObjCObjectPointerType())
4089 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004090 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4091 !CheckObjCARCUnavailableWeakConversion(ToType,
4092 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004093 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004094 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004095 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004096 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4097 << (Action == AA_Casting) << From->getType() << ToType
4098 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004099 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004100
Richard Smith354abec2017-12-08 23:29:59 +00004101 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004102 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004103 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004104 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004105
4106 // Make sure we extend blocks if necessary.
4107 // FIXME: doing this here is really ugly.
4108 if (Kind == CK_BlockPointerToObjCPointerCast) {
4109 ExprResult E = From;
4110 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004111 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004112 }
Brian Kelley11352a82017-03-29 18:09:02 +00004113 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4114 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004115 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004116 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004117 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004120 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004121 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004122 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004123 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004124 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004125 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004126 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004127
4128 // We may not have been able to figure out what this member pointer resolved
4129 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004130 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004131 (void)isCompleteType(From->getExprLoc(), From->getType());
4132 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004133 }
David Majnemerd96b9972014-08-08 00:10:39 +00004134
Richard Smith507840d2011-11-29 22:48:16 +00004135 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004136 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004137 break;
4138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004140 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004141 // Perform half-to-boolean conversion via float.
4142 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004143 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004144 FromType = Context.FloatTy;
4145 }
4146
Richard Smith507840d2011-11-29 22:48:16 +00004147 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004148 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004149 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004150 break;
4151
Douglas Gregor88d292c2010-05-13 16:44:06 +00004152 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004153 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004154 if (CheckDerivedToBaseConversion(
4155 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4156 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004157 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004158
Richard Smith507840d2011-11-29 22:48:16 +00004159 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4160 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004161 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004162 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004163 }
4164
Douglas Gregor46188682010-05-18 22:42:18 +00004165 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004166 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004167 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004168 break;
4169
George Burgess IVdf1ed002016-01-13 01:52:39 +00004170 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004171 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004172 Expr *Elem = prepareVectorSplat(ToType, From).get();
4173 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4174 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004175 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177
Douglas Gregor46188682010-05-18 22:42:18 +00004178 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004179 // Case 1. x -> _Complex y
4180 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4181 QualType ElType = ToComplex->getElementType();
4182 bool isFloatingComplex = ElType->isRealFloatingType();
4183
4184 // x -> y
4185 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4186 // do nothing
4187 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004188 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004189 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004190 } else {
4191 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004192 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004193 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004194 }
4195 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004196 From = ImpCastExprToType(From, ToType,
4197 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004198 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004199
4200 // Case 2. _Complex x -> y
4201 } else {
4202 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4203 assert(FromComplex);
4204
4205 QualType ElType = FromComplex->getElementType();
4206 bool isFloatingComplex = ElType->isRealFloatingType();
4207
4208 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004209 From = ImpCastExprToType(From, ElType,
4210 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004211 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004212 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004213
4214 // x -> y
4215 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4216 // do nothing
4217 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004218 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004219 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004220 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004221 } else {
4222 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004223 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004224 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004225 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004226 }
4227 }
Douglas Gregor46188682010-05-18 22:42:18 +00004228 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004229
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004230 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004231 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004232 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004233 break;
4234 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004235
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004236 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004237 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004238 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004239 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4240 if (FromRes.isInvalid())
4241 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004242 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004243 assert ((ConvTy == Sema::Compatible) &&
4244 "Improper transparent union conversion");
4245 (void)ConvTy;
4246 break;
4247 }
4248
Guy Benyei259f9f42013-02-07 16:05:33 +00004249 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004250 case ICK_Zero_Queue_Conversion:
4251 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004252 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004253 From->getValueKind()).get();
4254 break;
4255
Douglas Gregor46188682010-05-18 22:42:18 +00004256 case ICK_Lvalue_To_Rvalue:
4257 case ICK_Array_To_Pointer:
4258 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004259 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004260 case ICK_Qualification:
4261 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004262 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004263 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004264 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004265 }
4266
4267 switch (SCS.Third) {
4268 case ICK_Identity:
4269 // Nothing to do.
4270 break;
4271
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004272 case ICK_Function_Conversion:
4273 // If both sides are functions (or pointers/references to them), there could
4274 // be incompatible exception declarations.
4275 if (CheckExceptionSpecCompatibility(From, ToType))
4276 return ExprError();
4277
4278 From = ImpCastExprToType(From, ToType, CK_NoOp,
4279 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4280 break;
4281
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004282 case ICK_Qualification: {
4283 // The qualification keeps the category of the inner expression, unless the
4284 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004285 ExprValueKind VK =
4286 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4287
4288 CastKind CK = CK_NoOp;
4289
4290 if (ToType->isReferenceType() &&
4291 ToType->getPointeeType().getAddressSpace() !=
4292 From->getType().getAddressSpace())
4293 CK = CK_AddressSpaceConversion;
4294
4295 if (ToType->isPointerType() &&
4296 ToType->getPointeeType().getAddressSpace() !=
4297 From->getType()->getPointeeType().getAddressSpace())
4298 CK = CK_AddressSpaceConversion;
4299
4300 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4301 /*BasePath=*/nullptr, CCK)
4302 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004303
Douglas Gregore981bb02011-03-14 16:13:32 +00004304 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004305 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004306 Diag(From->getBeginLoc(),
4307 getLangOpts().CPlusPlus11
4308 ? diag::ext_deprecated_string_literal_conversion
4309 : diag::warn_deprecated_string_literal_conversion)
4310 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004311 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004312
Douglas Gregor39c16d42008-10-24 04:54:22 +00004313 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004314 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004315
Douglas Gregor39c16d42008-10-24 04:54:22 +00004316 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004317 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004318 }
4319
Douglas Gregor298f43d2012-04-12 20:42:30 +00004320 // If this conversion sequence involved a scalar -> atomic conversion, perform
4321 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004322 if (!ToAtomicType.isNull()) {
4323 assert(Context.hasSameType(
4324 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4325 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004326 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004327 }
4328
George Burgess IV8d141e02015-12-14 22:00:49 +00004329 // If this conversion sequence succeeded and involved implicitly converting a
4330 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004331 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004332 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004333 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004334
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004335 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004336}
4337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004338/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004339///
4340/// If the particular type trait requires a complete type, tries to complete
4341/// it. If completing the type fails, a diagnostic is emitted and false
4342/// returned. If completing the type succeeds or no completion was required,
4343/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004344static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004345 SourceLocation Loc,
4346 QualType ArgTy) {
4347 // C++0x [meta.unary.prop]p3:
4348 // For all of the class templates X declared in this Clause, instantiating
4349 // that template with a template argument that is a class template
4350 // specialization may result in the implicit instantiation of the template
4351 // argument if and only if the semantics of X require that the argument
4352 // must be a complete type.
4353 // We apply this rule to all the type trait expressions used to implement
4354 // these class templates. We also try to follow any GCC documented behavior
4355 // in these expressions to ensure portability of standard libraries.
4356 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004357 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004358 // is_complete_type somewhat obviously cannot require a complete type.
4359 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004360 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004361
4362 // These traits are modeled on the type predicates in C++0x
4363 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4364 // requiring a complete type, as whether or not they return true cannot be
4365 // impacted by the completeness of the type.
4366 case UTT_IsVoid:
4367 case UTT_IsIntegral:
4368 case UTT_IsFloatingPoint:
4369 case UTT_IsArray:
4370 case UTT_IsPointer:
4371 case UTT_IsLvalueReference:
4372 case UTT_IsRvalueReference:
4373 case UTT_IsMemberFunctionPointer:
4374 case UTT_IsMemberObjectPointer:
4375 case UTT_IsEnum:
4376 case UTT_IsUnion:
4377 case UTT_IsClass:
4378 case UTT_IsFunction:
4379 case UTT_IsReference:
4380 case UTT_IsArithmetic:
4381 case UTT_IsFundamental:
4382 case UTT_IsObject:
4383 case UTT_IsScalar:
4384 case UTT_IsCompound:
4385 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004386 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004387
4388 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4389 // which requires some of its traits to have the complete type. However,
4390 // the completeness of the type cannot impact these traits' semantics, and
4391 // so they don't require it. This matches the comments on these traits in
4392 // Table 49.
4393 case UTT_IsConst:
4394 case UTT_IsVolatile:
4395 case UTT_IsSigned:
4396 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004397
4398 // This type trait always returns false, checking the type is moot.
4399 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004400 return true;
4401
David Majnemer213bea32015-11-16 06:58:51 +00004402 // C++14 [meta.unary.prop]:
4403 // If T is a non-union class type, T shall be a complete type.
4404 case UTT_IsEmpty:
4405 case UTT_IsPolymorphic:
4406 case UTT_IsAbstract:
4407 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4408 if (!RD->isUnion())
4409 return !S.RequireCompleteType(
4410 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4411 return true;
4412
4413 // C++14 [meta.unary.prop]:
4414 // If T is a class type, T shall be a complete type.
4415 case UTT_IsFinal:
4416 case UTT_IsSealed:
4417 if (ArgTy->getAsCXXRecordDecl())
4418 return !S.RequireCompleteType(
4419 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4420 return true;
4421
Richard Smithf03e9082017-06-01 00:28:16 +00004422 // C++1z [meta.unary.prop]:
4423 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004424 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004425 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004426 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004427 case UTT_IsStandardLayout:
4428 case UTT_IsPOD:
4429 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004430 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4431 // or an array of unknown bound. But GCC actually imposes the same constraints
4432 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004433 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004434 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004435 case UTT_HasNothrowConstructor:
4436 case UTT_HasNothrowCopy:
4437 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004438 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004439 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004440 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004441 case UTT_HasTrivialCopy:
4442 case UTT_HasTrivialDestructor:
4443 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004444 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4445 LLVM_FALLTHROUGH;
4446
4447 // C++1z [meta.unary.prop]:
4448 // T shall be a complete type, cv void, or an array of unknown bound.
4449 case UTT_IsDestructible:
4450 case UTT_IsNothrowDestructible:
4451 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004452 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004453 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004454 return true;
4455
4456 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004457 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004458 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004459}
4460
Joao Matosc9523d42013-03-27 01:34:16 +00004461static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4462 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004463 bool (CXXRecordDecl::*HasTrivial)() const,
4464 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004465 bool (CXXMethodDecl::*IsDesiredOp)() const)
4466{
4467 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4468 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4469 return true;
4470
4471 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4472 DeclarationNameInfo NameInfo(Name, KeyLoc);
4473 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4474 if (Self.LookupQualifiedName(Res, RD)) {
4475 bool FoundOperator = false;
4476 Res.suppressDiagnostics();
4477 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4478 Op != OpEnd; ++Op) {
4479 if (isa<FunctionTemplateDecl>(*Op))
4480 continue;
4481
4482 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4483 if((Operator->*IsDesiredOp)()) {
4484 FoundOperator = true;
4485 const FunctionProtoType *CPT =
4486 Operator->getType()->getAs<FunctionProtoType>();
4487 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004488 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004489 return false;
4490 }
4491 }
4492 return FoundOperator;
4493 }
4494 return false;
4495}
4496
Alp Toker95e7ff22014-01-01 05:57:51 +00004497static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004498 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004499 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004500
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004501 ASTContext &C = Self.Context;
4502 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004503 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004504 // Type trait expressions corresponding to the primary type category
4505 // predicates in C++0x [meta.unary.cat].
4506 case UTT_IsVoid:
4507 return T->isVoidType();
4508 case UTT_IsIntegral:
4509 return T->isIntegralType(C);
4510 case UTT_IsFloatingPoint:
4511 return T->isFloatingType();
4512 case UTT_IsArray:
4513 return T->isArrayType();
4514 case UTT_IsPointer:
4515 return T->isPointerType();
4516 case UTT_IsLvalueReference:
4517 return T->isLValueReferenceType();
4518 case UTT_IsRvalueReference:
4519 return T->isRValueReferenceType();
4520 case UTT_IsMemberFunctionPointer:
4521 return T->isMemberFunctionPointerType();
4522 case UTT_IsMemberObjectPointer:
4523 return T->isMemberDataPointerType();
4524 case UTT_IsEnum:
4525 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004526 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004527 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004528 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004529 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004530 case UTT_IsFunction:
4531 return T->isFunctionType();
4532
4533 // Type trait expressions which correspond to the convenient composition
4534 // predicates in C++0x [meta.unary.comp].
4535 case UTT_IsReference:
4536 return T->isReferenceType();
4537 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004538 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004539 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004540 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004541 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004542 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004543 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004544 // Note: semantic analysis depends on Objective-C lifetime types to be
4545 // considered scalar types. However, such types do not actually behave
4546 // like scalar types at run time (since they may require retain/release
4547 // operations), so we report them as non-scalar.
4548 if (T->isObjCLifetimeType()) {
4549 switch (T.getObjCLifetime()) {
4550 case Qualifiers::OCL_None:
4551 case Qualifiers::OCL_ExplicitNone:
4552 return true;
4553
4554 case Qualifiers::OCL_Strong:
4555 case Qualifiers::OCL_Weak:
4556 case Qualifiers::OCL_Autoreleasing:
4557 return false;
4558 }
4559 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004560
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004561 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004562 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004563 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004564 case UTT_IsMemberPointer:
4565 return T->isMemberPointerType();
4566
4567 // Type trait expressions which correspond to the type property predicates
4568 // in C++0x [meta.unary.prop].
4569 case UTT_IsConst:
4570 return T.isConstQualified();
4571 case UTT_IsVolatile:
4572 return T.isVolatileQualified();
4573 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004574 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004575 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004576 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004577 case UTT_IsStandardLayout:
4578 return T->isStandardLayoutType();
4579 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004580 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004581 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004582 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004583 case UTT_IsEmpty:
4584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4585 return !RD->isUnion() && RD->isEmpty();
4586 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004587 case UTT_IsPolymorphic:
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->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004590 return false;
4591 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004592 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004593 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004594 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004595 case UTT_IsAggregate:
4596 // Report vector extensions and complex types as aggregates because they
4597 // support aggregate initialization. GCC mirrors this behavior for vectors
4598 // but not _Complex.
4599 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4600 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004601 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4602 // even then only when it is used with the 'interface struct ...' syntax
4603 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004604 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004605 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004606 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004607 case UTT_IsSealed:
4608 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004609 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004610 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004611 case UTT_IsSigned:
4612 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004613 case UTT_IsUnsigned:
4614 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004615
4616 // Type trait expressions which query classes regarding their construction,
4617 // destruction, and copying. Rather than being based directly on the
4618 // related type predicates in the standard, they are specified by both
4619 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4620 // specifications.
4621 //
4622 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4623 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004624 //
4625 // Note that these builtins do not behave as documented in g++: if a class
4626 // has both a trivial and a non-trivial special member of a particular kind,
4627 // they return false! For now, we emulate this behavior.
4628 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4629 // does not correctly compute triviality in the presence of multiple special
4630 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004631 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004632 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4633 // If __is_pod (type) is true then the trait is true, else if type is
4634 // a cv class or union type (or array thereof) with a trivial default
4635 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004636 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004637 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004638 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4639 return RD->hasTrivialDefaultConstructor() &&
4640 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004641 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004642 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004643 // This trait is implemented by MSVC 2012 and needed to parse the
4644 // standard library headers. Specifically this is used as the logic
4645 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004646 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004647 return true;
4648 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4649 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4650 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004651 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004652 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4653 // If __is_pod (type) is true or type is a reference type then
4654 // the trait is true, else if type is a cv class or union type
4655 // with a trivial copy constructor ([class.copy]) then the trait
4656 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004657 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004658 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004659 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4660 return RD->hasTrivialCopyConstructor() &&
4661 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004662 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004663 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004664 // This trait is implemented by MSVC 2012 and needed to parse the
4665 // standard library headers. Specifically it is used as the logic
4666 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004667 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004668 return true;
4669 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4670 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4671 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004672 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004673 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4674 // If type is const qualified or is a reference type then the
4675 // trait is false. Otherwise if __is_pod (type) is true then the
4676 // trait is true, else if type is a cv class or union type with
4677 // a trivial copy assignment ([class.copy]) then the trait is
4678 // true, else it is false.
4679 // Note: the const and reference restrictions are interesting,
4680 // given that const and reference members don't prevent a class
4681 // from having a trivial copy assignment operator (but do cause
4682 // errors if the copy assignment operator is actually used, q.v.
4683 // [class.copy]p12).
4684
Richard Smith92f241f2012-12-08 02:53:02 +00004685 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004686 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004687 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004688 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004689 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4690 return RD->hasTrivialCopyAssignment() &&
4691 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004692 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004693 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004694 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004695 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004696 // C++14 [meta.unary.prop]:
4697 // For reference types, is_destructible<T>::value is true.
4698 if (T->isReferenceType())
4699 return true;
4700
4701 // Objective-C++ ARC: autorelease types don't require destruction.
4702 if (T->isObjCLifetimeType() &&
4703 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4704 return true;
4705
4706 // C++14 [meta.unary.prop]:
4707 // For incomplete types and function types, is_destructible<T>::value is
4708 // false.
4709 if (T->isIncompleteType() || T->isFunctionType())
4710 return false;
4711
Richard Smithf03e9082017-06-01 00:28:16 +00004712 // A type that requires destruction (via a non-trivial destructor or ARC
4713 // lifetime semantics) is not trivially-destructible.
4714 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4715 return false;
4716
David Majnemerac73de92015-08-11 03:03:28 +00004717 // C++14 [meta.unary.prop]:
4718 // For object types and given U equal to remove_all_extents_t<T>, if the
4719 // expression std::declval<U&>().~U() is well-formed when treated as an
4720 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4721 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4722 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4723 if (!Destructor)
4724 return false;
4725 // C++14 [dcl.fct.def.delete]p2:
4726 // A program that refers to a deleted function implicitly or
4727 // explicitly, other than to declare it, is ill-formed.
4728 if (Destructor->isDeleted())
4729 return false;
4730 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4731 return false;
4732 if (UTT == UTT_IsNothrowDestructible) {
4733 const FunctionProtoType *CPT =
4734 Destructor->getType()->getAs<FunctionProtoType>();
4735 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004736 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004737 return false;
4738 }
4739 }
4740 return true;
4741
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004742 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004743 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004744 // If __is_pod (type) is true or type is a reference type
4745 // then the trait is true, else if type is a cv class or union
4746 // type (or array thereof) with a trivial destructor
4747 // ([class.dtor]) then the trait is true, else it is
4748 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004749 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004750 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004751
John McCall31168b02011-06-15 23:02:42 +00004752 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004753 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004754 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4755 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004756
Richard Smith92f241f2012-12-08 02:53:02 +00004757 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4758 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004759 return false;
4760 // TODO: Propagate nothrowness for implicitly declared special members.
4761 case UTT_HasNothrowAssign:
4762 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4763 // If type is const qualified or is a reference type then the
4764 // trait is false. Otherwise if __has_trivial_assign (type)
4765 // is true then the trait is true, else if type is a cv class
4766 // or union type with copy assignment operators that are known
4767 // not to throw an exception then the trait is true, else it is
4768 // false.
4769 if (C.getBaseElementType(T).isConstQualified())
4770 return false;
4771 if (T->isReferenceType())
4772 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004773 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004774 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004775
Joao Matosc9523d42013-03-27 01:34:16 +00004776 if (const RecordType *RT = T->getAs<RecordType>())
4777 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4778 &CXXRecordDecl::hasTrivialCopyAssignment,
4779 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4780 &CXXMethodDecl::isCopyAssignmentOperator);
4781 return false;
4782 case UTT_HasNothrowMoveAssign:
4783 // This trait is implemented by MSVC 2012 and needed to parse the
4784 // standard library headers. Specifically this is used as the logic
4785 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004786 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004787 return true;
4788
4789 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4790 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4791 &CXXRecordDecl::hasTrivialMoveAssignment,
4792 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4793 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004794 return false;
4795 case UTT_HasNothrowCopy:
4796 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4797 // If __has_trivial_copy (type) is true then the trait is true, else
4798 // if type is a cv class or union type with copy constructors that are
4799 // known not to throw an exception then the trait is true, else it is
4800 // false.
John McCall31168b02011-06-15 23:02:42 +00004801 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004802 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004803 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4804 if (RD->hasTrivialCopyConstructor() &&
4805 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004806 return true;
4807
4808 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004809 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004810 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004811 // A template constructor is never a copy constructor.
4812 // FIXME: However, it may actually be selected at the actual overload
4813 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004814 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004815 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004816 // UsingDecl itself is not a constructor
4817 if (isa<UsingDecl>(ND))
4818 continue;
4819 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004820 if (Constructor->isCopyConstructor(FoundTQs)) {
4821 FoundConstructor = true;
4822 const FunctionProtoType *CPT
4823 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004824 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4825 if (!CPT)
4826 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004827 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004828 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004829 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004830 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004831 }
4832 }
4833
Richard Smith938f40b2011-06-11 17:19:42 +00004834 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004835 }
4836 return false;
4837 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004838 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004839 // If __has_trivial_constructor (type) is true then the trait is
4840 // true, else if type is a cv class or union type (or array
4841 // thereof) with a default constructor that is known not to
4842 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004843 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004844 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004845 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4846 if (RD->hasTrivialDefaultConstructor() &&
4847 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004848 return true;
4849
Alp Tokerb4bca412014-01-20 00:23:47 +00004850 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004851 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004852 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004853 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004854 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004855 // UsingDecl itself is not a constructor
4856 if (isa<UsingDecl>(ND))
4857 continue;
4858 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004859 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004860 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004861 const FunctionProtoType *CPT
4862 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004863 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4864 if (!CPT)
4865 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004866 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004867 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004868 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004869 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004870 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004871 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004872 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004873 }
4874 return false;
4875 case UTT_HasVirtualDestructor:
4876 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4877 // If type is a class type with a virtual destructor ([class.dtor])
4878 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004879 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004880 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004881 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004882 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004883
4884 // These type trait expressions are modeled on the specifications for the
4885 // Embarcadero C++0x type trait functions:
4886 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4887 case UTT_IsCompleteType:
4888 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4889 // Returns True if and only if T is a complete type at the point of the
4890 // function call.
4891 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004892 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004893 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004894 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004895}
Sebastian Redl5822f082009-02-07 20:10:22 +00004896
Alp Tokercbb90342013-12-13 20:49:58 +00004897static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4898 QualType RhsT, SourceLocation KeyLoc);
4899
Douglas Gregor29c42f22012-02-24 07:38:34 +00004900static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4901 ArrayRef<TypeSourceInfo *> Args,
4902 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004903 if (Kind <= UTT_Last)
4904 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4905
Eric Fiselier1af6c112018-01-12 00:09:37 +00004906 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4907 // traits to avoid duplication.
4908 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004909 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4910 Args[1]->getType(), RParenLoc);
4911
Douglas Gregor29c42f22012-02-24 07:38:34 +00004912 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004913 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004914 case clang::TT_IsConstructible:
4915 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004916 case clang::TT_IsTriviallyConstructible: {
4917 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004918 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004919 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004920 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004921 // definition for is_constructible, as defined below, is known to call
4922 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004923 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004924 // The predicate condition for a template specialization
4925 // is_constructible<T, Args...> shall be satisfied if and only if the
4926 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004927 // variable t:
4928 //
4929 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004930 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004931
4932 // Precondition: T and all types in the parameter pack Args shall be
4933 // complete types, (possibly cv-qualified) void, or arrays of
4934 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004935 for (const auto *TSI : Args) {
4936 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004937 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004938 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004939
Simon Pilgrim75c26882016-09-30 14:25:09 +00004940 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004941 diag::err_incomplete_type_used_in_type_trait_expr))
4942 return false;
4943 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004944
David Majnemer9658ecc2015-11-13 05:32:43 +00004945 // Make sure the first argument is not incomplete nor a function type.
4946 QualType T = Args[0]->getType();
4947 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004948 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004949
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004950 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004951 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004952 if (RD && RD->isAbstract())
4953 return false;
4954
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004955 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4956 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004957 ArgExprs.reserve(Args.size() - 1);
4958 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004959 QualType ArgTy = Args[I]->getType();
4960 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4961 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004962 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004963 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004964 ArgTy.getNonLValueExprType(S.Context),
4965 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004966 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004967 for (Expr &E : OpaqueArgExprs)
4968 ArgExprs.push_back(&E);
4969
Simon Pilgrim75c26882016-09-30 14:25:09 +00004970 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004971 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004972 EnterExpressionEvaluationContext Unevaluated(
4973 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004974 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4975 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4976 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4977 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4978 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004979 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004980 if (Init.Failed())
4981 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004982
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004983 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004984 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4985 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004986
Alp Toker73287bf2014-01-20 00:24:09 +00004987 if (Kind == clang::TT_IsConstructible)
4988 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004989
Eric Fiselier1af6c112018-01-12 00:09:37 +00004990 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4991 if (!T->isReferenceType())
4992 return false;
4993
4994 return !Init.isDirectReferenceBinding();
4995 }
4996
Alp Toker73287bf2014-01-20 00:24:09 +00004997 if (Kind == clang::TT_IsNothrowConstructible)
4998 return S.canThrow(Result.get()) == CT_Cannot;
4999
5000 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005001 // Under Objective-C ARC and Weak, if the destination has non-trivial
5002 // Objective-C lifetime, this is a non-trivial construction.
5003 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005004 return false;
5005
5006 // The initialization succeeded; now make sure there are no non-trivial
5007 // calls.
5008 return !Result.get()->hasNonTrivialCall(S.Context);
5009 }
5010
5011 llvm_unreachable("unhandled type trait");
5012 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005013 }
Alp Tokercbb90342013-12-13 20:49:58 +00005014 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005015 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005016
Douglas Gregor29c42f22012-02-24 07:38:34 +00005017 return false;
5018}
5019
Simon Pilgrim75c26882016-09-30 14:25:09 +00005020ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5021 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005022 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005023 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005024
Alp Toker95e7ff22014-01-01 05:57:51 +00005025 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5026 *this, Kind, KWLoc, Args[0]->getType()))
5027 return ExprError();
5028
Douglas Gregor29c42f22012-02-24 07:38:34 +00005029 bool Dependent = false;
5030 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5031 if (Args[I]->getType()->isDependentType()) {
5032 Dependent = true;
5033 break;
5034 }
5035 }
Alp Tokercbb90342013-12-13 20:49:58 +00005036
5037 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005038 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005039 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5040
5041 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5042 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005043}
5044
Alp Toker88f64e62013-12-13 21:19:30 +00005045ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5046 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005047 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005048 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005049 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005050
Douglas Gregor29c42f22012-02-24 07:38:34 +00005051 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5052 TypeSourceInfo *TInfo;
5053 QualType T = GetTypeFromParser(Args[I], &TInfo);
5054 if (!TInfo)
5055 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005056
5057 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005058 }
Alp Tokercbb90342013-12-13 20:49:58 +00005059
Douglas Gregor29c42f22012-02-24 07:38:34 +00005060 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5061}
5062
Alp Tokercbb90342013-12-13 20:49:58 +00005063static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5064 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005065 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5066 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005067
5068 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005069 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005070 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005071 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005072 // Base and Derived are not unions and name the same class type without
5073 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005074
John McCall388ef532011-01-28 22:02:36 +00005075 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005076 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005077 if (!rhsRecord || !lhsRecord) {
5078 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5079 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5080 if (!LHSObjTy || !RHSObjTy)
5081 return false;
5082
5083 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5084 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5085 if (!BaseInterface || !DerivedInterface)
5086 return false;
5087
5088 if (Self.RequireCompleteType(
5089 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5090 return false;
5091
5092 return BaseInterface->isSuperClassOf(DerivedInterface);
5093 }
John McCall388ef532011-01-28 22:02:36 +00005094
5095 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5096 == (lhsRecord == rhsRecord));
5097
5098 if (lhsRecord == rhsRecord)
5099 return !lhsRecord->getDecl()->isUnion();
5100
5101 // C++0x [meta.rel]p2:
5102 // If Base and Derived are class types and are different types
5103 // (ignoring possible cv-qualifiers) then Derived shall be a
5104 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005105 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005106 diag::err_incomplete_type_used_in_type_trait_expr))
5107 return false;
5108
5109 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5110 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5111 }
John Wiegley65497cc2011-04-27 23:09:49 +00005112 case BTT_IsSame:
5113 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005114 case BTT_TypeCompatible: {
5115 // GCC ignores cv-qualifiers on arrays for this builtin.
5116 Qualifiers LhsQuals, RhsQuals;
5117 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5118 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5119 return Self.Context.typesAreCompatible(Lhs, Rhs);
5120 }
John Wiegley65497cc2011-04-27 23:09:49 +00005121 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005122 case BTT_IsConvertibleTo: {
5123 // C++0x [meta.rel]p4:
5124 // Given the following function prototype:
5125 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005126 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005127 // typename add_rvalue_reference<T>::type create();
5128 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005129 // the predicate condition for a template specialization
5130 // is_convertible<From, To> shall be satisfied if and only if
5131 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005132 // well-formed, including any implicit conversions to the return
5133 // type of the function:
5134 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005135 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005136 // return create<From>();
5137 // }
5138 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005139 // Access checking is performed as if in a context unrelated to To and
5140 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005141 // of the return-statement (including conversions to the return type)
5142 // is considered.
5143 //
5144 // We model the initialization as a copy-initialization of a temporary
5145 // of the appropriate type, which for this expression is identical to the
5146 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005147
5148 // Functions aren't allowed to return function or array types.
5149 if (RhsT->isFunctionType() || RhsT->isArrayType())
5150 return false;
5151
5152 // A return statement in a void function must have void type.
5153 if (RhsT->isVoidType())
5154 return LhsT->isVoidType();
5155
5156 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005157 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005158 return false;
5159
5160 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005161 if (LhsT->isObjectType() || LhsT->isFunctionType())
5162 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005163
5164 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005165 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005166 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005167 Expr::getValueKindForType(LhsT));
5168 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005169 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005170 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005171
5172 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005173 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005174 EnterExpressionEvaluationContext Unevaluated(
5175 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005176 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5177 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005178 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005179 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005180 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005181
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005182 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005183 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5184 }
Alp Toker73287bf2014-01-20 00:24:09 +00005185
David Majnemerb3d96882016-05-23 17:21:55 +00005186 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005187 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005188 case BTT_IsTriviallyAssignable: {
5189 // C++11 [meta.unary.prop]p3:
5190 // is_trivially_assignable is defined as:
5191 // is_assignable<T, U>::value is true and the assignment, as defined by
5192 // is_assignable, is known to call no operation that is not trivial
5193 //
5194 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005195 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005196 // treated as an unevaluated operand (Clause 5).
5197 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005198 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005199 // void, or arrays of unknown bound.
5200 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005201 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005202 diag::err_incomplete_type_used_in_type_trait_expr))
5203 return false;
5204 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005205 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005206 diag::err_incomplete_type_used_in_type_trait_expr))
5207 return false;
5208
5209 // cv void is never assignable.
5210 if (LhsT->isVoidType() || RhsT->isVoidType())
5211 return false;
5212
Simon Pilgrim75c26882016-09-30 14:25:09 +00005213 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005214 // declval<U>().
5215 if (LhsT->isObjectType() || LhsT->isFunctionType())
5216 LhsT = Self.Context.getRValueReferenceType(LhsT);
5217 if (RhsT->isObjectType() || RhsT->isFunctionType())
5218 RhsT = Self.Context.getRValueReferenceType(RhsT);
5219 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5220 Expr::getValueKindForType(LhsT));
5221 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5222 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005223
5224 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005225 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005226 EnterExpressionEvaluationContext Unevaluated(
5227 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005228 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005229 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005230 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5231 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005232 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5233 return false;
5234
David Majnemerb3d96882016-05-23 17:21:55 +00005235 if (BTT == BTT_IsAssignable)
5236 return true;
5237
Alp Toker73287bf2014-01-20 00:24:09 +00005238 if (BTT == BTT_IsNothrowAssignable)
5239 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005240
Alp Toker73287bf2014-01-20 00:24:09 +00005241 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005242 // Under Objective-C ARC and Weak, if the destination has non-trivial
5243 // Objective-C lifetime, this is a non-trivial assignment.
5244 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005245 return false;
5246
5247 return !Result.get()->hasNonTrivialCall(Self.Context);
5248 }
5249
5250 llvm_unreachable("unhandled type trait");
5251 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005252 }
Alp Tokercbb90342013-12-13 20:49:58 +00005253 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005254 }
5255 llvm_unreachable("Unknown type trait or not implemented");
5256}
5257
John Wiegley6242b6a2011-04-28 00:16:57 +00005258ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5259 SourceLocation KWLoc,
5260 ParsedType Ty,
5261 Expr* DimExpr,
5262 SourceLocation RParen) {
5263 TypeSourceInfo *TSInfo;
5264 QualType T = GetTypeFromParser(Ty, &TSInfo);
5265 if (!TSInfo)
5266 TSInfo = Context.getTrivialTypeSourceInfo(T);
5267
5268 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5269}
5270
5271static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5272 QualType T, Expr *DimExpr,
5273 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005274 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005275
5276 switch(ATT) {
5277 case ATT_ArrayRank:
5278 if (T->isArrayType()) {
5279 unsigned Dim = 0;
5280 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5281 ++Dim;
5282 T = AT->getElementType();
5283 }
5284 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005285 }
John Wiegleyd3522222011-04-28 02:06:46 +00005286 return 0;
5287
John Wiegley6242b6a2011-04-28 00:16:57 +00005288 case ATT_ArrayExtent: {
5289 llvm::APSInt Value;
5290 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005291 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005292 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005293 false).isInvalid())
5294 return 0;
5295 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005296 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5297 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005298 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005299 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005300 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005301
5302 if (T->isArrayType()) {
5303 unsigned D = 0;
5304 bool Matched = false;
5305 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5306 if (Dim == D) {
5307 Matched = true;
5308 break;
5309 }
5310 ++D;
5311 T = AT->getElementType();
5312 }
5313
John Wiegleyd3522222011-04-28 02:06:46 +00005314 if (Matched && T->isArrayType()) {
5315 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5316 return CAT->getSize().getLimitedValue();
5317 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005318 }
John Wiegleyd3522222011-04-28 02:06:46 +00005319 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005320 }
5321 }
5322 llvm_unreachable("Unknown type trait or not implemented");
5323}
5324
5325ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5326 SourceLocation KWLoc,
5327 TypeSourceInfo *TSInfo,
5328 Expr* DimExpr,
5329 SourceLocation RParen) {
5330 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005331
Chandler Carruthc5276e52011-05-01 08:48:21 +00005332 // FIXME: This should likely be tracked as an APInt to remove any host
5333 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005334 uint64_t Value = 0;
5335 if (!T->isDependentType())
5336 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5337
Chandler Carruthc5276e52011-05-01 08:48:21 +00005338 // While the specification for these traits from the Embarcadero C++
5339 // compiler's documentation says the return type is 'unsigned int', Clang
5340 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5341 // compiler, there is no difference. On several other platforms this is an
5342 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005343 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5344 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005345}
5346
John Wiegleyf9f65842011-04-25 06:54:41 +00005347ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005348 SourceLocation KWLoc,
5349 Expr *Queried,
5350 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005351 // If error parsing the expression, ignore.
5352 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005353 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005354
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005355 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005356
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005357 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005358}
5359
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005360static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5361 switch (ET) {
5362 case ET_IsLValueExpr: return E->isLValue();
5363 case ET_IsRValueExpr: return E->isRValue();
5364 }
5365 llvm_unreachable("Expression trait not covered by switch");
5366}
5367
John Wiegleyf9f65842011-04-25 06:54:41 +00005368ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005369 SourceLocation KWLoc,
5370 Expr *Queried,
5371 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005372 if (Queried->isTypeDependent()) {
5373 // Delay type-checking for type-dependent expressions.
5374 } else if (Queried->getType()->isPlaceholderType()) {
5375 ExprResult PE = CheckPlaceholderExpr(Queried);
5376 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005377 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005378 }
5379
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005380 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005381
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005382 return new (Context)
5383 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005384}
5385
Richard Trieu82402a02011-09-15 21:56:47 +00005386QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005387 ExprValueKind &VK,
5388 SourceLocation Loc,
5389 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005390 assert(!LHS.get()->getType()->isPlaceholderType() &&
5391 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005392 "placeholders should have been weeded out by now");
5393
Richard Smith4baaa5a2016-12-03 01:14:32 +00005394 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5395 // temporary materialization conversion otherwise.
5396 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005397 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005398 else if (LHS.get()->isRValue())
5399 LHS = TemporaryMaterializationConversion(LHS.get());
5400 if (LHS.isInvalid())
5401 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005402
5403 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005404 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005405 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005406
Sebastian Redl5822f082009-02-07 20:10:22 +00005407 const char *OpSpelling = isIndirect ? "->*" : ".*";
5408 // C++ 5.5p2
5409 // The binary operator .* [p3: ->*] binds its second operand, which shall
5410 // be of type "pointer to member of T" (where T is a completely-defined
5411 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005412 QualType RHSType = RHS.get()->getType();
5413 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005414 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005415 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005416 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005417 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005418 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005419
Sebastian Redl5822f082009-02-07 20:10:22 +00005420 QualType Class(MemPtr->getClass(), 0);
5421
Douglas Gregord07ba342010-10-13 20:41:14 +00005422 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5423 // member pointer points must be completely-defined. However, there is no
5424 // reason for this semantic distinction, and the rule is not enforced by
5425 // other compilers. Therefore, we do not check this property, as it is
5426 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005427
Sebastian Redl5822f082009-02-07 20:10:22 +00005428 // C++ 5.5p2
5429 // [...] to its first operand, which shall be of class T or of a class of
5430 // which T is an unambiguous and accessible base class. [p3: a pointer to
5431 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005432 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005433 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005434 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5435 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005436 else {
5437 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005438 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005439 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005440 return QualType();
5441 }
5442 }
5443
Richard Trieu82402a02011-09-15 21:56:47 +00005444 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005445 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005446 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5447 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005448 return QualType();
5449 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005450
Richard Smith0f59cb32015-12-18 21:45:41 +00005451 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005452 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005453 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005454 return QualType();
5455 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005456
5457 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005458 if (CheckDerivedToBaseConversion(
5459 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005460 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005461 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005462 return QualType();
5463
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005464 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005465 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5466 if (isIndirect)
5467 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005468 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005469 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005470 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005471 }
5472
Richard Trieu82402a02011-09-15 21:56:47 +00005473 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005474 // Diagnose use of pointer-to-member type which when used as
5475 // the functional cast in a pointer-to-member expression.
5476 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5477 return QualType();
5478 }
John McCall7decc9e2010-11-18 06:31:45 +00005479
Sebastian Redl5822f082009-02-07 20:10:22 +00005480 // C++ 5.5p2
5481 // The result is an object or a function of the type specified by the
5482 // second operand.
5483 // The cv qualifiers are the union of those in the pointer and the left side,
5484 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005485 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005486 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005487
Douglas Gregor1d042092011-01-26 16:40:18 +00005488 // C++0x [expr.mptr.oper]p6:
5489 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005490 // ill-formed if the second operand is a pointer to member function with
5491 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5492 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005493 // is a pointer to member function with ref-qualifier &&.
5494 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5495 switch (Proto->getRefQualifier()) {
5496 case RQ_None:
5497 // Do nothing
5498 break;
5499
5500 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005501 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005502 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5503 // is (exactly) 'const'.
5504 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005505 Diag(Loc, getLangOpts().CPlusPlus2a
5506 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5507 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5508 else
5509 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5510 << RHSType << 1 << LHS.get()->getSourceRange();
5511 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005512 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
Douglas Gregor1d042092011-01-26 16:40:18 +00005514 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005515 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005516 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005517 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005518 break;
5519 }
5520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521
John McCall7decc9e2010-11-18 06:31:45 +00005522 // C++ [expr.mptr.oper]p6:
5523 // The result of a .* expression whose second operand is a pointer
5524 // to a data member is of the same value category as its
5525 // first operand. The result of a .* expression whose second
5526 // operand is a pointer to a member function is a prvalue. The
5527 // result of an ->* expression is an lvalue if its second operand
5528 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005529 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005530 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005531 return Context.BoundMemberTy;
5532 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005533 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005534 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005535 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005536 }
John McCall7decc9e2010-11-18 06:31:45 +00005537
Sebastian Redl5822f082009-02-07 20:10:22 +00005538 return Result;
5539}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005541/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005542///
5543/// This is part of the parameter validation for the ? operator. If either
5544/// value operand is a class type, the two operands are attempted to be
5545/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005546/// It returns true if the program is ill-formed and has already been diagnosed
5547/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005548static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5549 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005550 bool &HaveConversion,
5551 QualType &ToType) {
5552 HaveConversion = false;
5553 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005554
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005555 InitializationKind Kind =
5556 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005557 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005558 // The process for determining whether an operand expression E1 of type T1
5559 // can be converted to match an operand expression E2 of type T2 is defined
5560 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005561 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5562 // implicitly converted to type "lvalue reference to T2", subject to the
5563 // constraint that in the conversion the reference must bind directly to
5564 // an lvalue.
5565 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005566 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005567 // the constraint that the reference must bind directly.
5568 if (To->isLValue() || To->isXValue()) {
5569 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5570 : Self.Context.getRValueReferenceType(ToType);
5571
Douglas Gregor838fcc32010-03-26 20:14:36 +00005572 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005574 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005575 if (InitSeq.isDirectReferenceBinding()) {
5576 ToType = T;
5577 HaveConversion = true;
5578 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
Douglas Gregor838fcc32010-03-26 20:14:36 +00005581 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005582 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005583 }
John McCall65eb8792010-02-25 01:37:24 +00005584
Sebastian Redl1a99f442009-04-16 17:51:27 +00005585 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5586 // -- if E1 and E2 have class type, and the underlying class types are
5587 // the same or one is a base class of the other:
5588 QualType FTy = From->getType();
5589 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005590 const RecordType *FRec = FTy->getAs<RecordType>();
5591 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005593 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5594 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5595 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005596 // E1 can be converted to match E2 if the class of T2 is the
5597 // same type as, or a base class of, the class of T1, and
5598 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005599 if (FRec == TRec || FDerivedFromT) {
5600 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005601 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005602 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005603 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005604 HaveConversion = true;
5605 return false;
5606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607
Douglas Gregor838fcc32010-03-26 20:14:36 +00005608 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005609 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregor838fcc32010-03-26 20:14:36 +00005613 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615
Douglas Gregor838fcc32010-03-26 20:14:36 +00005616 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5617 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005619 // an rvalue).
5620 //
5621 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5622 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005623 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005624
Douglas Gregor838fcc32010-03-26 20:14:36 +00005625 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005626 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005627 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005628 ToType = TTy;
5629 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005630 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005631
Sebastian Redl1a99f442009-04-16 17:51:27 +00005632 return false;
5633}
5634
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005635/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005636///
5637/// This is part of the parameter validation for the ? operator. If either
5638/// value operand is a class type, overload resolution is used to find a
5639/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005640static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005641 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005642 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005643 OverloadCandidateSet CandidateSet(QuestionLoc,
5644 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005645 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005646 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005647
5648 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005649 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005650 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005651 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005652 ExprResult LHSRes = Self.PerformImplicitConversion(
5653 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5654 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005655 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005656 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005657 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005658
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005659 ExprResult RHSRes = Self.PerformImplicitConversion(
5660 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5661 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005662 if (RHSRes.isInvalid())
5663 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005664 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005665 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005666 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005667 return false;
John Wiegley01296292011-04-08 18:41:53 +00005668 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005670 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005671
5672 // Emit a better diagnostic if one of the expressions is a null pointer
5673 // constant and the other is a pointer type. In this case, the user most
5674 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005675 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005676 return true;
5677
5678 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005679 << LHS.get()->getType() << RHS.get()->getType()
5680 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005681 return true;
5682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005683 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005684 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005685 << LHS.get()->getType() << RHS.get()->getType()
5686 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005687 // FIXME: Print the possible common types by printing the return types of
5688 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005689 break;
5690
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005691 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005692 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005693 }
5694 return true;
5695}
5696
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005697/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005698/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005699static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005700 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005701 InitializationKind Kind =
5702 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005703 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005704 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005705 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005706 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005707 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005708
John Wiegley01296292011-04-08 18:41:53 +00005709 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005710 return false;
5711}
5712
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005713/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005714///
5715/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5716/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005717QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5718 ExprResult &RHS, ExprValueKind &VK,
5719 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005720 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005721 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5722 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005723
Richard Smith45edb702012-08-07 22:06:48 +00005724 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005725 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005726 //
5727 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5728 // a is that of a integer vector with the same number of elements and
5729 // size as the vectors of b and c. If one of either b or c is a scalar
5730 // it is implicitly converted to match the type of the vector.
5731 // Otherwise the expression is ill-formed. If both b and c are scalars,
5732 // then b and c are checked and converted to the type of a if possible.
5733 // Unlike the OpenCL ?: operator, the expression is evaluated as
5734 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005735 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005736 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005737 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005738 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005739 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005740 }
5741
John McCall7decc9e2010-11-18 06:31:45 +00005742 // Assume r-value.
5743 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005744 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005745
Sebastian Redl1a99f442009-04-16 17:51:27 +00005746 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005747 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005748 return Context.DependentTy;
5749
Richard Smith45edb702012-08-07 22:06:48 +00005750 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005751 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005752 QualType LTy = LHS.get()->getType();
5753 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005754 bool LVoid = LTy->isVoidType();
5755 bool RVoid = RTy->isVoidType();
5756 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005757 // ... one of the following shall hold:
5758 // -- The second or the third operand (but not both) is a (possibly
5759 // parenthesized) throw-expression; the result is of the type
5760 // and value category of the other.
5761 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5762 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5763 if (LThrow != RThrow) {
5764 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5765 VK = NonThrow->getValueKind();
5766 // DR (no number yet): the result is a bit-field if the
5767 // non-throw-expression operand is a bit-field.
5768 OK = NonThrow->getObjectKind();
5769 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005770 }
5771
Sebastian Redl1a99f442009-04-16 17:51:27 +00005772 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005773 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005774 if (LVoid && RVoid)
5775 return Context.VoidTy;
5776
5777 // Neither holds, error.
5778 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5779 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005780 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005781 return QualType();
5782 }
5783
5784 // Neither is void.
5785
Richard Smithf2b084f2012-08-08 06:13:49 +00005786 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005787 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005788 // either has (cv) class type [...] an attempt is made to convert each of
5789 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005791 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005792 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005793 QualType L2RType, R2LType;
5794 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005795 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005796 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005797 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005798 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799
Sebastian Redl1a99f442009-04-16 17:51:27 +00005800 // If both can be converted, [...] the program is ill-formed.
5801 if (HaveL2R && HaveR2L) {
5802 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005803 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005804 return QualType();
5805 }
5806
5807 // If exactly one conversion is possible, that conversion is applied to
5808 // the chosen operand and the converted operands are used in place of the
5809 // original operands for the remainder of this section.
5810 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005811 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005812 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005813 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005814 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005815 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005816 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005817 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005818 }
5819 }
5820
Richard Smithf2b084f2012-08-08 06:13:49 +00005821 // C++11 [expr.cond]p3
5822 // if both are glvalues of the same value category and the same type except
5823 // for cv-qualification, an attempt is made to convert each of those
5824 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005825 // FIXME:
5826 // Resolving a defect in P0012R1: we extend this to cover all cases where
5827 // one of the operands is reference-compatible with the other, in order
5828 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005829 ExprValueKind LVK = LHS.get()->getValueKind();
5830 ExprValueKind RVK = RHS.get()->getValueKind();
5831 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005832 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005833 // DerivedToBase was already handled by the class-specific case above.
5834 // FIXME: Should we allow ObjC conversions here?
5835 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5836 if (CompareReferenceRelationship(
5837 QuestionLoc, LTy, RTy, DerivedToBase,
5838 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005839 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5840 // [...] subject to the constraint that the reference must bind
5841 // directly [...]
5842 !RHS.get()->refersToBitField() &&
5843 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005844 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005845 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005846 } else if (CompareReferenceRelationship(
5847 QuestionLoc, RTy, LTy, DerivedToBase,
5848 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005849 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5850 !LHS.get()->refersToBitField() &&
5851 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005852 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5853 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005854 }
5855 }
5856
5857 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005858 // If the second and third operands are glvalues of the same value
5859 // category and have the same type, the result is of that type and
5860 // value category and it is a bit-field if the second or the third
5861 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005862 // We only extend this to bitfields, not to the crazy other kinds of
5863 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005864 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005865 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005866 LHS.get()->isOrdinaryOrBitFieldObject() &&
5867 RHS.get()->isOrdinaryOrBitFieldObject()) {
5868 VK = LHS.get()->getValueKind();
5869 if (LHS.get()->getObjectKind() == OK_BitField ||
5870 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005871 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005872
5873 // If we have function pointer types, unify them anyway to unify their
5874 // exception specifications, if any.
5875 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5876 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005877 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005878 /*ConvertArgs*/false);
5879 LTy = Context.getQualifiedType(LTy, Qs);
5880
5881 assert(!LTy.isNull() && "failed to find composite pointer type for "
5882 "canonically equivalent function ptr types");
5883 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5884 }
5885
John McCall7decc9e2010-11-18 06:31:45 +00005886 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005887 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005888
Richard Smithf2b084f2012-08-08 06:13:49 +00005889 // C++11 [expr.cond]p5
5890 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005891 // do not have the same type, and either has (cv) class type, ...
5892 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5893 // ... overload resolution is used to determine the conversions (if any)
5894 // to be applied to the operands. If the overload resolution fails, the
5895 // program is ill-formed.
5896 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5897 return QualType();
5898 }
5899
Richard Smithf2b084f2012-08-08 06:13:49 +00005900 // C++11 [expr.cond]p6
5901 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005902 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005903 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5904 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005905 if (LHS.isInvalid() || RHS.isInvalid())
5906 return QualType();
5907 LTy = LHS.get()->getType();
5908 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005909
5910 // After those conversions, one of the following shall hold:
5911 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005912 // is of that type. If the operands have class type, the result
5913 // is a prvalue temporary of the result type, which is
5914 // copy-initialized from either the second operand or the third
5915 // operand depending on the value of the first operand.
5916 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5917 if (LTy->isRecordType()) {
5918 // The operands have class type. Make a temporary copy.
5919 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005920
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005921 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5922 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005923 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005924 if (LHSCopy.isInvalid())
5925 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005926
5927 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5928 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005929 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005930 if (RHSCopy.isInvalid())
5931 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005932
John Wiegley01296292011-04-08 18:41:53 +00005933 LHS = LHSCopy;
5934 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005935 }
5936
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005937 // If we have function pointer types, unify them anyway to unify their
5938 // exception specifications, if any.
5939 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5940 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5941 assert(!LTy.isNull() && "failed to find composite pointer type for "
5942 "canonically equivalent function ptr types");
5943 }
5944
Sebastian Redl1a99f442009-04-16 17:51:27 +00005945 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005946 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005947
Douglas Gregor46188682010-05-18 22:42:18 +00005948 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005949 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005950 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5951 /*AllowBothBool*/true,
5952 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005953
Sebastian Redl1a99f442009-04-16 17:51:27 +00005954 // -- The second and third operands have arithmetic or enumeration type;
5955 // the usual arithmetic conversions are performed to bring them to a
5956 // common type, and the result is of that type.
5957 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005958 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005959 if (LHS.isInvalid() || RHS.isInvalid())
5960 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005961 if (ResTy.isNull()) {
5962 Diag(QuestionLoc,
5963 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5965 return QualType();
5966 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005967
5968 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5969 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5970
5971 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005972 }
5973
5974 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005975 // type and the other is a null pointer constant, or both are null
5976 // pointer constants, at least one of which is non-integral; pointer
5977 // conversions and qualification conversions are performed to bring them
5978 // to their composite pointer type. The result is of the composite
5979 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005980 // -- The second and third operands have pointer to member type, or one has
5981 // pointer to member type and the other is a null pointer constant;
5982 // pointer to member conversions and qualification conversions are
5983 // performed to bring them to a common type, whose cv-qualification
5984 // shall match the cv-qualification of either the second or the third
5985 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005986 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5987 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005988 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005989
Douglas Gregor697a3912010-04-01 22:47:07 +00005990 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005991 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5992 if (!Composite.isNull())
5993 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005994
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005995 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005996 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005997 return QualType();
5998
Sebastian Redl1a99f442009-04-16 17:51:27 +00005999 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006000 << LHS.get()->getType() << RHS.get()->getType()
6001 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006002 return QualType();
6003}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006004
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006005static FunctionProtoType::ExceptionSpecInfo
6006mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6007 FunctionProtoType::ExceptionSpecInfo ESI2,
6008 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6009 ExceptionSpecificationType EST1 = ESI1.Type;
6010 ExceptionSpecificationType EST2 = ESI2.Type;
6011
6012 // If either of them can throw anything, that is the result.
6013 if (EST1 == EST_None) return ESI1;
6014 if (EST2 == EST_None) return ESI2;
6015 if (EST1 == EST_MSAny) return ESI1;
6016 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006017 if (EST1 == EST_NoexceptFalse) return ESI1;
6018 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006019
6020 // If either of them is non-throwing, the result is the other.
6021 if (EST1 == EST_DynamicNone) return ESI2;
6022 if (EST2 == EST_DynamicNone) return ESI1;
6023 if (EST1 == EST_BasicNoexcept) return ESI2;
6024 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006025 if (EST1 == EST_NoexceptTrue) return ESI2;
6026 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006027
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006028 // If we're left with value-dependent computed noexcept expressions, we're
6029 // stuck. Before C++17, we can just drop the exception specification entirely,
6030 // since it's not actually part of the canonical type. And this should never
6031 // happen in C++17, because it would mean we were computing the composite
6032 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006033 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006034 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006035 "computing composite pointer type of dependent types");
6036 return FunctionProtoType::ExceptionSpecInfo();
6037 }
6038
6039 // Switch over the possibilities so that people adding new values know to
6040 // update this function.
6041 switch (EST1) {
6042 case EST_None:
6043 case EST_DynamicNone:
6044 case EST_MSAny:
6045 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006046 case EST_DependentNoexcept:
6047 case EST_NoexceptFalse:
6048 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006049 llvm_unreachable("handled above");
6050
6051 case EST_Dynamic: {
6052 // This is the fun case: both exception specifications are dynamic. Form
6053 // the union of the two lists.
6054 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6055 llvm::SmallPtrSet<QualType, 8> Found;
6056 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6057 for (QualType E : Exceptions)
6058 if (Found.insert(S.Context.getCanonicalType(E)).second)
6059 ExceptionTypeStorage.push_back(E);
6060
6061 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6062 Result.Exceptions = ExceptionTypeStorage;
6063 return Result;
6064 }
6065
6066 case EST_Unevaluated:
6067 case EST_Uninstantiated:
6068 case EST_Unparsed:
6069 llvm_unreachable("shouldn't see unresolved exception specifications here");
6070 }
6071
6072 llvm_unreachable("invalid ExceptionSpecificationType");
6073}
6074
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006075/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006076///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006077/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006078/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006079/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006080/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006081///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006082/// \param Loc The location of the operator requiring these two expressions to
6083/// be converted to the composite pointer type.
6084///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006085/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006086QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006087 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006088 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006089 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006090
6091 // C++1z [expr]p14:
6092 // The composite pointer type of two operands p1 and p2 having types T1
6093 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006094 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006095
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006096 // where at least one is a pointer or pointer to member type or
6097 // std::nullptr_t is:
6098 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6099 T1->isNullPtrType();
6100 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6101 T2->isNullPtrType();
6102 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006103 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006104
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006105 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6106 // This can't actually happen, following the standard, but we also use this
6107 // to implement the end of [expr.conv], which hits this case.
6108 //
6109 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6110 if (T1IsPointerLike &&
6111 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006112 if (ConvertArgs)
6113 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6114 ? CK_NullToMemberPointer
6115 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006116 return T1;
6117 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006118 if (T2IsPointerLike &&
6119 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006120 if (ConvertArgs)
6121 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6122 ? CK_NullToMemberPointer
6123 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006124 return T2;
6125 }
Mike Stump11289f42009-09-09 15:08:12 +00006126
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006127 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006128 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006129 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006130 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6131 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006132
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006133 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6134 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6135 // the union of cv1 and cv2;
6136 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6137 // "pointer to function", where the function types are otherwise the same,
6138 // "pointer to function";
6139 // FIXME: This rule is defective: it should also permit removing noexcept
6140 // from a pointer to member function. As a Clang extension, we also
6141 // permit removing 'noreturn', so we generalize this rule to;
6142 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6143 // "pointer to member function" and the pointee types can be unified
6144 // by a function pointer conversion, that conversion is applied
6145 // before checking the following rules.
6146 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6147 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6148 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6149 // respectively;
6150 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6151 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6152 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6153 // T1 or the cv-combined type of T1 and T2, respectively;
6154 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6155 // T2;
6156 //
6157 // If looked at in the right way, these bullets all do the same thing.
6158 // What we do here is, we build the two possible cv-combined types, and try
6159 // the conversions in both directions. If only one works, or if the two
6160 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006161 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006162 //
6163 // Note that this will fail to find a composite pointer type for "pointer
6164 // to void" and "pointer to function". We can't actually perform the final
6165 // conversion in this case, even though a composite pointer type formally
6166 // exists.
6167 SmallVector<unsigned, 4> QualifierUnion;
6168 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006169 QualType Composite1 = T1;
6170 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006171 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006172 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006173 const PointerType *Ptr1, *Ptr2;
6174 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6175 (Ptr2 = Composite2->getAs<PointerType>())) {
6176 Composite1 = Ptr1->getPointeeType();
6177 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006178
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006179 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006180 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006181 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006182 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006183
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006184 QualifierUnion.push_back(
6185 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006186 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006187 continue;
6188 }
Mike Stump11289f42009-09-09 15:08:12 +00006189
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006190 const MemberPointerType *MemPtr1, *MemPtr2;
6191 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6192 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6193 Composite1 = MemPtr1->getPointeeType();
6194 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006195
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006196 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006197 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006198 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006199 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006201 QualifierUnion.push_back(
6202 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6203 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6204 MemPtr2->getClass()));
6205 continue;
6206 }
Mike Stump11289f42009-09-09 15:08:12 +00006207
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006208 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006209
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006210 // Cannot unwrap any more types.
6211 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006212 }
Mike Stump11289f42009-09-09 15:08:12 +00006213
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006214 // Apply the function pointer conversion to unify the types. We've already
6215 // unwrapped down to the function types, and we want to merge rather than
6216 // just convert, so do this ourselves rather than calling
6217 // IsFunctionConversion.
6218 //
6219 // FIXME: In order to match the standard wording as closely as possible, we
6220 // currently only do this under a single level of pointers. Ideally, we would
6221 // allow this in general, and set NeedConstBefore to the relevant depth on
6222 // the side(s) where we changed anything.
6223 if (QualifierUnion.size() == 1) {
6224 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6225 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6226 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6227 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6228
6229 // The result is noreturn if both operands are.
6230 bool Noreturn =
6231 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6232 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6233 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6234
6235 // The result is nothrow if both operands are.
6236 SmallVector<QualType, 8> ExceptionTypeStorage;
6237 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6238 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6239 ExceptionTypeStorage);
6240
6241 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6242 FPT1->getParamTypes(), EPI1);
6243 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6244 FPT2->getParamTypes(), EPI2);
6245 }
6246 }
6247 }
6248
Richard Smith5e9746f2016-10-21 22:00:42 +00006249 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006250 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006251 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006252 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006253 for (unsigned I = 0; I != NeedConstBefore; ++I)
6254 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006255 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006258 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006259 auto MOC = MemberOfClass.rbegin();
6260 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6261 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6262 auto Classes = *MOC++;
6263 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006264 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006265 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006266 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006267 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006268 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006269 } else {
6270 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006271 Composite1 =
6272 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6273 Composite2 =
6274 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006275 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006276 }
6277
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006278 struct Conversion {
6279 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006280 Expr *&E1, *&E2;
6281 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006282 InitializedEntity Entity;
6283 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006284 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006285 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006286
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006287 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6288 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006289 : S(S), E1(E1), E2(E2), Composite(Composite),
6290 Entity(InitializedEntity::InitializeTemporary(Composite)),
6291 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6292 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6293 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006294
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006295 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006296 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6297 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006298 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006299 E1 = E1Result.getAs<Expr>();
6300
6301 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6302 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006303 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006304 E2 = E2Result.getAs<Expr>();
6305
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006306 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006307 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006308 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006309
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006310 // Try to convert to each composite pointer type.
6311 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006312 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6313 if (ConvertArgs && C1.perform())
6314 return QualType();
6315 return C1.Composite;
6316 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006317 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006318
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006319 if (C1.Viable == C2.Viable) {
6320 // Either Composite1 and Composite2 are viable and are different, or
6321 // neither is viable.
6322 // FIXME: How both be viable and different?
6323 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006324 }
6325
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006326 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006327 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6328 return QualType();
6329
6330 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006331}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006332
John McCalldadc5752010-08-24 06:29:42 +00006333ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006334 if (!E)
6335 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006336
John McCall31168b02011-06-15 23:02:42 +00006337 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6338
6339 // If the result is a glvalue, we shouldn't bind it.
6340 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006341 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006342
John McCall31168b02011-06-15 23:02:42 +00006343 // In ARC, calls that return a retainable type can return retained,
6344 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006345 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006346 E->getType()->isObjCRetainableType()) {
6347
6348 bool ReturnsRetained;
6349
6350 // For actual calls, we compute this by examining the type of the
6351 // called value.
6352 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6353 Expr *Callee = Call->getCallee()->IgnoreParens();
6354 QualType T = Callee->getType();
6355
6356 if (T == Context.BoundMemberTy) {
6357 // Handle pointer-to-members.
6358 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6359 T = BinOp->getRHS()->getType();
6360 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6361 T = Mem->getMemberDecl()->getType();
6362 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006363
John McCall31168b02011-06-15 23:02:42 +00006364 if (const PointerType *Ptr = T->getAs<PointerType>())
6365 T = Ptr->getPointeeType();
6366 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6367 T = Ptr->getPointeeType();
6368 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6369 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006370
John McCall31168b02011-06-15 23:02:42 +00006371 const FunctionType *FTy = T->getAs<FunctionType>();
6372 assert(FTy && "call to value not of function type?");
6373 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6374
6375 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6376 // type always produce a +1 object.
6377 } else if (isa<StmtExpr>(E)) {
6378 ReturnsRetained = true;
6379
Ted Kremeneke65b0862012-03-06 20:05:56 +00006380 // We hit this case with the lambda conversion-to-block optimization;
6381 // we don't want any extra casts here.
6382 } else if (isa<CastExpr>(E) &&
6383 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006384 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006385
John McCall31168b02011-06-15 23:02:42 +00006386 // For message sends and property references, we try to find an
6387 // actual method. FIXME: we should infer retention by selector in
6388 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006389 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006390 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006391 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6392 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006393 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6394 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006395 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006396 // Don't do reclaims if we're using the zero-element array
6397 // constant.
6398 if (ArrayLit->getNumElements() == 0 &&
6399 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6400 return E;
6401
Ted Kremeneke65b0862012-03-06 20:05:56 +00006402 D = ArrayLit->getArrayWithObjectsMethod();
6403 } else if (ObjCDictionaryLiteral *DictLit
6404 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006405 // Don't do reclaims if we're using the zero-element dictionary
6406 // constant.
6407 if (DictLit->getNumElements() == 0 &&
6408 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6409 return E;
6410
Ted Kremeneke65b0862012-03-06 20:05:56 +00006411 D = DictLit->getDictWithObjectsMethod();
6412 }
John McCall31168b02011-06-15 23:02:42 +00006413
6414 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006415
6416 // Don't do reclaims on performSelector calls; despite their
6417 // return type, the invoked method doesn't necessarily actually
6418 // return an object.
6419 if (!ReturnsRetained &&
6420 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006421 return E;
John McCall31168b02011-06-15 23:02:42 +00006422 }
6423
John McCall16de4d22011-11-14 19:53:16 +00006424 // Don't reclaim an object of Class type.
6425 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006426 return E;
John McCall16de4d22011-11-14 19:53:16 +00006427
Tim Shen4a05bb82016-06-21 20:29:17 +00006428 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006429
John McCall2d637d22011-09-10 06:18:15 +00006430 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6431 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006432 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6433 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006434 }
6435
David Blaikiebbafb8a2012-03-11 07:00:24 +00006436 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006437 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006438
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006439 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6440 // a fast path for the common case that the type is directly a RecordType.
6441 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006442 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006443 while (!RT) {
6444 switch (T->getTypeClass()) {
6445 case Type::Record:
6446 RT = cast<RecordType>(T);
6447 break;
6448 case Type::ConstantArray:
6449 case Type::IncompleteArray:
6450 case Type::VariableArray:
6451 case Type::DependentSizedArray:
6452 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6453 break;
6454 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006455 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006456 }
6457 }
Mike Stump11289f42009-09-09 15:08:12 +00006458
Richard Smithfd555f62012-02-22 02:04:18 +00006459 // That should be enough to guarantee that this type is complete, if we're
6460 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006461 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006462 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006463 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006464
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006465 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6466 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006467 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006468
John McCall31168b02011-06-15 23:02:42 +00006469 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006470 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006471 CheckDestructorAccess(E->getExprLoc(), Destructor,
6472 PDiag(diag::err_access_dtor_temp)
6473 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006474 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6475 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006476
Richard Smithfd555f62012-02-22 02:04:18 +00006477 // If destructor is trivial, we can avoid the extra copy.
6478 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006479 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006480
John McCall28fc7092011-11-10 05:35:25 +00006481 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006482 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006483 }
Richard Smitheec915d62012-02-18 04:13:32 +00006484
6485 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006486 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6487
6488 if (IsDecltype)
6489 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6490
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006491 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006492}
6493
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006494ExprResult
John McCall5d413782010-12-06 08:20:24 +00006495Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006496 if (SubExpr.isInvalid())
6497 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006498
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006499 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006500}
6501
John McCall28fc7092011-11-10 05:35:25 +00006502Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006503 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006504
Eli Friedman3bda6b12012-02-02 23:15:15 +00006505 CleanupVarDeclMarking();
6506
John McCall28fc7092011-11-10 05:35:25 +00006507 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6508 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006509 assert(Cleanup.exprNeedsCleanups() ||
6510 ExprCleanupObjects.size() == FirstCleanup);
6511 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006512 return SubExpr;
6513
Craig Topper5fc8fc22014-08-27 06:28:36 +00006514 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6515 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006516
Tim Shen4a05bb82016-06-21 20:29:17 +00006517 auto *E = ExprWithCleanups::Create(
6518 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006519 DiscardCleanupsInEvaluationContext();
6520
6521 return E;
6522}
6523
John McCall5d413782010-12-06 08:20:24 +00006524Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006525 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006526
Eli Friedman3bda6b12012-02-02 23:15:15 +00006527 CleanupVarDeclMarking();
6528
Tim Shen4a05bb82016-06-21 20:29:17 +00006529 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006530 return SubStmt;
6531
6532 // FIXME: In order to attach the temporaries, wrap the statement into
6533 // a StmtExpr; currently this is only used for asm statements.
6534 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6535 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006536 CompoundStmt *CompStmt = CompoundStmt::Create(
6537 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006538 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6539 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006540 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006541}
6542
Richard Smithfd555f62012-02-22 02:04:18 +00006543/// Process the expression contained within a decltype. For such expressions,
6544/// certain semantic checks on temporaries are delayed until this point, and
6545/// are omitted for the 'topmost' call in the decltype expression. If the
6546/// topmost call bound a temporary, strip that temporary off the expression.
6547ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006548 assert(ExprEvalContexts.back().ExprContext ==
6549 ExpressionEvaluationContextRecord::EK_Decltype &&
6550 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006551
Akira Hatanaka0a848562019-01-10 20:12:16 +00006552 ExprResult Result = CheckPlaceholderExpr(E);
6553 if (Result.isInvalid())
6554 return ExprError();
6555 E = Result.get();
6556
Richard Smithfd555f62012-02-22 02:04:18 +00006557 // C++11 [expr.call]p11:
6558 // If a function call is a prvalue of object type,
6559 // -- if the function call is either
6560 // -- the operand of a decltype-specifier, or
6561 // -- the right operand of a comma operator that is the operand of a
6562 // decltype-specifier,
6563 // a temporary object is not introduced for the prvalue.
6564
6565 // Recursively rebuild ParenExprs and comma expressions to strip out the
6566 // outermost CXXBindTemporaryExpr, if any.
6567 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6568 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6569 if (SubExpr.isInvalid())
6570 return ExprError();
6571 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006572 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006573 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006574 }
6575 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6576 if (BO->getOpcode() == BO_Comma) {
6577 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6578 if (RHS.isInvalid())
6579 return ExprError();
6580 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006581 return E;
6582 return new (Context) BinaryOperator(
6583 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006584 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006585 }
6586 }
6587
6588 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006589 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6590 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006591 if (TopCall)
6592 E = TopCall;
6593 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006594 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006595
6596 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006597 ExprEvalContexts.back().ExprContext =
6598 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006599
Richard Smithf86b0ae2012-07-28 19:54:11 +00006600 // In MS mode, don't perform any extra checking of call return types within a
6601 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006602 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006603 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006604
Richard Smithfd555f62012-02-22 02:04:18 +00006605 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006606 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6607 I != N; ++I) {
6608 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006609 if (Call == TopCall)
6610 continue;
6611
David Majnemerced8bdf2015-02-25 17:36:15 +00006612 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006613 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006614 return ExprError();
6615 }
6616
6617 // Now all relevant types are complete, check the destructors are accessible
6618 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006619 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6620 I != N; ++I) {
6621 CXXBindTemporaryExpr *Bind =
6622 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006623 if (Bind == TopBind)
6624 continue;
6625
6626 CXXTemporary *Temp = Bind->getTemporary();
6627
6628 CXXRecordDecl *RD =
6629 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6630 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6631 Temp->setDestructor(Destructor);
6632
Richard Smith7d847b12012-05-11 22:20:10 +00006633 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6634 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006635 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006636 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006637 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6638 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006639
6640 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006641 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006642 }
6643
6644 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006645 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006646}
6647
Richard Smith79c927b2013-11-06 19:31:51 +00006648/// Note a set of 'operator->' functions that were used for a member access.
6649static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006650 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006651 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6652 // FIXME: Make this configurable?
6653 unsigned Limit = 9;
6654 if (OperatorArrows.size() > Limit) {
6655 // Produce Limit-1 normal notes and one 'skipping' note.
6656 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6657 SkipCount = OperatorArrows.size() - (Limit - 1);
6658 }
6659
6660 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6661 if (I == SkipStart) {
6662 S.Diag(OperatorArrows[I]->getLocation(),
6663 diag::note_operator_arrows_suppressed)
6664 << SkipCount;
6665 I += SkipCount;
6666 } else {
6667 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6668 << OperatorArrows[I]->getCallResultType();
6669 ++I;
6670 }
6671 }
6672}
6673
Nico Weber964d3322015-02-16 22:35:45 +00006674ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6675 SourceLocation OpLoc,
6676 tok::TokenKind OpKind,
6677 ParsedType &ObjectType,
6678 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006679 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006680 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006681 if (Result.isInvalid()) return ExprError();
6682 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006683
John McCall526ab472011-10-25 17:37:35 +00006684 Result = CheckPlaceholderExpr(Base);
6685 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006686 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006687
John McCallb268a282010-08-23 23:25:46 +00006688 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006689 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006690 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006691 // If we have a pointer to a dependent type and are using the -> operator,
6692 // the object type is the type that the pointer points to. We might still
6693 // have enough information about that type to do something useful.
6694 if (OpKind == tok::arrow)
6695 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6696 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697
John McCallba7bf592010-08-24 05:47:05 +00006698 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006699 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006700 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006701 }
Mike Stump11289f42009-09-09 15:08:12 +00006702
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006703 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006704 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006705 // returned, with the original second operand.
6706 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006707 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006708 bool NoArrowOperatorFound = false;
6709 bool FirstIteration = true;
6710 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006711 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006712 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006713 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006714 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006716 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006717 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6718 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006719 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006720 noteOperatorArrows(*this, OperatorArrows);
6721 Diag(OpLoc, diag::note_operator_arrow_depth)
6722 << getLangOpts().ArrowDepth;
6723 return ExprError();
6724 }
6725
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006726 Result = BuildOverloadedArrowExpr(
6727 S, Base, OpLoc,
6728 // When in a template specialization and on the first loop iteration,
6729 // potentially give the default diagnostic (with the fixit in a
6730 // separate note) instead of having the error reported back to here
6731 // and giving a diagnostic with a fixit attached to the error itself.
6732 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006733 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006734 : &NoArrowOperatorFound);
6735 if (Result.isInvalid()) {
6736 if (NoArrowOperatorFound) {
6737 if (FirstIteration) {
6738 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006739 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006740 << FixItHint::CreateReplacement(OpLoc, ".");
6741 OpKind = tok::period;
6742 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006743 }
6744 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6745 << BaseType << Base->getSourceRange();
6746 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006747 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006748 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006749 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006750 }
6751 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006752 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006753 }
John McCallb268a282010-08-23 23:25:46 +00006754 Base = Result.get();
6755 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006756 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006757 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006758 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006759 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006760 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6761 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006762 return ExprError();
6763 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006764 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006765 }
Mike Stump11289f42009-09-09 15:08:12 +00006766
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006767 if (OpKind == tok::arrow &&
6768 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006769 BaseType = BaseType->getPointeeType();
6770 }
Mike Stump11289f42009-09-09 15:08:12 +00006771
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006772 // Objective-C properties allow "." access on Objective-C pointer types,
6773 // so adjust the base type to the object type itself.
6774 if (BaseType->isObjCObjectPointerType())
6775 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006776
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006777 // C++ [basic.lookup.classref]p2:
6778 // [...] If the type of the object expression is of pointer to scalar
6779 // type, the unqualified-id is looked up in the context of the complete
6780 // postfix-expression.
6781 //
6782 // This also indicates that we could be parsing a pseudo-destructor-name.
6783 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006784 // expressions or normal member (ivar or property) access expressions, and
6785 // it's legal for the type to be incomplete if this is a pseudo-destructor
6786 // call. We'll do more incomplete-type checks later in the lookup process,
6787 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006788 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006789 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006790 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006791 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006792 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006793 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006794 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006795 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006796 }
Mike Stump11289f42009-09-09 15:08:12 +00006797
Douglas Gregor3024f072012-04-16 07:05:22 +00006798 // The object type must be complete (or dependent), or
6799 // C++11 [expr.prim.general]p3:
6800 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006801 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006802 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006803 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006804 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006805 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006806 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006808 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006809 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006810 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006811 // type C (or of pointer to a class type C), the unqualified-id is looked
6812 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006813 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006814 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006815}
6816
Simon Pilgrim75c26882016-09-30 14:25:09 +00006817static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006818 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006819 if (Base->hasPlaceholderType()) {
6820 ExprResult result = S.CheckPlaceholderExpr(Base);
6821 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006822 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006823 }
6824 ObjectType = Base->getType();
6825
David Blaikie1d578782011-12-16 16:03:09 +00006826 // C++ [expr.pseudo]p2:
6827 // The left-hand side of the dot operator shall be of scalar type. The
6828 // left-hand side of the arrow operator shall be of pointer to scalar type.
6829 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006830 // Note that this is rather different from the normal handling for the
6831 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006832 if (OpKind == tok::arrow) {
6833 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6834 ObjectType = Ptr->getPointeeType();
6835 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006836 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006837 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6838 << ObjectType << true
6839 << FixItHint::CreateReplacement(OpLoc, ".");
6840 if (S.isSFINAEContext())
6841 return true;
6842
6843 OpKind = tok::period;
6844 }
6845 }
6846
6847 return false;
6848}
6849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006850/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006851/// pointer objects.
6852static bool
6853canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6854 QualType DestructedType) {
6855 // If this is a record type, check if its destructor is callable.
6856 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00006857 if (RD->hasDefinition())
6858 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6859 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006860 return false;
6861 }
6862
6863 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6864 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6865 DestructedType->isVectorType();
6866}
6867
John McCalldadc5752010-08-24 06:29:42 +00006868ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006869 SourceLocation OpLoc,
6870 tok::TokenKind OpKind,
6871 const CXXScopeSpec &SS,
6872 TypeSourceInfo *ScopeTypeInfo,
6873 SourceLocation CCLoc,
6874 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006875 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006876 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877
Eli Friedman0ce4de42012-01-25 04:35:06 +00006878 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006879 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6880 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006881
Douglas Gregorc5c57342012-09-10 14:57:06 +00006882 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6883 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006884 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006885 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006886 else {
Nico Weber58829272012-01-23 05:50:57 +00006887 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6888 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006889 return ExprError();
6890 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006891 }
6892
6893 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006895 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006896 if (DestructedTypeInfo) {
6897 QualType DestructedType = DestructedTypeInfo->getType();
6898 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006899 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006900 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6901 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006902 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6903 // Foo *foo;
6904 // foo.~Foo();
6905 if (OpKind == tok::period && ObjectType->isPointerType() &&
6906 Context.hasSameUnqualifiedType(DestructedType,
6907 ObjectType->getPointeeType())) {
6908 auto Diagnostic =
6909 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6910 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006912 // Issue a fixit only when the destructor is valid.
6913 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6914 *this, DestructedType))
6915 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6916
6917 // Recover by setting the object type to the destructed type and the
6918 // operator to '->'.
6919 ObjectType = DestructedType;
6920 OpKind = tok::arrow;
6921 } else {
6922 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6923 << ObjectType << DestructedType << Base->getSourceRange()
6924 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6925
6926 // Recover by setting the destructed type to the object type.
6927 DestructedType = ObjectType;
6928 DestructedTypeInfo =
6929 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6930 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6931 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006932 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006933 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006934
John McCall31168b02011-06-15 23:02:42 +00006935 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6936 // Okay: just pretend that the user provided the correctly-qualified
6937 // type.
6938 } else {
6939 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6940 << ObjectType << DestructedType << Base->getSourceRange()
6941 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6942 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006943
John McCall31168b02011-06-15 23:02:42 +00006944 // Recover by setting the destructed type to the object type.
6945 DestructedType = ObjectType;
6946 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6947 DestructedTypeStart);
6948 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6949 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006950 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006953 // C++ [expr.pseudo]p2:
6954 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6955 // form
6956 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006958 //
6959 // shall designate the same scalar type.
6960 if (ScopeTypeInfo) {
6961 QualType ScopeType = ScopeTypeInfo->getType();
6962 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006963 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006965 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006966 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006967 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006968 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006970 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006971 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006972 }
6973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006974
John McCallb268a282010-08-23 23:25:46 +00006975 Expr *Result
6976 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6977 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006978 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006979 ScopeTypeInfo,
6980 CCLoc,
6981 TildeLoc,
6982 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983
David Majnemerced8bdf2015-02-25 17:36:15 +00006984 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006985}
6986
John McCalldadc5752010-08-24 06:29:42 +00006987ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006988 SourceLocation OpLoc,
6989 tok::TokenKind OpKind,
6990 CXXScopeSpec &SS,
6991 UnqualifiedId &FirstTypeName,
6992 SourceLocation CCLoc,
6993 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006994 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006995 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6996 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006997 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006998 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6999 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007000 "Invalid second type name in pseudo-destructor");
7001
Eli Friedman0ce4de42012-01-25 04:35:06 +00007002 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007003 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7004 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007005
7006 // Compute the object type that we should use for name lookup purposes. Only
7007 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007008 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007009 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007010 if (ObjectType->isRecordType())
7011 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007012 else if (ObjectType->isDependentType())
7013 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007015
7016 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007017 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007018 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007019 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007020 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007021 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007023 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007024 S, &SS, true, false, ObjectTypePtrForLookup,
7025 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007026 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007027 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7028 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007030 // couldn't find anything useful in scope. Just store the identifier and
7031 // it's location, and we'll perform (qualified) name lookup again at
7032 // template instantiation time.
7033 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7034 SecondTypeName.StartLocation);
7035 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007036 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007037 diag::err_pseudo_dtor_destructor_non_type)
7038 << SecondTypeName.Identifier << ObjectType;
7039 if (isSFINAEContext())
7040 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007041
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007042 // Recover by assuming we had the right type all along.
7043 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007044 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007045 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007046 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007047 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007048 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007049 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007050 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007051 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007052 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007053 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007054 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007055 TemplateId->TemplateNameLoc,
7056 TemplateId->LAngleLoc,
7057 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007058 TemplateId->RAngleLoc,
7059 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007060 if (T.isInvalid() || !T.get()) {
7061 // Recover by assuming we had the right type all along.
7062 DestructedType = ObjectType;
7063 } else
7064 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007066
7067 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007068 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007069 if (!DestructedType.isNull()) {
7070 if (!DestructedTypeInfo)
7071 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007072 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007073 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007075
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007076 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007077 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007078 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007079 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007080 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007081 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007083 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007084 S, &SS, true, false, ObjectTypePtrForLookup,
7085 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007086 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007088 diag::err_pseudo_dtor_destructor_non_type)
7089 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007090
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007091 if (isSFINAEContext())
7092 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007094 // Just drop this type. It's unnecessary anyway.
7095 ScopeType = QualType();
7096 } else
7097 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007098 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007099 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007100 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007101 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007102 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007103 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007104 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007105 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007106 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007107 TemplateId->TemplateNameLoc,
7108 TemplateId->LAngleLoc,
7109 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007110 TemplateId->RAngleLoc,
7111 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007112 if (T.isInvalid() || !T.get()) {
7113 // Recover by dropping this type.
7114 ScopeType = QualType();
7115 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007117 }
7118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119
Douglas Gregor90ad9222010-02-24 23:02:30 +00007120 if (!ScopeType.isNull() && !ScopeTypeInfo)
7121 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7122 FirstTypeName.StartLocation);
7123
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124
John McCallb268a282010-08-23 23:25:46 +00007125 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007126 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007127 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007128}
7129
David Blaikie1d578782011-12-16 16:03:09 +00007130ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7131 SourceLocation OpLoc,
7132 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007133 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007134 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007135 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007136 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7137 return ExprError();
7138
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007139 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7140 false);
David Blaikie1d578782011-12-16 16:03:09 +00007141
7142 TypeLocBuilder TLB;
7143 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7144 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7145 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7146 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7147
7148 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007149 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007150 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007151}
7152
John Wiegley01296292011-04-08 18:41:53 +00007153ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007154 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007155 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007156 // Convert the expression to match the conversion function's implicit object
7157 // parameter.
7158 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7159 FoundDecl, Method);
7160 if (Exp.isInvalid())
7161 return true;
7162
Eli Friedman98b01ed2012-03-01 04:01:32 +00007163 if (Method->getParent()->isLambda() &&
7164 Method->getConversionType()->isBlockPointerType()) {
7165 // This is a lambda coversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007166 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007167 Expr *SubE = E;
7168 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7169 if (CE && CE->getCastKind() == CK_NoOp)
7170 SubE = CE->getSubExpr();
7171 SubE = SubE->IgnoreParens();
7172 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7173 SubE = BE->getSubExpr();
7174 if (isa<LambdaExpr>(SubE)) {
7175 // For the conversion to block pointer on a lambda expression, we
7176 // construct a special BlockLiteral instead; this doesn't really make
7177 // a difference in ARC, but outside of ARC the resulting block literal
7178 // follows the normal lifetime rules for block literals instead of being
7179 // autoreleased.
7180 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007181 PushExpressionEvaluationContext(
7182 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007183 ExprResult BlockExp = BuildBlockForLambdaConversion(
7184 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007185 PopExpressionEvaluationContext();
7186
Richard Smith7ed5fb22018-07-27 17:13:18 +00007187 if (BlockExp.isInvalid())
7188 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7189 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007190 }
7191 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007192
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007193 MemberExpr *ME = new (Context) MemberExpr(
7194 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7195 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007196 if (HadMultipleCandidates)
7197 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007198 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007199
Alp Toker314cc812014-01-25 16:55:45 +00007200 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007201 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7202 ResultType = ResultType.getNonLValueExprType(Context);
7203
Bruno Riccic5885cf2018-12-21 15:20:32 +00007204 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7205 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007206
7207 if (CheckFunctionCall(Method, CE,
7208 Method->getType()->castAs<FunctionProtoType>()))
7209 return ExprError();
7210
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007211 return CE;
7212}
7213
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007214ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7215 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007216 // If the operand is an unresolved lookup expression, the expression is ill-
7217 // formed per [over.over]p1, because overloaded function names cannot be used
7218 // without arguments except in explicit contexts.
7219 ExprResult R = CheckPlaceholderExpr(Operand);
7220 if (R.isInvalid())
7221 return R;
7222
7223 // The operand may have been modified when checking the placeholder type.
7224 Operand = R.get();
7225
Richard Smith51ec0cf2017-02-21 01:17:38 +00007226 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007227 // The expression operand for noexcept is in an unevaluated expression
7228 // context, so side effects could result in unintended consequences.
7229 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7230 }
7231
Richard Smithf623c962012-04-17 00:58:00 +00007232 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007233 return new (Context)
7234 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007235}
7236
7237ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7238 Expr *Operand, SourceLocation RParen) {
7239 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007240}
7241
Eli Friedmanf798f652012-05-24 22:04:19 +00007242static bool IsSpecialDiscardedValue(Expr *E) {
7243 // In C++11, discarded-value expressions of a certain form are special,
7244 // according to [expr]p10:
7245 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7246 // expression is an lvalue of volatile-qualified type and it has
7247 // one of the following forms:
7248 E = E->IgnoreParens();
7249
Eli Friedmanc49c2262012-05-24 22:36:31 +00007250 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007251 if (isa<DeclRefExpr>(E))
7252 return true;
7253
Eli Friedmanc49c2262012-05-24 22:36:31 +00007254 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007255 if (isa<ArraySubscriptExpr>(E))
7256 return true;
7257
Eli Friedmanc49c2262012-05-24 22:36:31 +00007258 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007259 if (isa<MemberExpr>(E))
7260 return true;
7261
Eli Friedmanc49c2262012-05-24 22:36:31 +00007262 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007263 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7264 if (UO->getOpcode() == UO_Deref)
7265 return true;
7266
7267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007268 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007269 if (BO->isPtrMemOp())
7270 return true;
7271
Eli Friedmanc49c2262012-05-24 22:36:31 +00007272 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007273 if (BO->getOpcode() == BO_Comma)
7274 return IsSpecialDiscardedValue(BO->getRHS());
7275 }
7276
Eli Friedmanc49c2262012-05-24 22:36:31 +00007277 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007278 // operands are one of the above, or
7279 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7280 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7281 IsSpecialDiscardedValue(CO->getFalseExpr());
7282 // The related edge case of "*x ?: *x".
7283 if (BinaryConditionalOperator *BCO =
7284 dyn_cast<BinaryConditionalOperator>(E)) {
7285 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7286 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7287 IsSpecialDiscardedValue(BCO->getFalseExpr());
7288 }
7289
7290 // Objective-C++ extensions to the rule.
7291 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7292 return true;
7293
7294 return false;
7295}
7296
John McCall34376a62010-12-04 03:47:34 +00007297/// Perform the conversions required for an expression used in a
7298/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007299ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007300 if (E->hasPlaceholderType()) {
7301 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007302 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007303 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007304 }
7305
John McCallfee942d2010-12-02 02:07:15 +00007306 // C99 6.3.2.1:
7307 // [Except in specific positions,] an lvalue that does not have
7308 // array type is converted to the value stored in the
7309 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007310 if (E->isRValue()) {
7311 // In C, function designators (i.e. expressions of function type)
7312 // are r-values, but we still want to do function-to-pointer decay
7313 // on them. This is both technically correct and convenient for
7314 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007315 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007316 return DefaultFunctionArrayConversion(E);
7317
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007318 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007319 }
John McCallfee942d2010-12-02 02:07:15 +00007320
Eli Friedmanf798f652012-05-24 22:04:19 +00007321 if (getLangOpts().CPlusPlus) {
7322 // The C++11 standard defines the notion of a discarded-value expression;
7323 // normally, we don't need to do anything to handle it, but if it is a
7324 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7325 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007326 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007327 E->getType().isVolatileQualified() &&
7328 IsSpecialDiscardedValue(E)) {
7329 ExprResult Res = DefaultLvalueConversion(E);
7330 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007331 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007332 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007333 }
Richard Smith122f88d2016-12-06 23:52:28 +00007334
7335 // C++1z:
7336 // If the expression is a prvalue after this optional conversion, the
7337 // temporary materialization conversion is applied.
7338 //
7339 // We skip this step: IR generation is able to synthesize the storage for
7340 // itself in the aggregate case, and adding the extra node to the AST is
7341 // just clutter.
7342 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7343 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007344 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007345 }
John McCall34376a62010-12-04 03:47:34 +00007346
7347 // GCC seems to also exclude expressions of incomplete enum type.
7348 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7349 if (!T->getDecl()->isComplete()) {
7350 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007351 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007352 return E;
John McCall34376a62010-12-04 03:47:34 +00007353 }
7354 }
7355
John Wiegley01296292011-04-08 18:41:53 +00007356 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7357 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007358 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007359 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007360
John McCallca61b652010-12-04 12:29:11 +00007361 if (!E->getType()->isVoidType())
7362 RequireCompleteType(E->getExprLoc(), E->getType(),
7363 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007364 return E;
John McCall34376a62010-12-04 03:47:34 +00007365}
7366
Faisal Valia17d19f2013-11-07 05:17:06 +00007367// If we can unambiguously determine whether Var can never be used
7368// in a constant expression, return true.
7369// - if the variable and its initializer are non-dependent, then
7370// we can unambiguously check if the variable is a constant expression.
7371// - if the initializer is not value dependent - we can determine whether
7372// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007373// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007374// never be a constant expression.
7375// - FXIME: if the initializer is dependent, we can still do some analysis and
7376// identify certain cases unambiguously as non-const by using a Visitor:
7377// - such as those that involve odr-use of a ParmVarDecl, involve a new
7378// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007379static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007380 ASTContext &Context) {
7381 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007382 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007383
7384 // If there is no initializer - this can not be a constant expression.
7385 if (!Var->getAnyInitializer(DefVD)) return true;
7386 assert(DefVD);
7387 if (DefVD->isWeak()) return false;
7388 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007389
Faisal Valia17d19f2013-11-07 05:17:06 +00007390 Expr *Init = cast<Expr>(Eval->Value);
7391
7392 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007393 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7394 // of value-dependent expressions, and use it here to determine whether the
7395 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007396 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007397 }
7398
Simon Pilgrim75c26882016-09-30 14:25:09 +00007399 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007400}
7401
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007402/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007403/// that must be captured by any of its enclosing lambdas that are ready to
7404/// capture. If there is a lambda that can capture a nested
7405/// potential-capture, go ahead and do so. Also, check to see if any
7406/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007407/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007408
Faisal Valiab3d6462013-12-07 20:22:44 +00007409static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7410 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7411
Simon Pilgrim75c26882016-09-30 14:25:09 +00007412 assert(!S.isUnevaluatedContext());
7413 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007414#ifndef NDEBUG
7415 DeclContext *DC = S.CurContext;
7416 while (DC && isa<CapturedDecl>(DC))
7417 DC = DC->getParent();
7418 assert(
7419 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007420 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007421#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007422
7423 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7424
Faisal Valiab3d6462013-12-07 20:22:44 +00007425 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007426 // lambda (within a generic outer lambda), must be captured by an
7427 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007428 const unsigned NumPotentialCaptures =
7429 CurrentLSI->getNumPotentialVariableCaptures();
7430 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007431 Expr *VarExpr = nullptr;
7432 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007433 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007434 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007435 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007436 // need to check enclosing lambda's for speculative captures.
7437 // For e.g.:
7438 // Even though 'x' is not odr-used, it should be captured.
7439 // int test() {
7440 // const int x = 10;
7441 // auto L = [=](auto a) {
7442 // (void) +x + a;
7443 // };
7444 // }
7445 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007446 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007447 continue;
7448
7449 // If we have a capture-capable lambda for the variable, go ahead and
7450 // capture the variable in that lambda (and all its enclosing lambdas).
7451 if (const Optional<unsigned> Index =
7452 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007453 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007454 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7455 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7456 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007457 }
7458 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007459 VariableCanNeverBeAConstantExpression(Var, S.Context);
7460 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7461 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007462 // can not be used in a constant expression - which means
7463 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007464 // capture violation early, if the variable is un-captureable.
7465 // This is purely for diagnosing errors early. Otherwise, this
7466 // error would get diagnosed when the lambda becomes capture ready.
7467 QualType CaptureType, DeclRefType;
7468 SourceLocation ExprLoc = VarExpr->getExprLoc();
7469 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007470 /*EllipsisLoc*/ SourceLocation(),
7471 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007472 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007473 // We will never be able to capture this variable, and we need
7474 // to be able to in any and all instantiations, so diagnose it.
7475 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007476 /*EllipsisLoc*/ SourceLocation(),
7477 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007478 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007479 }
7480 }
7481 }
7482
Faisal Valiab3d6462013-12-07 20:22:44 +00007483 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007484 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007485 // If we have a capture-capable lambda for 'this', go ahead and capture
7486 // 'this' in that lambda (and all its enclosing lambdas).
7487 if (const Optional<unsigned> Index =
7488 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007489 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007490 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7491 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7492 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7493 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007494 }
7495 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007496
7497 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007498 CurrentLSI->clearPotentialCaptures();
7499}
7500
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007501static ExprResult attemptRecovery(Sema &SemaRef,
7502 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007503 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007504 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7505 Consumer.getLookupResult().getLookupKind());
7506 const CXXScopeSpec *SS = Consumer.getSS();
7507 CXXScopeSpec NewSS;
7508
7509 // Use an approprate CXXScopeSpec for building the expr.
7510 if (auto *NNS = TC.getCorrectionSpecifier())
7511 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7512 else if (SS && !TC.WillReplaceSpecifier())
7513 NewSS = *SS;
7514
Richard Smithde6d6c42015-12-29 19:43:10 +00007515 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007516 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007517 R.addDecl(ND);
7518 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007519 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007520 CXXRecordDecl *Record = nullptr;
7521 if (auto *NNS = TC.getCorrectionSpecifier())
7522 Record = NNS->getAsType()->getAsCXXRecordDecl();
7523 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007524 Record =
7525 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7526 if (Record)
7527 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007528
7529 // Detect and handle the case where the decl might be an implicit
7530 // member.
7531 bool MightBeImplicitMember;
7532 if (!Consumer.isAddressOfOperand())
7533 MightBeImplicitMember = true;
7534 else if (!NewSS.isEmpty())
7535 MightBeImplicitMember = false;
7536 else if (R.isOverloadedResult())
7537 MightBeImplicitMember = false;
7538 else if (R.isUnresolvableResult())
7539 MightBeImplicitMember = true;
7540 else
7541 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7542 isa<IndirectFieldDecl>(ND) ||
7543 isa<MSPropertyDecl>(ND);
7544
7545 if (MightBeImplicitMember)
7546 return SemaRef.BuildPossibleImplicitMemberExpr(
7547 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007548 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007549 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7550 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7551 Ivar->getIdentifier());
7552 }
7553 }
7554
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007555 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7556 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007557}
7558
Kaelyn Takata6c759512014-10-27 18:07:37 +00007559namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007560class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7561 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7562
7563public:
7564 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7565 : TypoExprs(TypoExprs) {}
7566 bool VisitTypoExpr(TypoExpr *TE) {
7567 TypoExprs.insert(TE);
7568 return true;
7569 }
7570};
7571
Kaelyn Takata6c759512014-10-27 18:07:37 +00007572class TransformTypos : public TreeTransform<TransformTypos> {
7573 typedef TreeTransform<TransformTypos> BaseTransform;
7574
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007575 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7576 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007577 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007578 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007579 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007580 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007582 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007583 /// If the TypoExprs were successfully corrected, then the diagnostics should
7584 /// suggest the corrections. Otherwise the diagnostics will not suggest
7585 /// anything (having been passed an empty TypoCorrection).
7586 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007587 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007588 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007589 if (State.DiagHandler) {
7590 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7591 ExprResult Replacement = TransformCache[TE];
7592
7593 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7594 // TypoCorrection, replacing the existing decls. This ensures the right
7595 // NamedDecl is used in diagnostics e.g. in the case where overload
7596 // resolution was used to select one from several possible decls that
7597 // had been stored in the TypoCorrection.
7598 if (auto *ND = getDeclFromExpr(
7599 Replacement.isInvalid() ? nullptr : Replacement.get()))
7600 TC.setCorrectionDecl(ND);
7601
7602 State.DiagHandler(TC);
7603 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007604 SemaRef.clearDelayedTypo(TE);
7605 }
7606 }
7607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007608 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007609 /// given combination of the other TypoExprs, retry those corrections against
7610 /// the next combination of substitutions for the other TypoExprs by advancing
7611 /// to the next potential correction of the second TypoExpr. For the second
7612 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7613 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7614 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7615 /// TransformCache). Returns true if there is still any untried combinations
7616 /// of corrections.
7617 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7618 for (auto TE : TypoExprs) {
7619 auto &State = SemaRef.getTypoExprState(TE);
7620 TransformCache.erase(TE);
7621 if (!State.Consumer->finished())
7622 return true;
7623 State.Consumer->resetCorrectionStream();
7624 }
7625 return false;
7626 }
7627
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007628 NamedDecl *getDeclFromExpr(Expr *E) {
7629 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7630 E = OverloadResolution[OE];
7631
7632 if (!E)
7633 return nullptr;
7634 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007635 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007636 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007637 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007638 // FIXME: Add any other expr types that could be be seen by the delayed typo
7639 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007640 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007641 return nullptr;
7642 }
7643
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007644 ExprResult TryTransform(Expr *E) {
7645 Sema::SFINAETrap Trap(SemaRef);
7646 ExprResult Res = TransformExpr(E);
7647 if (Trap.hasErrorOccurred() || Res.isInvalid())
7648 return ExprError();
7649
7650 return ExprFilter(Res.get());
7651 }
7652
Kaelyn Takata6c759512014-10-27 18:07:37 +00007653public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007654 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7655 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007656
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007657 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7658 MultiExprArg Args,
7659 SourceLocation RParenLoc,
7660 Expr *ExecConfig = nullptr) {
7661 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7662 RParenLoc, ExecConfig);
7663 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007664 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007665 Expr *ResultCall = Result.get();
7666 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7667 ResultCall = BE->getSubExpr();
7668 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7669 OverloadResolution[OE] = CE->getCallee();
7670 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007671 }
7672 return Result;
7673 }
7674
Kaelyn Takata6c759512014-10-27 18:07:37 +00007675 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7676
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007677 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7678
Kaelyn Takata6c759512014-10-27 18:07:37 +00007679 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007680 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007681 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007682 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007683
Kaelyn Takata6c759512014-10-27 18:07:37 +00007684 // Exit if either the transform was valid or if there were no TypoExprs
7685 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007686 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007687 !CheckAndAdvanceTypoExprCorrectionStreams())
7688 break;
7689 }
7690
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007691 // Ensure none of the TypoExprs have multiple typo correction candidates
7692 // with the same edit length that pass all the checks and filters.
7693 // TODO: Properly handle various permutations of possible corrections when
7694 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007695 // Also, disable typo correction while attempting the transform when
7696 // handling potentially ambiguous typo corrections as any new TypoExprs will
7697 // have been introduced by the application of one of the correction
7698 // candidates and add little to no value if corrected.
7699 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007700 while (!AmbiguousTypoExprs.empty()) {
7701 auto TE = AmbiguousTypoExprs.back();
7702 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007703 auto &State = SemaRef.getTypoExprState(TE);
7704 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007705 TransformCache.erase(TE);
7706 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007707 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007708 TransformCache.erase(TE);
7709 Res = ExprError();
7710 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007711 }
7712 AmbiguousTypoExprs.remove(TE);
7713 State.Consumer->restoreSavedPosition();
7714 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007715 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007716 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007717
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007718 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007719 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007720 FindTypoExprs(TypoExprs).TraverseStmt(E);
7721
Kaelyn Takata6c759512014-10-27 18:07:37 +00007722 EmitAllDiagnostics();
7723
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007724 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007725 }
7726
7727 ExprResult TransformTypoExpr(TypoExpr *E) {
7728 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7729 // cached transformation result if there is one and the TypoExpr isn't the
7730 // first one that was encountered.
7731 auto &CacheEntry = TransformCache[E];
7732 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7733 return CacheEntry;
7734 }
7735
7736 auto &State = SemaRef.getTypoExprState(E);
7737 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7738
7739 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7740 // typo correction and return it.
7741 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007742 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007743 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007744 // FIXME: If we would typo-correct to an invalid declaration, it's
7745 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007746 ExprResult NE = State.RecoveryHandler ?
7747 State.RecoveryHandler(SemaRef, E, TC) :
7748 attemptRecovery(SemaRef, *State.Consumer, TC);
7749 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007750 // Check whether there may be a second viable correction with the same
7751 // edit distance; if so, remember this TypoExpr may have an ambiguous
7752 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007753 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007754 if ((Next = State.Consumer->peekNextCorrection()) &&
7755 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7756 AmbiguousTypoExprs.insert(E);
7757 } else {
7758 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007759 }
7760 assert(!NE.isUnset() &&
7761 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007762 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007763 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007764 }
7765 return CacheEntry = ExprError();
7766 }
7767};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007768}
Faisal Valia17d19f2013-11-07 05:17:06 +00007769
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007770ExprResult
7771Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7772 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007773 // If the current evaluation context indicates there are uncorrected typos
7774 // and the current expression isn't guaranteed to not have typos, try to
7775 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007776 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007777 (E->isTypeDependent() || E->isValueDependent() ||
7778 E->isInstantiationDependent())) {
7779 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007780 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007781 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007782 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007783 ExprEvalContexts.back().NumTypos -= TyposResolved;
7784 return Result;
7785 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007786 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007787 }
7788 return E;
7789}
7790
Richard Smith945f8d32013-01-14 22:39:08 +00007791ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007792 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00007793 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007794 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007795
7796 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007797 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007798
Richard Smithb3d203f2018-10-19 19:01:34 +00007799 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007800 return ExprError();
7801
Richard Smith945f8d32013-01-14 22:39:08 +00007802 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00007803 // Top-level expressions default to 'id' when we're in a debugger.
7804 if (getLangOpts().DebuggerCastResultToId &&
7805 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7806 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7807 if (FullExpr.isInvalid())
7808 return ExprError();
7809 }
7810
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007811 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007812 if (FullExpr.isInvalid())
7813 return ExprError();
7814
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007815 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007816 if (FullExpr.isInvalid())
7817 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007818
7819 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007820 }
John Wiegley01296292011-04-08 18:41:53 +00007821
Kaelyn Takata49d84322014-11-11 23:26:56 +00007822 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7823 if (FullExpr.isInvalid())
7824 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007825
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007826 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007827
Simon Pilgrim75c26882016-09-30 14:25:09 +00007828 // At the end of this full expression (which could be a deeply nested
7829 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007830 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007831 // Consider the following code:
7832 // void f(int, int);
7833 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007834 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007835 // const int x = 10, y = 20;
7836 // auto L = [=](auto a) {
7837 // auto M = [=](auto b) {
7838 // f(x, b); <-- requires x to be captured by L and M
7839 // f(y, a); <-- requires y to be captured by L, but not all Ms
7840 // };
7841 // };
7842 // }
7843
Simon Pilgrim75c26882016-09-30 14:25:09 +00007844 // FIXME: Also consider what happens for something like this that involves
7845 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007846 // void f() {
7847 // const int n = 0;
7848 // auto L = [&](auto a) {
7849 // +n + ({ 0; a; });
7850 // };
7851 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007852 //
7853 // Here, we see +n, and then the full-expression 0; ends, so we don't
7854 // capture n (and instead remove it from our list of potential captures),
7855 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007856 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007857
Alexey Bataev31939e32016-11-11 12:36:20 +00007858 LambdaScopeInfo *const CurrentLSI =
7859 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007860 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007861 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007862 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007863 // By ensuring we are in the context of a lambda's call operator
7864 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007865 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007866 // PR, a proper fix would entail :
7867 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007868 // - Add to Sema an integer holding the smallest (outermost) scope
7869 // index that we are *lexically* within, and save/restore/set to
7870 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007871 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007872 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007873 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007874 DeclContext *DC = CurContext;
7875 while (DC && isa<CapturedDecl>(DC))
7876 DC = DC->getParent();
7877 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007878 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007879 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007880 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7881 *this);
John McCall5d413782010-12-06 08:20:24 +00007882 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007883}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007884
7885StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7886 if (!FullStmt) return StmtError();
7887
John McCall5d413782010-12-06 08:20:24 +00007888 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007889}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007890
Simon Pilgrim75c26882016-09-30 14:25:09 +00007891Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007892Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7893 CXXScopeSpec &SS,
7894 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007895 DeclarationName TargetName = TargetNameInfo.getName();
7896 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007897 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007898
Douglas Gregor43edb322011-10-24 22:31:10 +00007899 // If the name itself is dependent, then the result is dependent.
7900 if (TargetName.isDependentName())
7901 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007902
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007903 // Do the redeclaration lookup in the current scope.
7904 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7905 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007906 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007907 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007908
Douglas Gregor43edb322011-10-24 22:31:10 +00007909 switch (R.getResultKind()) {
7910 case LookupResult::Found:
7911 case LookupResult::FoundOverloaded:
7912 case LookupResult::FoundUnresolvedValue:
7913 case LookupResult::Ambiguous:
7914 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007915
Douglas Gregor43edb322011-10-24 22:31:10 +00007916 case LookupResult::NotFound:
7917 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007918
Douglas Gregor43edb322011-10-24 22:31:10 +00007919 case LookupResult::NotFoundInCurrentInstantiation:
7920 return IER_Dependent;
7921 }
David Blaikie8a40f702012-01-17 06:56:22 +00007922
7923 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007924}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007925
Simon Pilgrim75c26882016-09-30 14:25:09 +00007926Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007927Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7928 bool IsIfExists, CXXScopeSpec &SS,
7929 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007930 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007931
Richard Smith151c4562016-12-20 21:35:28 +00007932 // Check for an unexpanded parameter pack.
7933 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7934 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7935 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007936 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007937
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007938 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7939}