blob: dd5dfaacf248acda3f890eefc146ccddc28cdfad [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000012///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000046/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
Richard Smith715ee072018-06-20 21:58:20 +000083ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
Richard Smith69bc9aa2018-06-22 19:50:19 +000085 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
Richard Smith715ee072018-06-20 21:58:20 +000087 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&
89 "not a constructor name");
90
Richard Smith69bc9aa2018-06-22 19:50:19 +000091 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
Richard Smith715ee072018-06-20 21:58:20 +000099 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100 return ParsedType();
101
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
113 break;
114 }
115 }
Richard Smith2e34bbd2018-08-08 00:42:42 +0000116 if (!InjectedClassName) {
117 if (!CurClass->isInvalidDecl()) {
118 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119 // properly. Work around it here for now.
120 Diag(SS.getLastQualifierNameLoc(),
121 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122 }
Ilya Biryukova2d58252018-07-04 08:50:12 +0000123 return ParsedType();
Richard Smith2e34bbd2018-08-08 00:42:42 +0000124 }
Richard Smith715ee072018-06-20 21:58:20 +0000125
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130 return ParsedType::make(T);
131}
132
John McCallba7bf592010-08-24 05:47:05 +0000133ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000134 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000139 // Determine where to perform name lookup.
140
141 // FIXME: This area of the standard is very messy, and the current
142 // wording is rather unclear about which scopes we search for the
143 // destructor name; see core issues 399 and 555. Issue 399 in
144 // particular shows where the current description of destructor name
145 // lookup is completely out of line with existing practice, e.g.,
146 // this appears to be ill-formed:
147 //
148 // namespace N {
149 // template <typename T> struct S {
150 // ~S();
151 // };
152 // }
153 //
154 // void f(N::S<int>* s) {
155 // s->N::S<int>::~S();
156 // }
157 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000158 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000159 // For this reason, we're currently only doing the C++03 version of this
160 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000162 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163 bool isDependent = false;
164 bool LookInScope = false;
165
Richard Smith64e033f2015-01-15 00:48:52 +0000166 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000167 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000168
Douglas Gregorfe17d252010-02-16 19:09:40 +0000169 // If we have an object type, it's because we are in a
170 // pseudo-destructor-expression or a member access expression, and
171 // we know what type we're looking for.
172 if (ObjectTypePtr)
173 SearchType = GetTypeFromParser(ObjectTypePtr);
174
175 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000176 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000177
Douglas Gregor46841e12010-02-23 00:15:22 +0000178 bool AlreadySearched = false;
179 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000180 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000182 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000183 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000184 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000185 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000186 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000187 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000188 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000189 // Here, we determine whether the code below is permitted to look at the
190 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000191 DeclContext *DC = computeDeclContext(SS, EnteringContext);
192 if (DC && DC->isFileContext()) {
193 AlreadySearched = true;
194 LookupCtx = DC;
195 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000196 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000197 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000198 LookInScope = true;
199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000200
Sebastian Redla771d222010-07-07 23:17:38 +0000201 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000202 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000203 if (AlreadySearched) {
204 // Nothing left to do.
205 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000207 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000208 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000210 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211 LookupCtx = computeDeclContext(SearchType);
212 isDependent = SearchType->isDependentType();
213 } else {
214 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000215 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000216 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 } else if (ObjectTypePtr) {
218 // C++ [basic.lookup.classref]p3:
219 // If the unqualified-id is ~type-name, the type-name is looked up
220 // in the context of the entire postfix-expression. If the type T
221 // of the object expression is of a class type C, the type-name is
222 // also looked up in the scope of class C. At least one of the
223 // lookups shall find a name that refers to (possibly
224 // cv-qualified) T.
225 LookupCtx = computeDeclContext(SearchType);
226 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000227 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000228 "Caller should have completed object type");
229
230 LookInScope = true;
231 } else {
232 // Perform lookup into the current scope (only).
233 LookInScope = true;
234 }
235
Craig Topperc3ec1492014-05-26 06:22:03 +0000236 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238 for (unsigned Step = 0; Step != 2; ++Step) {
239 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000240 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000241 // we're allowed to look there).
242 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000243 if (Step == 0 && LookupCtx) {
244 if (RequireCompleteDeclContext(SS, LookupCtx))
245 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000246 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000247 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000248 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000249 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250 continue;
John McCallcb731542017-06-11 20:33:00 +0000251 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000252
253 // FIXME: Should we be suppressing ambiguities here?
254 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000255 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256
257 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000259 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000260
261 if (SearchType.isNull() || SearchType->isDependentType() ||
262 Context.hasSameUnqualifiedType(T, SearchType)) {
263 // We found our type!
264
Richard Smithc278c002014-01-22 00:30:17 +0000265 return CreateParsedType(T,
266 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000267 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000268
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000269 if (!SearchType.isNull())
270 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000271 }
272
273 // If the name that we found is a class template name, and it is
274 // the same name as the template name in the last part of the
275 // nested-name-specifier (if present) or the object type, then
276 // this is the destructor for that class.
277 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280 QualType MemberOfType;
281 if (SS.isSet()) {
282 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000286 }
287 }
288 if (MemberOfType.isNull())
289 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
Douglas Gregorfe17d252010-02-16 19:09:40 +0000291 if (MemberOfType.isNull())
292 continue;
293
294 // We're referring into a class template specialization. If the
295 // class template we found is the same as the template being
296 // specialized, we found what we are looking for.
297 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
298 if (ClassTemplateSpecializationDecl *Spec
299 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000302 return CreateParsedType(
303 MemberOfType,
304 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000305 }
306
307 continue;
308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
Douglas Gregorfe17d252010-02-16 19:09:40 +0000310 // We're referring to an unresolved class template
311 // specialization. Determine whether we class template we found
312 // is the same as the template being specialized or, if we don't
313 // know which template is being specialized, that it at least
314 // has the same name.
315 if (const TemplateSpecializationType *SpecType
316 = MemberOfType->getAs<TemplateSpecializationType>()) {
317 TemplateName SpecName = SpecType->getTemplateName();
318
319 // The class template we found is the same template being
320 // specialized.
321 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000323 return CreateParsedType(
324 MemberOfType,
325 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000326
327 continue;
328 }
329
330 // The class template we found has the same name as the
331 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000333 = SpecName.getAsDependentTemplateName()) {
334 if (DepTemplate->isIdentifier() &&
335 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000336 return CreateParsedType(
337 MemberOfType,
338 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000339
340 continue;
341 }
342 }
343 }
344 }
345
346 if (isDependent) {
347 // We didn't find our type, but that's okay: it's dependent
348 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000349
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000350 // FIXME: What if we have no nested-name-specifier?
351 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352 SS.getWithLocInContext(Context),
353 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000354 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000355 }
356
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000357 if (NonMatchingTypeDecl) {
358 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
360 << T << SearchType;
361 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
362 << T;
363 } else if (ObjectTypePtr)
364 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000366 else {
367 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368 diag::err_destructor_class_name);
369 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000370 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000371 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373 Class->getNameAsString());
374 }
375 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000376
David Blaikieefdccaa2016-01-15 23:43:34 +0000377 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000378}
379
Richard Smithef2cd8f2017-02-08 20:39:08 +0000380ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
381 ParsedType ObjectType) {
382 if (DS.getTypeSpecType() == DeclSpec::TST_error)
383 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000384
Richard Smithef2cd8f2017-02-08 20:39:08 +0000385 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
386 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
387 return nullptr;
388 }
389
390 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
391 "unexpected type in getDestructorType");
392 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
393
394 // If we know the type of the object, check that the correct destructor
395 // type was named now; we can give better diagnostics this way.
396 QualType SearchType = GetTypeFromParser(ObjectType);
397 if (!SearchType.isNull() && !SearchType->isDependentType() &&
398 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000399 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
400 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000401 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000402 }
403
404 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000405}
406
Richard Smithd091dc12013-12-05 00:58:33 +0000407bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
408 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000409 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000410
411 if (!SS.isValid())
412 return false;
413
414 switch (SS.getScopeRep()->getKind()) {
415 case NestedNameSpecifier::Identifier:
416 case NestedNameSpecifier::TypeSpec:
417 case NestedNameSpecifier::TypeSpecWithTemplate:
418 // Per C++11 [over.literal]p2, literal operators can only be declared at
419 // namespace scope. Therefore, this unqualified-id cannot name anything.
420 // Reject it early, because we have no AST representation for this in the
421 // case where the scope is dependent.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000422 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
423 << SS.getScopeRep();
Richard Smithd091dc12013-12-05 00:58:33 +0000424 return true;
425
426 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000427 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000428 case NestedNameSpecifier::Namespace:
429 case NestedNameSpecifier::NamespaceAlias:
430 return false;
431 }
432
433 llvm_unreachable("unknown nested name specifier kind");
434}
435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000437ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000438 SourceLocation TypeidLoc,
439 TypeSourceInfo *Operand,
440 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000441 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000443 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000444 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000446 Qualifiers Quals;
447 QualType T
448 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
449 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 if (T->getAs<RecordType>() &&
451 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
452 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
David Majnemer6f3150a2014-11-21 21:09:12 +0000454 if (T->isVariablyModifiedType())
455 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
456
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
458 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000459}
460
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000461/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000462ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000463 SourceLocation TypeidLoc,
464 Expr *E,
465 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000466 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000467 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000468 if (E->getType()->isPlaceholderType()) {
469 ExprResult result = CheckPlaceholderExpr(E);
470 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000471 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000472 }
473
Douglas Gregor9da64192010-04-26 22:37:10 +0000474 QualType T = E->getType();
475 if (const RecordType *RecordT = T->getAs<RecordType>()) {
476 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
477 // C++ [expr.typeid]p3:
478 // [...] If the type of the expression is a class type, the class
479 // shall be completely-defined.
480 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
481 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482
Douglas Gregor9da64192010-04-26 22:37:10 +0000483 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000484 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000485 // polymorphic class type [...] [the] expression is an unevaluated
486 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000487 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000488 // The subexpression is potentially evaluated; switch the context
489 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000490 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000491 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000492 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000493
494 // We require a vtable to query the type at run time.
495 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000496 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000497 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499
Douglas Gregor9da64192010-04-26 22:37:10 +0000500 // C++ [expr.typeid]p4:
501 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502 // cv-qualified type, the result of the typeid expression refers to a
503 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000505 Qualifiers Quals;
506 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
507 if (!Context.hasSameType(T, UnqualT)) {
508 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000509 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000510 }
511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000512
David Majnemer6f3150a2014-11-21 21:09:12 +0000513 if (E->getType()->isVariablyModifiedType())
514 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
515 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000516 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000517 E->HasSideEffects(Context, WasEvaluated)) {
518 // The expression operand for typeid is in an unevaluated expression
519 // context, so side effects could result in unintended consequences.
520 Diag(E->getExprLoc(), WasEvaluated
521 ? diag::warn_side_effects_typeid
522 : diag::warn_side_effects_unevaluated_context);
523 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000524
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000525 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
526 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000527}
528
529/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000530ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000531Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
532 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000533 // OpenCL C++ 1.0 s2.9: typeid is not supported.
534 if (getLangOpts().OpenCLCPlusPlus) {
535 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
536 << "typeid");
537 }
538
Douglas Gregor9da64192010-04-26 22:37:10 +0000539 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000540 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000541 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000542
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000543 if (!CXXTypeInfoDecl) {
544 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
545 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
546 LookupQualifiedName(R, getStdNamespace());
547 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000548 // Microsoft's typeinfo doesn't have type_info in std but in the global
549 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000550 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000551 LookupQualifiedName(R, Context.getTranslationUnitDecl());
552 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
553 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000554 if (!CXXTypeInfoDecl)
555 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Nico Weber1b7f39d2012-05-20 01:27:21 +0000558 if (!getLangOpts().RTTI) {
559 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
560 }
561
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000562 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor9da64192010-04-26 22:37:10 +0000564 if (isType) {
565 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000566 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000567 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
568 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000569 if (T.isNull())
570 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregor9da64192010-04-26 22:37:10 +0000572 if (!TInfo)
573 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000574
Douglas Gregor9da64192010-04-26 22:37:10 +0000575 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000576 }
Mike Stump11289f42009-09-09 15:08:12 +0000577
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000579 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000580}
581
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
583/// a single GUID.
584static void
585getUuidAttrOfType(Sema &SemaRef, QualType QT,
586 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
587 // Optionally remove one level of pointer, reference or array indirection.
588 const Type *Ty = QT.getTypePtr();
589 if (QT->isPointerType() || QT->isReferenceType())
590 Ty = QT->getPointeeType().getTypePtr();
591 else if (QT->isArrayType())
592 Ty = Ty->getBaseElementTypeUnsafe();
593
Reid Klecknere516eab2016-12-13 18:58:09 +0000594 const auto *TD = Ty->getAsTagDecl();
595 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000596 return;
597
Reid Klecknere516eab2016-12-13 18:58:09 +0000598 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000599 UuidAttrs.insert(Uuid);
600 return;
601 }
602
603 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000604 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000605 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
606 for (const TemplateArgument &TA : TAL.asArray()) {
607 const UuidAttr *UuidForTA = nullptr;
608 if (TA.getKind() == TemplateArgument::Type)
609 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
610 else if (TA.getKind() == TemplateArgument::Declaration)
611 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
612
613 if (UuidForTA)
614 UuidAttrs.insert(UuidForTA);
615 }
616 }
617}
618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000620ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
621 SourceLocation TypeidLoc,
622 TypeSourceInfo *Operand,
623 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000624 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000625 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000626 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
627 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
628 if (UuidAttrs.empty())
629 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
630 if (UuidAttrs.size() > 1)
631 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000632 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
David Majnemer2041b462016-03-28 03:19:50 +0000635 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000636 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000637}
638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000639/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000640ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
641 SourceLocation TypeidLoc,
642 Expr *E,
643 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000644 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000645 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000646 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
647 UuidStr = "00000000-0000-0000-0000-000000000000";
648 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000649 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
650 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
651 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000652 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000653 if (UuidAttrs.size() > 1)
654 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000655 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000656 }
Francois Pichetb7577652010-12-27 01:32:00 +0000657 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000658
David Majnemer2041b462016-03-28 03:19:50 +0000659 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000660 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000661}
662
663/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
664ExprResult
665Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
666 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000668 if (!MSVCGuidDecl) {
669 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
670 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
671 LookupQualifiedName(R, Context.getTranslationUnitDecl());
672 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
673 if (!MSVCGuidDecl)
674 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675 }
676
Francois Pichet9f4f2072010-09-08 12:20:18 +0000677 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Francois Pichet9f4f2072010-09-08 12:20:18 +0000679 if (isType) {
680 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000682 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
683 &TInfo);
684 if (T.isNull())
685 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686
Francois Pichet9f4f2072010-09-08 12:20:18 +0000687 if (!TInfo)
688 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
689
690 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
691 }
692
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000694 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
695}
696
Steve Naroff66356bd2007-09-16 14:56:35 +0000697/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000698ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000699Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000700 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000701 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000702 return new (Context)
703 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000704}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000705
Sebastian Redl576fd422009-05-10 18:38:11 +0000706/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000707ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000708Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000709 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000710}
711
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000712/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000713ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000714Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
715 bool IsThrownVarInScope = false;
716 if (Ex) {
717 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000718 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000719 // copy/move construction of a class object [...]
720 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000721 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000722 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000723 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000724 // innermost enclosing try-block (if there is one), the copy/move
725 // operation from the operand to the exception object (15.1) can be
726 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000727 // exception object
728 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
729 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
730 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
731 for( ; S; S = S->getParent()) {
732 if (S->isDeclScope(Var)) {
733 IsThrownVarInScope = true;
734 break;
735 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000736
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000737 if (S->getFlags() &
738 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
739 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
740 Scope::TryScope))
741 break;
742 }
743 }
744 }
745 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000746
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000747 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
748}
749
Simon Pilgrim75c26882016-09-30 14:25:09 +0000750ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000751 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000752 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000753 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +0000754 !getSourceManager().isInSystemHeader(OpLoc) &&
755 (!getLangOpts().OpenMPIsDevice ||
756 !getLangOpts().OpenMPHostCXXExceptions ||
757 isInOpenMPTargetExecutionDirective() ||
758 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000759 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000760
Justin Lebar2a8db342016-09-28 22:45:54 +0000761 // Exceptions aren't allowed in CUDA device code.
762 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000763 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000765
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000766 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768
John Wiegley01296292011-04-08 18:41:53 +0000769 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000770 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000772 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000773
774 // Initialize the exception result. This implicitly weeds out
775 // abstract types or types with inaccessible copy constructors.
776
777 // C++0x [class.copymove]p31:
778 // When certain criteria are met, an implementation is allowed to omit the
779 // copy/move construction of a class object [...]
780 //
781 // - in a throw-expression, when the operand is the name of a
782 // non-volatile automatic object (other than a function or
783 // catch-clause
784 // parameter) whose scope does not extend beyond the end of the
785 // innermost enclosing try-block (if there is one), the copy/move
786 // operation from the operand to the exception object (15.1) can be
787 // omitted by constructing the automatic object directly into the
788 // exception object
789 const VarDecl *NRVOVariable = nullptr;
790 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000791 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000792
793 InitializedEntity Entity = InitializedEntity::InitializeException(
794 OpLoc, ExceptionObjectTy,
795 /*NRVO=*/NRVOVariable != nullptr);
796 ExprResult Res = PerformMoveOrCopyInitialization(
797 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798 if (Res.isInvalid())
799 return ExprError();
800 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000801 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000802
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000803 return new (Context)
804 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000805}
806
David Majnemere7a818f2015-03-06 18:53:55 +0000807static void
808collectPublicBases(CXXRecordDecl *RD,
809 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812 bool ParentIsPublic) {
813 for (const CXXBaseSpecifier &BS : RD->bases()) {
814 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815 bool NewSubobject;
816 // Virtual bases constitute the same subobject. Non-virtual bases are
817 // always distinct subobjects.
818 if (BS.isVirtual())
819 NewSubobject = VBases.insert(BaseDecl).second;
820 else
821 NewSubobject = true;
822
823 if (NewSubobject)
824 ++SubobjectsSeen[BaseDecl];
825
826 // Only add subobjects which have public access throughout the entire chain.
827 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828 if (PublicPath)
829 PublicSubobjectsSeen.insert(BaseDecl);
830
831 // Recurse on to each base subobject.
832 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833 PublicPath);
834 }
835}
836
837static void getUnambiguousPublicSubobjects(
838 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
839 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842 SubobjectsSeen[RD] = 1;
843 PublicSubobjectsSeen.insert(RD);
844 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845 /*ParentIsPublic=*/true);
846
847 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848 // Skip ambiguous objects.
849 if (SubobjectsSeen[PublicSubobject] > 1)
850 continue;
851
852 Objects.push_back(PublicSubobject);
853 }
854}
855
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000857bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
858 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000859 // If the type of the exception would be an incomplete type or a pointer
860 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000861 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000862 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000863 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000864 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000865 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000866 }
867 if (!isPointer || !Ty->isVoidType()) {
868 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000869 isPointer ? diag::err_throw_incomplete_ptr
870 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000871 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000872 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000873
David Majnemerd09a51c2015-03-03 01:50:05 +0000874 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000875 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000876 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000877 }
878
Eli Friedman91a3d272010-06-03 20:39:03 +0000879 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000880 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881 if (!RD)
882 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000883
Douglas Gregor88d292c2010-05-13 16:44:06 +0000884 // If we are throwing a polymorphic class type or pointer thereof,
885 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000886 MarkVTableUsed(ThrowLoc, RD);
887
Eli Friedman36ebbec2010-10-12 20:32:36 +0000888 // If a pointer is thrown, the referenced object will not be destroyed.
889 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000890 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000891
Richard Smitheec915d62012-02-18 04:13:32 +0000892 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000893 if (!RD->hasIrrelevantDestructor()) {
894 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895 MarkFunctionReferenced(E->getExprLoc(), Destructor);
896 CheckDestructorAccess(E->getExprLoc(), Destructor,
897 PDiag(diag::err_access_dtor_exception) << Ty);
898 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000899 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000900 }
901 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000902
David Majnemerdfa6d202015-03-11 18:36:39 +0000903 // The MSVC ABI creates a list of all types which can catch the exception
904 // object. This list also references the appropriate copy constructor to call
905 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000906 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000907 // We are only interested in the public, unambiguous bases contained within
908 // the exception object. Bases which are ambiguous or otherwise
909 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000910 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000912
David Majnemere7a818f2015-03-06 18:53:55 +0000913 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000914 // Attempt to lookup the copy constructor. Various pieces of machinery
915 // will spring into action, like template instantiation, which means this
916 // cannot be a simple walk of the class's decls. Instead, we must perform
917 // lookup and overload resolution.
918 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919 if (!CD)
920 continue;
921
922 // Mark the constructor referenced as it is used by this throw expression.
923 MarkFunctionReferenced(E->getExprLoc(), CD);
924
925 // Skip this copy constructor if it is trivial, we don't need to record it
926 // in the catchable type data.
927 if (CD->isTrivial())
928 continue;
929
930 // The copy constructor is non-trivial, create a mapping from this class
931 // type to this constructor.
932 // N.B. The selection of copy constructor is not sensitive to this
933 // particular throw-site. Lookup will be performed at the catch-site to
934 // ensure that the copy constructor is, in fact, accessible (via
935 // friendship or any other means).
936 Context.addCopyConstructorForExceptionObject(Subobject, CD);
937
938 // We don't keep the instantiated default argument expressions around so
939 // we must rebuild them here.
940 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000941 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000943 }
944 }
945 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000946
David Majnemerba3e5ec2015-03-13 18:26:17 +0000947 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000948}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000949
Faisal Vali67b04462016-06-11 16:41:54 +0000950static QualType adjustCVQualifiersForCXXThisWithinLambda(
951 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953
954 QualType ClassType = ThisTy->getPointeeType();
955 LambdaScopeInfo *CurLSI = nullptr;
956 DeclContext *CurDC = CurSemaContext;
957
958 // Iterate through the stack of lambdas starting from the innermost lambda to
959 // the outermost lambda, checking if '*this' is ever captured by copy - since
960 // that could change the cv-qualifiers of the '*this' object.
961 // The object referred to by '*this' starts out with the cv-qualifiers of its
962 // member function. We then start with the innermost lambda and iterate
963 // outward checking to see if any lambda performs a by-copy capture of '*this'
964 // - and if so, any nested lambda must respect the 'constness' of that
965 // capturing lamdbda's call operator.
966 //
967
Faisal Vali999f27e2017-05-02 20:56:34 +0000968 // Since the FunctionScopeInfo stack is representative of the lexical
969 // nesting of the lambda expressions during initial parsing (and is the best
970 // place for querying information about captures about lambdas that are
971 // partially processed) and perhaps during instantiation of function templates
972 // that contain lambda expressions that need to be transformed BUT not
973 // necessarily during instantiation of a nested generic lambda's function call
974 // operator (which might even be instantiated at the end of the TU) - at which
975 // time the DeclContext tree is mature enough to query capture information
976 // reliably - we use a two pronged approach to walk through all the lexically
977 // enclosing lambda expressions:
978 //
979 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981 // enclosed by the call-operator of the LSI below it on the stack (while
982 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983 // the stack represents the innermost lambda.
984 //
985 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986 // represents a lambda's call operator. If it does, we must be instantiating
987 // a generic lambda's call operator (represented by the Current LSI, and
988 // should be the only scenario where an inconsistency between the LSI and the
989 // DeclContext should occur), so climb out the DeclContexts if they
990 // represent lambdas, while querying the corresponding closure types
991 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000992
Faisal Vali999f27e2017-05-02 20:56:34 +0000993 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000994 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000995 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000998 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001000
1001 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001002 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001003
Faisal Vali67b04462016-06-11 16:41:54 +00001004 auto C = CurLSI->getCXXThisCapture();
1005
1006 if (C.isCopyCapture()) {
1007 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1008 if (CurLSI->CallOperator->isConst())
1009 ClassType.addConst();
1010 return ASTCtx.getPointerType(ClassType);
1011 }
1012 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001013
1014 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001016 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001017 assert(CurLSI && "While computing 'this' capture-type for a generic "
1018 "lambda, we must have a corresponding LambdaScopeInfo");
1019 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1020 "While computing 'this' capture-type for a generic lambda, when we "
1021 "run out of enclosing LSI's, yet the enclosing DC is a "
1022 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1023 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001024 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001025
Faisal Vali67b04462016-06-11 16:41:54 +00001026 auto IsThisCaptured =
1027 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028 IsConst = false;
1029 IsByCopy = false;
1030 for (auto &&C : Closure->captures()) {
1031 if (C.capturesThis()) {
1032 if (C.getCaptureKind() == LCK_StarThis)
1033 IsByCopy = true;
1034 if (Closure->getLambdaCallOperator()->isConst())
1035 IsConst = true;
1036 return true;
1037 }
1038 }
1039 return false;
1040 };
1041
1042 bool IsByCopyCapture = false;
1043 bool IsConstCapture = false;
1044 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045 while (Closure &&
1046 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047 if (IsByCopyCapture) {
1048 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1049 if (IsConstCapture)
1050 ClassType.addConst();
1051 return ASTCtx.getPointerType(ClassType);
1052 }
1053 Closure = isLambdaCallOperator(Closure->getParent())
1054 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055 : nullptr;
1056 }
1057 }
1058 return ASTCtx.getPointerType(ClassType);
1059}
1060
Eli Friedman73a04092012-01-07 04:59:52 +00001061QualType Sema::getCurrentThisType() {
1062 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001063 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001064
Richard Smith938f40b2011-06-11 17:19:42 +00001065 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066 if (method && method->isInstance())
1067 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001068 }
Faisal Validc6b5962016-03-21 09:25:37 +00001069
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001070 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001071 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001072
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001073 assert(isa<CXXRecordDecl>(DC) &&
1074 "Trying to get 'this' type from static method?");
1075
1076 // This is a lambda call operator that is being instantiated as a default
1077 // initializer. DC must point to the enclosing class type, so we can recover
1078 // the 'this' type from it.
1079
1080 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081 // There are no cv-qualifiers for 'this' within default initializers,
1082 // per [expr.prim.general]p4.
1083 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001084 }
Faisal Vali67b04462016-06-11 16:41:54 +00001085
1086 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087 // might need to be adjusted if the lambda or any of its enclosing lambda's
1088 // captures '*this' by copy.
1089 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001092 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001093}
1094
Simon Pilgrim75c26882016-09-30 14:25:09 +00001095Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001096 Decl *ContextDecl,
1097 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001098 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001099 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100{
1101 if (!Enabled || !ContextDecl)
1102 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001103
1104 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001105 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106 Record = Template->getTemplatedDecl();
1107 else
1108 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001109
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001110 // We care only for CVR qualifiers here, so cut everything else.
1111 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001112 S.CXXThisTypeOverride
1113 = S.Context.getPointerType(
1114 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001115
Douglas Gregor3024f072012-04-16 07:05:22 +00001116 this->Enabled = true;
1117}
1118
1119
1120Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1121 if (Enabled) {
1122 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1123 }
1124}
1125
Faisal Validc6b5962016-03-21 09:25:37 +00001126static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1127 QualType ThisTy, SourceLocation Loc,
1128 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001129
Faisal Vali67b04462016-06-11 16:41:54 +00001130 QualType AdjustedThisTy = ThisTy;
1131 // The type of the corresponding data member (not a 'this' pointer if 'by
1132 // copy').
1133 QualType CaptureThisFieldTy = ThisTy;
1134 if (ByCopy) {
1135 // If we are capturing the object referred to by '*this' by copy, ignore any
1136 // cv qualifiers inherited from the type of the member function for the type
1137 // of the closure-type's corresponding data member and any use of 'this'.
1138 CaptureThisFieldTy = ThisTy->getPointeeType();
1139 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1140 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1141 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001142
Faisal Vali67b04462016-06-11 16:41:54 +00001143 FieldDecl *Field = FieldDecl::Create(
1144 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1145 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1146 ICIS_NoInit);
1147
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001148 Field->setImplicit(true);
1149 Field->setAccess(AS_private);
1150 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001151 Expr *This =
1152 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001153 if (ByCopy) {
1154 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1155 UO_Deref,
1156 This).get();
1157 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001158 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001159 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1160 InitializationSequence Init(S, Entity, InitKind, StarThis);
1161 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1162 if (ER.isInvalid()) return nullptr;
1163 return ER.get();
1164 }
1165 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001166}
1167
Simon Pilgrim75c26882016-09-30 14:25:09 +00001168bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001169 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1170 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001171 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001172 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001173 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001174
Faisal Validc6b5962016-03-21 09:25:37 +00001175 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001176
Reid Kleckner87a31802018-03-12 21:43:02 +00001177 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1178 ? *FunctionScopeIndexToStopAt
1179 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001180
Simon Pilgrim75c26882016-09-30 14:25:09 +00001181 // Check that we can capture the *enclosing object* (referred to by '*this')
1182 // by the capturing-entity/closure (lambda/block/etc) at
1183 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1184
1185 // Note: The *enclosing object* can only be captured by-value by a
1186 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001187 // [*this] { ... }.
1188 // Every other capture of the *enclosing object* results in its by-reference
1189 // capture.
1190
1191 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1192 // stack), we can capture the *enclosing object* only if:
1193 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1194 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001195 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001196 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001197 // -- or, there is some enclosing closure 'E' that has already captured the
1198 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001199 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001200 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001201 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001202
1203
Faisal Validc6b5962016-03-21 09:25:37 +00001204 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001205 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001206 if (CapturingScopeInfo *CSI =
1207 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1208 if (CSI->CXXThisCaptureIndex != 0) {
1209 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001210 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001211 break;
1212 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001213 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1214 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1215 // This context can't implicitly capture 'this'; fail out.
1216 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001217 Diag(Loc, diag::err_this_capture)
1218 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001219 return true;
1220 }
Eli Friedman20139d32012-01-11 02:36:31 +00001221 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001222 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001223 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001224 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001225 (Explicit && idx == MaxFunctionScopesIndex)) {
1226 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1227 // iteration through can be an explicit capture, all enclosing closures,
1228 // if any, must perform implicit captures.
1229
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001230 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001231 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001232 continue;
1233 }
Eli Friedman20139d32012-01-11 02:36:31 +00001234 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001235 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001236 Diag(Loc, diag::err_this_capture)
1237 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001238 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001239 }
Eli Friedman73a04092012-01-07 04:59:52 +00001240 break;
1241 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001242 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001243
1244 // If we got here, then the closure at MaxFunctionScopesIndex on the
1245 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1246 // (including implicit by-reference captures in any enclosing closures).
1247
1248 // In the loop below, respect the ByCopy flag only for the closure requesting
1249 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001250 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001251 // implicitly capturing the *enclosing object* by reference (see loop
1252 // above)).
1253 assert((!ByCopy ||
1254 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1255 "Only a lambda can capture the enclosing object (referred to by "
1256 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001257 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1258 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001259 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001260 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1261 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001262 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001263 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001264
Faisal Validc6b5962016-03-21 09:25:37 +00001265 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1266 // For lambda expressions, build a field and an initializing expression,
1267 // and capture the *enclosing object* by copy only if this is the first
1268 // iteration.
1269 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1270 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001271
Faisal Validc6b5962016-03-21 09:25:37 +00001272 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001273 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001274 ThisExpr =
1275 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1276 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001277
Faisal Validc6b5962016-03-21 09:25:37 +00001278 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001279 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001280 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001281 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001282}
1283
Richard Smith938f40b2011-06-11 17:19:42 +00001284ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001285 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1286 /// is a non-lvalue expression whose value is the address of the object for
1287 /// which the function is called.
1288
Douglas Gregor09deffa2011-10-18 16:47:30 +00001289 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001290 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001291
Eli Friedman73a04092012-01-07 04:59:52 +00001292 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001293 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001294}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001295
Douglas Gregor3024f072012-04-16 07:05:22 +00001296bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1297 // If we're outside the body of a member function, then we'll have a specified
1298 // type for 'this'.
1299 if (CXXThisTypeOverride.isNull())
1300 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001301
Douglas Gregor3024f072012-04-16 07:05:22 +00001302 // Determine whether we're looking into a class that's currently being
1303 // defined.
1304 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1305 return Class && Class->isBeingDefined();
1306}
1307
Vedant Kumara14a1f92018-01-17 18:53:51 +00001308/// Parse construction of a specified type.
1309/// Can be interpreted either as function-style casting ("int(x)")
1310/// or class type construction ("ClassType(x,y,z)")
1311/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001312ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001313Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001314 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001315 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001316 SourceLocation RParenOrBraceLoc,
1317 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001318 if (!TypeRep)
1319 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
John McCall97513962010-01-15 18:39:57 +00001321 TypeSourceInfo *TInfo;
1322 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1323 if (!TInfo)
1324 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001325
Vedant Kumara14a1f92018-01-17 18:53:51 +00001326 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1327 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001328 // Avoid creating a non-type-dependent expression that contains typos.
1329 // Non-type-dependent expressions are liable to be discarded without
1330 // checking for embedded typos.
1331 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1332 !Result.get()->isTypeDependent())
1333 Result = CorrectDelayedTyposInExpr(Result.get());
1334 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001335}
1336
Douglas Gregor2b88c112010-09-08 00:15:04 +00001337ExprResult
1338Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001339 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001340 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001341 SourceLocation RParenOrBraceLoc,
1342 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001343 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001344 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001345
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001346 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001347 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1348 // directly. We work around this by dropping the locations of the braces.
1349 SourceRange Locs = ListInitialization
1350 ? SourceRange()
1351 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1352 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1353 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001354 }
1355
Richard Smith600b5262017-01-26 20:40:47 +00001356 assert((!ListInitialization ||
1357 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1358 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001359 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001360
Richard Smith60437622017-02-09 19:17:44 +00001361 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1362 InitializationKind Kind =
1363 Exprs.size()
1364 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001365 ? InitializationKind::CreateDirectList(
1366 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1367 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1368 RParenOrBraceLoc)
1369 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1370 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001371
1372 // C++1z [expr.type.conv]p1:
1373 // If the type is a placeholder for a deduced class type, [...perform class
1374 // template argument deduction...]
1375 DeducedType *Deduced = Ty->getContainedDeducedType();
1376 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1377 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1378 Kind, Exprs);
1379 if (Ty.isNull())
1380 return ExprError();
1381 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1382 }
1383
Douglas Gregordd04d332009-01-16 18:33:17 +00001384 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001385 // If the expression list is a parenthesized single expression, the type
1386 // conversion expression is equivalent (in definedness, and if defined in
1387 // meaning) to the corresponding cast expression.
1388 if (Exprs.size() == 1 && !ListInitialization &&
1389 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001390 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001391 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1392 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001393 }
1394
Richard Smith49a6b6e2017-03-24 01:14:25 +00001395 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001396 QualType ElemTy = Ty;
1397 if (Ty->isArrayType()) {
1398 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001399 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1400 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001401 ElemTy = Context.getBaseElementType(Ty);
1402 }
1403
Richard Smith49a6b6e2017-03-24 01:14:25 +00001404 // There doesn't seem to be an explicit rule against this but sanity demands
1405 // we only construct objects with object types.
1406 if (Ty->isFunctionType())
1407 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1408 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001409
Richard Smith49a6b6e2017-03-24 01:14:25 +00001410 // C++17 [expr.type.conv]p2:
1411 // If the type is cv void and the initializer is (), the expression is a
1412 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001413 if (!Ty->isVoidType() &&
1414 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001415 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001416 return ExprError();
1417
Richard Smith49a6b6e2017-03-24 01:14:25 +00001418 // Otherwise, the expression is a prvalue of the specified type whose
1419 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001420 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1421 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001422
Richard Smith49a6b6e2017-03-24 01:14:25 +00001423 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001424 return Result;
1425
1426 Expr *Inner = Result.get();
1427 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1428 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001429 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1430 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001431 // If we created a CXXTemporaryObjectExpr, that node also represents the
1432 // functional cast. Otherwise, create an explicit cast to represent
1433 // the syntactic form of a functional-style cast that was used here.
1434 //
1435 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1436 // would give a more consistent AST representation than using a
1437 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1438 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001439 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001440 SourceRange Locs = ListInitialization
1441 ? SourceRange()
1442 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001443 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001444 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1445 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001446 }
1447
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001448 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001449}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001450
Artem Belevich78929ef2018-09-21 17:29:33 +00001451bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1452 // [CUDA] Ignore this function, if we can't call it.
1453 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1454 if (getLangOpts().CUDA &&
1455 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1456 return false;
1457
1458 SmallVector<const FunctionDecl*, 4> PreventedBy;
1459 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1460
1461 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1462 return Result;
1463
1464 // In case of CUDA, return true if none of the 1-argument deallocator
1465 // functions are actually callable.
1466 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1467 assert(FD->getNumParams() == 1 &&
1468 "Only single-operand functions should be in PreventedBy");
1469 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1470 });
1471}
1472
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001473/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001474/// deallocation function.
1475static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001476 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001477 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001478
1479 if (FD->getOverloadedOperator() != OO_Delete &&
1480 FD->getOverloadedOperator() != OO_Array_Delete)
1481 return false;
1482
1483 unsigned UsualParams = 1;
1484
1485 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1486 S.Context.hasSameUnqualifiedType(
1487 FD->getParamDecl(UsualParams)->getType(),
1488 S.Context.getSizeType()))
1489 ++UsualParams;
1490
1491 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1492 S.Context.hasSameUnqualifiedType(
1493 FD->getParamDecl(UsualParams)->getType(),
1494 S.Context.getTypeDeclType(S.getStdAlignValT())))
1495 ++UsualParams;
1496
1497 return UsualParams == FD->getNumParams();
1498}
1499
1500namespace {
1501 struct UsualDeallocFnInfo {
1502 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001503 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001504 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001505 Destroying(false), HasSizeT(false), HasAlignValT(false),
1506 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001507 // A function template declaration is never a usual deallocation function.
1508 if (!FD)
1509 return;
Richard Smith5b349582017-10-13 01:55:36 +00001510 unsigned NumBaseParams = 1;
1511 if (FD->isDestroyingOperatorDelete()) {
1512 Destroying = true;
1513 ++NumBaseParams;
1514 }
1515 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001516 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001517 else if (FD->getNumParams() == NumBaseParams + 1) {
1518 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001519 HasAlignValT = !HasSizeT;
1520 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001521
1522 // In CUDA, determine how much we'd like / dislike to call this.
1523 if (S.getLangOpts().CUDA)
1524 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1525 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001526 }
1527
Eric Fiselierfa752f22018-03-21 19:19:48 +00001528 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001529
Richard Smithf75dcbe2016-10-11 00:21:10 +00001530 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1531 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001532 // C++ P0722:
1533 // A destroying operator delete is preferred over a non-destroying
1534 // operator delete.
1535 if (Destroying != Other.Destroying)
1536 return Destroying;
1537
Richard Smithf75dcbe2016-10-11 00:21:10 +00001538 // C++17 [expr.delete]p10:
1539 // If the type has new-extended alignment, a function with a parameter
1540 // of type std::align_val_t is preferred; otherwise a function without
1541 // such a parameter is preferred
1542 if (HasAlignValT != Other.HasAlignValT)
1543 return HasAlignValT == WantAlign;
1544
1545 if (HasSizeT != Other.HasSizeT)
1546 return HasSizeT == WantSize;
1547
1548 // Use CUDA call preference as a tiebreaker.
1549 return CUDAPref > Other.CUDAPref;
1550 }
1551
Richard Smithb2f0f052016-10-10 18:54:32 +00001552 DeclAccessPair Found;
1553 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001554 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001555 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001556 };
1557}
1558
1559/// Determine whether a type has new-extended alignment. This may be called when
1560/// the type is incomplete (for a delete-expression with an incomplete pointee
1561/// type), in which case it will conservatively return false if the alignment is
1562/// not known.
1563static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1564 return S.getLangOpts().AlignedAllocation &&
1565 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1566 S.getASTContext().getTargetInfo().getNewAlign();
1567}
1568
1569/// Select the correct "usual" deallocation function to use from a selection of
1570/// deallocation functions (either global or class-scope).
1571static UsualDeallocFnInfo resolveDeallocationOverload(
1572 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1573 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1574 UsualDeallocFnInfo Best;
1575
Richard Smithb2f0f052016-10-10 18:54:32 +00001576 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001577 UsualDeallocFnInfo Info(S, I.getPair());
1578 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1579 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001580 continue;
1581
1582 if (!Best) {
1583 Best = Info;
1584 if (BestFns)
1585 BestFns->push_back(Info);
1586 continue;
1587 }
1588
Richard Smithf75dcbe2016-10-11 00:21:10 +00001589 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001590 continue;
1591
1592 // If more than one preferred function is found, all non-preferred
1593 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001594 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001595 BestFns->clear();
1596
1597 Best = Info;
1598 if (BestFns)
1599 BestFns->push_back(Info);
1600 }
1601
1602 return Best;
1603}
1604
1605/// Determine whether a given type is a class for which 'delete[]' would call
1606/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1607/// we need to store the array size (even if the type is
1608/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001609static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1610 QualType allocType) {
1611 const RecordType *record =
1612 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1613 if (!record) return false;
1614
1615 // Try to find an operator delete[] in class scope.
1616
1617 DeclarationName deleteName =
1618 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1619 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1620 S.LookupQualifiedName(ops, record->getDecl());
1621
1622 // We're just doing this for information.
1623 ops.suppressDiagnostics();
1624
1625 // Very likely: there's no operator delete[].
1626 if (ops.empty()) return false;
1627
1628 // If it's ambiguous, it should be illegal to call operator delete[]
1629 // on this thing, so it doesn't matter if we allocate extra space or not.
1630 if (ops.isAmbiguous()) return false;
1631
Richard Smithb2f0f052016-10-10 18:54:32 +00001632 // C++17 [expr.delete]p10:
1633 // If the deallocation functions have class scope, the one without a
1634 // parameter of type std::size_t is selected.
1635 auto Best = resolveDeallocationOverload(
1636 S, ops, /*WantSize*/false,
1637 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1638 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001639}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001641/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001642///
Sebastian Redld74dd492012-02-12 18:41:05 +00001643/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001644/// @code new (memory) int[size][4] @endcode
1645/// or
1646/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001647///
1648/// \param StartLoc The first location of the expression.
1649/// \param UseGlobal True if 'new' was prefixed with '::'.
1650/// \param PlacementLParen Opening paren of the placement arguments.
1651/// \param PlacementArgs Placement new arguments.
1652/// \param PlacementRParen Closing paren of the placement arguments.
1653/// \param TypeIdParens If the type is in parens, the source range.
1654/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001655/// \param Initializer The initializing expression or initializer-list, or null
1656/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001657ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001658Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001659 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001661 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001662 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001663 // If the specified type is an array, unwrap it and save the expression.
1664 if (D.getNumTypeObjects() > 0 &&
1665 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001666 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001667 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001668 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1669 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001670 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001671 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1672 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001673 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001674 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1675 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001676
Sebastian Redl351bb782008-12-02 14:43:59 +00001677 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001678 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001679 }
1680
Douglas Gregor73341c42009-09-11 00:18:58 +00001681 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001682 if (ArraySize) {
1683 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001684 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1685 break;
1686
1687 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1688 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001689 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001690 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001691 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1692 // shall be a converted constant expression (5.19) of type std::size_t
1693 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001694 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1695 assert(IntWidth && "Builtin type of size 0?");
1696 llvm::APSInt Value(IntWidth);
1697 Array.NumElts
1698 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1699 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001700 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001701 } else {
1702 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001703 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001704 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001705 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001706 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001707 if (!Array.NumElts)
1708 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001709 }
1710 }
1711 }
1712 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001713
Craig Topperc3ec1492014-05-26 06:22:03 +00001714 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001715 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001716 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001717 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718
Sebastian Redl6047f072012-02-16 12:22:20 +00001719 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001720 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001721 DirectInitRange = List->getSourceRange();
1722
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001723 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1724 PlacementLParen, PlacementArgs, PlacementRParen,
1725 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001726 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001727}
1728
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001729static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1730 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001731 if (!Init)
1732 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001733 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1734 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001735 if (isa<ImplicitValueInitExpr>(Init))
1736 return true;
1737 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1738 return !CCE->isListInitialization() &&
1739 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001740 else if (Style == CXXNewExpr::ListInit) {
1741 assert(isa<InitListExpr>(Init) &&
1742 "Shouldn't create list CXXConstructExprs for arrays.");
1743 return true;
1744 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001745 return false;
1746}
1747
Akira Hatanakacae83f72017-06-29 18:48:40 +00001748// Emit a diagnostic if an aligned allocation/deallocation function that is not
1749// implemented in the standard library is selected.
1750static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1751 SourceLocation Loc, bool IsDelete,
1752 Sema &S) {
1753 if (!S.getLangOpts().AlignedAllocationUnavailable)
1754 return;
1755
1756 // Return if there is a definition.
1757 if (FD.isDefined())
1758 return;
1759
1760 bool IsAligned = false;
1761 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001762 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1763 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1764 S.getASTContext().getTargetInfo().getPlatformName());
1765
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001766 S.Diag(Loc, diag::err_aligned_allocation_unavailable)
1767 << IsDelete << FD.getType().getAsString() << OSName
1768 << alignedAllocMinVersion(T.getOS()).getAsString();
Louis Dionne751381d2018-08-21 15:54:24 +00001769 S.Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001770 }
1771}
1772
John McCalldadc5752010-08-24 06:29:42 +00001773ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001774Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001775 SourceLocation PlacementLParen,
1776 MultiExprArg PlacementArgs,
1777 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001778 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001779 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001780 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001781 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001782 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001783 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001784 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001785 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001786
Sebastian Redl6047f072012-02-16 12:22:20 +00001787 CXXNewExpr::InitializationStyle initStyle;
1788 if (DirectInitRange.isValid()) {
1789 assert(Initializer && "Have parens but no initializer.");
1790 initStyle = CXXNewExpr::CallInit;
1791 } else if (Initializer && isa<InitListExpr>(Initializer))
1792 initStyle = CXXNewExpr::ListInit;
1793 else {
1794 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1795 isa<CXXConstructExpr>(Initializer)) &&
1796 "Initializer expression that cannot have been implicitly created.");
1797 initStyle = CXXNewExpr::NoInit;
1798 }
1799
1800 Expr **Inits = &Initializer;
1801 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001802 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1803 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1804 Inits = List->getExprs();
1805 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001806 }
1807
Richard Smith60437622017-02-09 19:17:44 +00001808 // C++11 [expr.new]p15:
1809 // A new-expression that creates an object of type T initializes that
1810 // object as follows:
1811 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001812 // - If the new-initializer is omitted, the object is default-
1813 // initialized (8.5); if no initialization is performed,
1814 // the object has indeterminate value
1815 = initStyle == CXXNewExpr::NoInit
1816 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1817 // - Otherwise, the new-initializer is interpreted according to
1818 // the
1819 // initialization rules of 8.5 for direct-initialization.
1820 : initStyle == CXXNewExpr::ListInit
1821 ? InitializationKind::CreateDirectList(
1822 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001823 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001824 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1825 DirectInitRange.getBegin(),
1826 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001827
Richard Smith60437622017-02-09 19:17:44 +00001828 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1829 auto *Deduced = AllocType->getContainedDeducedType();
1830 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1831 if (ArraySize)
1832 return ExprError(Diag(ArraySize->getExprLoc(),
1833 diag::err_deduced_class_template_compound_type)
1834 << /*array*/ 2 << ArraySize->getSourceRange());
1835
1836 InitializedEntity Entity
1837 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1838 AllocType = DeduceTemplateSpecializationFromInitializer(
1839 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1840 if (AllocType.isNull())
1841 return ExprError();
1842 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001843 bool Braced = (initStyle == CXXNewExpr::ListInit);
1844 if (NumInits == 1) {
1845 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1846 Inits = p->getInits();
1847 NumInits = p->getNumInits();
1848 Braced = true;
1849 }
1850 }
1851
Sebastian Redl6047f072012-02-16 12:22:20 +00001852 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001853 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1854 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001855 if (NumInits > 1) {
1856 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001857 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001858 diag::err_auto_new_ctor_multiple_expressions)
1859 << AllocType << TypeRange);
1860 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001861 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001862 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001863 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001864 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001865 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001866 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001867 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001868 << AllocType << Deduce->getType()
1869 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001870 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001871 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001872 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001873 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001874
Douglas Gregorcda95f42010-05-16 16:01:03 +00001875 // Per C++0x [expr.new]p5, the type being constructed may be a
1876 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001877 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001878 if (const ConstantArrayType *Array
1879 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001880 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1881 Context.getSizeType(),
1882 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001883 AllocType = Array->getElementType();
1884 }
1885 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001886
Douglas Gregor3999e152010-10-06 16:00:31 +00001887 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1888 return ExprError();
1889
Simon Pilgrim75c26882016-09-30 14:25:09 +00001890 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001892 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1893 AllocType->isObjCLifetimeType()) {
1894 AllocType = Context.getLifetimeQualifiedType(AllocType,
1895 AllocType->getObjCARCImplicitLifetime());
1896 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001897
John McCall31168b02011-06-15 23:02:42 +00001898 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001899
John McCall5e77d762013-04-16 07:28:30 +00001900 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1901 ExprResult result = CheckPlaceholderExpr(ArraySize);
1902 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001903 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001904 }
Richard Smith8dd34252012-02-04 07:07:42 +00001905 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1906 // integral or enumeration type with a non-negative value."
1907 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1908 // enumeration type, or a class type for which a single non-explicit
1909 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001910 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001911 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001912 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001913 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001914 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001915 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001916 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1917
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001918 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001919 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001920
Simon Pilgrim75c26882016-09-30 14:25:09 +00001921 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001922 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001923 // Diagnose the compatibility of this conversion.
1924 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1925 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001926 } else {
1927 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1928 protected:
1929 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001930
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001931 public:
1932 SizeConvertDiagnoser(Expr *ArraySize)
1933 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1934 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001935
1936 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1937 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001938 return S.Diag(Loc, diag::err_array_size_not_integral)
1939 << S.getLangOpts().CPlusPlus11 << T;
1940 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001941
1942 SemaDiagnosticBuilder diagnoseIncomplete(
1943 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001944 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1945 << T << ArraySize->getSourceRange();
1946 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001947
1948 SemaDiagnosticBuilder diagnoseExplicitConv(
1949 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001950 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1951 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001952
1953 SemaDiagnosticBuilder noteExplicitConv(
1954 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001955 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1956 << ConvTy->isEnumeralType() << ConvTy;
1957 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001958
1959 SemaDiagnosticBuilder diagnoseAmbiguous(
1960 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001961 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1962 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001963
1964 SemaDiagnosticBuilder noteAmbiguous(
1965 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001966 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967 << ConvTy->isEnumeralType() << ConvTy;
1968 }
Richard Smithccc11812013-05-21 19:05:48 +00001969
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001970 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1971 QualType T,
1972 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001973 return S.Diag(Loc,
1974 S.getLangOpts().CPlusPlus11
1975 ? diag::warn_cxx98_compat_array_size_conversion
1976 : diag::ext_array_size_conversion)
1977 << T << ConvTy->isEnumeralType() << ConvTy;
1978 }
1979 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001980
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001981 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1982 SizeDiagnoser);
1983 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001984 if (ConvertedSize.isInvalid())
1985 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001987 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001988 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001989
Douglas Gregor0bf31402010-10-08 23:50:27 +00001990 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001991 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001993 // C++98 [expr.new]p7:
1994 // The expression in a direct-new-declarator shall have integral type
1995 // with a non-negative value.
1996 //
Richard Smith0511d232016-10-05 22:41:02 +00001997 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1998 // per CWG1464. Otherwise, if it's not a constant, we must have an
1999 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002000 if (!ArraySize->isValueDependent()) {
2001 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002002 // We've already performed any required implicit conversion to integer or
2003 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002004 // FIXME: Per CWG1464, we are required to check the value prior to
2005 // converting to size_t. This will never find a negative array size in
2006 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002007 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002008 if (Value.isSigned() && Value.isNegative()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002009 return ExprError(Diag(ArraySize->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002010 diag::err_typecheck_negative_array_size)
2011 << ArraySize->getSourceRange());
2012 }
2013
2014 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002015 unsigned ActiveSizeBits =
2016 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002017 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002018 return ExprError(
2019 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2020 << Value.toString(10) << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002021 }
Richard Smith0511d232016-10-05 22:41:02 +00002022
2023 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002024 } else if (TypeIdParens.isValid()) {
2025 // Can't have dynamic array size when the type-id is in parentheses.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002026 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2027 << ArraySize->getSourceRange()
2028 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2029 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
Douglas Gregorf2753b32010-07-13 15:54:32 +00002031 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002032 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
John McCall036f2f62011-05-15 07:14:44 +00002035 // Note that we do *not* convert the argument in any way. It can
2036 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002037 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002038
Craig Topperc3ec1492014-05-26 06:22:03 +00002039 FunctionDecl *OperatorNew = nullptr;
2040 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002041 unsigned Alignment =
2042 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2043 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2044 bool PassAlignment = getLangOpts().AlignedAllocation &&
2045 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Brian Gesiakcb024022018-04-01 22:59:22 +00002047 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002048 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002049 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002050 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002051 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002052 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002053 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002054 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002055
2056 // If this is an array allocation, compute whether the usual array
2057 // deallocation function for the type has a size_t parameter.
2058 bool UsualArrayDeleteWantsSize = false;
2059 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002060 UsualArrayDeleteWantsSize =
2061 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002062
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002063 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002064 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002066 OperatorNew->getType()->getAs<FunctionProtoType>();
2067 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2068 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Richard Smithd6f9e732014-05-13 19:56:21 +00002070 // We've already converted the placement args, just fill in any default
2071 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002072 // argument. Skip the second parameter too if we're passing in the
2073 // alignment; we've already filled it in.
2074 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2075 PassAlignment ? 2 : 1, PlacementArgs,
2076 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002077 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002079 if (!AllPlaceArgs.empty())
2080 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002081
Richard Smithd6f9e732014-05-13 19:56:21 +00002082 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002083 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002084
2085 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Richard Smithb2f0f052016-10-10 18:54:32 +00002087 // Warn if the type is over-aligned and is being allocated by (unaligned)
2088 // global operator new.
2089 if (PlacementArgs.empty() && !PassAlignment &&
2090 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002091 (OperatorNew->getBeginLoc().isValid() &&
2092 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002093 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002094 Diag(StartLoc, diag::warn_overaligned_type)
2095 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002096 << unsigned(Alignment / Context.getCharWidth())
2097 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002098 }
2099 }
2100
Sebastian Redl6047f072012-02-16 12:22:20 +00002101 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002102 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2103 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002104 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002105 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002106 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002107 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2108 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002109 }
2110
Richard Smithdd2ca572012-11-26 08:32:48 +00002111 // If we can perform the initialization, and we've not already done so,
2112 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002113 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002114 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002115 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002116 // The type we initialize is the complete type, including the array bound.
2117 QualType InitType;
2118 if (KnownArraySize)
2119 InitType = Context.getConstantArrayType(
2120 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2121 *KnownArraySize),
2122 ArrayType::Normal, 0);
2123 else if (ArraySize)
2124 InitType =
2125 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2126 else
2127 InitType = AllocType;
2128
Douglas Gregor85dabae2009-12-16 01:38:02 +00002129 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002130 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002131 InitializationSequence InitSeq(*this, Entity, Kind,
2132 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002134 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002135 if (FullInit.isInvalid())
2136 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
Sebastian Redl6047f072012-02-16 12:22:20 +00002138 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2139 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002140 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002141 if (CXXBindTemporaryExpr *Binder =
2142 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002143 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002145 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
Douglas Gregor6642ca22010-02-26 05:06:18 +00002148 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002149 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002150 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2151 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002152 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002153 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002154 }
2155 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002156 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2157 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002158 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002159 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002160 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002161
John McCall928a2572011-07-13 20:12:57 +00002162 // C++0x [expr.new]p17:
2163 // If the new expression creates an array of objects of class type,
2164 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002165 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2166 if (ArraySize && !BaseAllocType->isDependentType()) {
2167 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2168 if (CXXDestructorDecl *dtor = LookupDestructor(
2169 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2170 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002171 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002172 PDiag(diag::err_access_dtor)
2173 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002174 if (DiagnoseUseOfDecl(dtor, StartLoc))
2175 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002176 }
John McCall928a2572011-07-13 20:12:57 +00002177 }
2178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002180 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002181 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002182 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2183 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2184 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002185}
2186
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002187/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002188/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002189bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002190 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002191 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2192 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002193 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002194 return Diag(Loc, diag::err_bad_new_type)
2195 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002196 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002197 return Diag(Loc, diag::err_bad_new_type)
2198 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002199 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002200 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002201 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002202 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002203 diag::err_allocation_of_abstract_type))
2204 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002205 else if (AllocType->isVariablyModifiedType())
2206 return Diag(Loc, diag::err_variably_modified_new_type)
2207 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002208 else if (AllocType.getAddressSpace() != LangAS::Default &&
2209 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002210 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002211 << AllocType.getUnqualifiedType()
2212 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002213 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002214 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2215 QualType BaseAllocType = Context.getBaseElementType(AT);
2216 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2217 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002218 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002219 << BaseAllocType;
2220 }
2221 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002222
Sebastian Redlbd150f42008-11-21 19:14:01 +00002223 return false;
2224}
2225
Brian Gesiak87412d92018-02-15 20:09:25 +00002226static bool resolveAllocationOverload(
2227 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2228 bool &PassAlignment, FunctionDecl *&Operator,
2229 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002230 OverloadCandidateSet Candidates(R.getNameLoc(),
2231 OverloadCandidateSet::CSK_Normal);
2232 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2233 Alloc != AllocEnd; ++Alloc) {
2234 // Even member operator new/delete are implicitly treated as
2235 // static, so don't use AddMemberCandidate.
2236 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2237
2238 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2239 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2240 /*ExplicitTemplateArgs=*/nullptr, Args,
2241 Candidates,
2242 /*SuppressUserConversions=*/false);
2243 continue;
2244 }
2245
2246 FunctionDecl *Fn = cast<FunctionDecl>(D);
2247 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2248 /*SuppressUserConversions=*/false);
2249 }
2250
2251 // Do the resolution.
2252 OverloadCandidateSet::iterator Best;
2253 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2254 case OR_Success: {
2255 // Got one!
2256 FunctionDecl *FnDecl = Best->Function;
2257 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2258 Best->FoundDecl) == Sema::AR_inaccessible)
2259 return true;
2260
2261 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002262 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002263 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002264
Richard Smithb2f0f052016-10-10 18:54:32 +00002265 case OR_No_Viable_Function:
2266 // C++17 [expr.new]p13:
2267 // If no matching function is found and the allocated object type has
2268 // new-extended alignment, the alignment argument is removed from the
2269 // argument list, and overload resolution is performed again.
2270 if (PassAlignment) {
2271 PassAlignment = false;
2272 AlignArg = Args[1];
2273 Args.erase(Args.begin() + 1);
2274 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002275 Operator, &Candidates, AlignArg,
2276 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002277 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002278
Richard Smithb2f0f052016-10-10 18:54:32 +00002279 // MSVC will fall back on trying to find a matching global operator new
2280 // if operator new[] cannot be found. Also, MSVC will leak by not
2281 // generating a call to operator delete or operator delete[], but we
2282 // will not replicate that bug.
2283 // FIXME: Find out how this interacts with the std::align_val_t fallback
2284 // once MSVC implements it.
2285 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2286 S.Context.getLangOpts().MSVCCompat) {
2287 R.clear();
2288 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2289 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2290 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2291 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002292 Operator, /*Candidates=*/nullptr,
2293 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002294 }
Richard Smith1cdec012013-09-29 04:40:38 +00002295
Brian Gesiak87412d92018-02-15 20:09:25 +00002296 if (Diagnose) {
2297 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2298 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002299
Brian Gesiak87412d92018-02-15 20:09:25 +00002300 // If we have aligned candidates, only note the align_val_t candidates
2301 // from AlignedCandidates and the non-align_val_t candidates from
2302 // Candidates.
2303 if (AlignedCandidates) {
2304 auto IsAligned = [](OverloadCandidate &C) {
2305 return C.Function->getNumParams() > 1 &&
2306 C.Function->getParamDecl(1)->getType()->isAlignValT();
2307 };
2308 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002309
Brian Gesiak87412d92018-02-15 20:09:25 +00002310 // This was an overaligned allocation, so list the aligned candidates
2311 // first.
2312 Args.insert(Args.begin() + 1, AlignArg);
2313 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2314 R.getNameLoc(), IsAligned);
2315 Args.erase(Args.begin() + 1);
2316 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2317 IsUnaligned);
2318 } else {
2319 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2320 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002321 }
Richard Smith1cdec012013-09-29 04:40:38 +00002322 return true;
2323
Richard Smithb2f0f052016-10-10 18:54:32 +00002324 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002325 if (Diagnose) {
2326 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2327 << R.getLookupName() << Range;
2328 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2329 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002330 return true;
2331
2332 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002333 if (Diagnose) {
2334 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2335 << Best->Function->isDeleted() << R.getLookupName()
2336 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2337 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2338 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002339 return true;
2340 }
2341 }
2342 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002343}
2344
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002345bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002346 AllocationFunctionScope NewScope,
2347 AllocationFunctionScope DeleteScope,
2348 QualType AllocType, bool IsArray,
2349 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002350 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002351 FunctionDecl *&OperatorDelete,
2352 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002353 // --- Choosing an allocation function ---
2354 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002355 // 1) If looking in AFS_Global scope for allocation functions, only look in
2356 // the global scope. Else, if AFS_Class, only look in the scope of the
2357 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002358 // 2) If an array size is given, look for operator new[], else look for
2359 // operator new.
2360 // 3) The first argument is always size_t. Append the arguments from the
2361 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002362
Richard Smithb2f0f052016-10-10 18:54:32 +00002363 SmallVector<Expr*, 8> AllocArgs;
2364 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2365
2366 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002367 // FIXME: Should the Sema create the expression and embed it in the syntax
2368 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002369 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002370 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002371 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002372 Context.getSizeType(),
2373 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002374 AllocArgs.push_back(&Size);
2375
2376 QualType AlignValT = Context.VoidTy;
2377 if (PassAlignment) {
2378 DeclareGlobalNewDelete();
2379 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2380 }
2381 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2382 if (PassAlignment)
2383 AllocArgs.push_back(&Align);
2384
2385 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002386
Douglas Gregor6642ca22010-02-26 05:06:18 +00002387 // C++ [expr.new]p8:
2388 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002389 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002390 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002391 // type, the allocation function's name is operator new[] and the
2392 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002393 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002394 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002395
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002396 QualType AllocElemType = Context.getBaseElementType(AllocType);
2397
Richard Smithb2f0f052016-10-10 18:54:32 +00002398 // Find the allocation function.
2399 {
2400 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2401
2402 // C++1z [expr.new]p9:
2403 // If the new-expression begins with a unary :: operator, the allocation
2404 // function's name is looked up in the global scope. Otherwise, if the
2405 // allocated type is a class type T or array thereof, the allocation
2406 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002407 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002408 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2409
2410 // We can see ambiguity here if the allocation function is found in
2411 // multiple base classes.
2412 if (R.isAmbiguous())
2413 return true;
2414
2415 // If this lookup fails to find the name, or if the allocated type is not
2416 // a class type, the allocation function's name is looked up in the
2417 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002418 if (R.empty()) {
2419 if (NewScope == AFS_Class)
2420 return true;
2421
Richard Smithb2f0f052016-10-10 18:54:32 +00002422 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002423 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002424
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002425 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2426 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2427 return true;
2428 }
2429
Richard Smithb2f0f052016-10-10 18:54:32 +00002430 assert(!R.empty() && "implicitly declared allocation functions not found");
2431 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2432
2433 // We do our own custom access checks below.
2434 R.suppressDiagnostics();
2435
2436 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002437 OperatorNew, /*Candidates=*/nullptr,
2438 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002439 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002440 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002441
Richard Smithb2f0f052016-10-10 18:54:32 +00002442 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002444 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002445 return false;
2446 }
2447
Richard Smithb2f0f052016-10-10 18:54:32 +00002448 // Note, the name of OperatorNew might have been changed from array to
2449 // non-array by resolveAllocationOverload.
2450 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2451 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2452 ? OO_Array_Delete
2453 : OO_Delete);
2454
Douglas Gregor6642ca22010-02-26 05:06:18 +00002455 // C++ [expr.new]p19:
2456 //
2457 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002458 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002459 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002460 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002461 // the scope of T. If this lookup fails to find the name, or if
2462 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002463 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002464 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002465 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002466 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002467 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002468 LookupQualifiedName(FoundDelete, RD);
2469 }
John McCallfb6f5262010-03-18 08:19:33 +00002470 if (FoundDelete.isAmbiguous())
2471 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002472
Richard Smithb2f0f052016-10-10 18:54:32 +00002473 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002474 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002475 if (DeleteScope == AFS_Class)
2476 return true;
2477
Douglas Gregor6642ca22010-02-26 05:06:18 +00002478 DeclareGlobalNewDelete();
2479 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2480 }
2481
2482 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002483
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002484 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002485
John McCalld3be2c82010-09-14 21:34:24 +00002486 // Whether we're looking for a placement operator delete is dictated
2487 // by whether we selected a placement operator new, not by whether
2488 // we had explicit placement arguments. This matters for things like
2489 // struct A { void *operator new(size_t, int = 0); ... };
2490 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002491 //
2492 // We don't have any definition for what a "placement allocation function"
2493 // is, but we assume it's any allocation function whose
2494 // parameter-declaration-clause is anything other than (size_t).
2495 //
2496 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2497 // This affects whether an exception from the constructor of an overaligned
2498 // type uses the sized or non-sized form of aligned operator delete.
2499 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2500 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002501
2502 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002503 // C++ [expr.new]p20:
2504 // A declaration of a placement deallocation function matches the
2505 // declaration of a placement allocation function if it has the
2506 // same number of parameters and, after parameter transformations
2507 // (8.3.5), all parameter types except the first are
2508 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002509 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002510 // To perform this comparison, we compute the function type that
2511 // the deallocation function should have, and use that type both
2512 // for template argument deduction and for comparison purposes.
2513 QualType ExpectedFunctionType;
2514 {
2515 const FunctionProtoType *Proto
2516 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002517
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002518 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002519 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002520 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2521 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002522
John McCalldb40c7f2010-12-14 08:05:40 +00002523 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002524 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002525 EPI.Variadic = Proto->isVariadic();
2526
Douglas Gregor6642ca22010-02-26 05:06:18 +00002527 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002528 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002529 }
2530
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002532 DEnd = FoundDelete.end();
2533 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002534 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002535 if (FunctionTemplateDecl *FnTmpl =
2536 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002537 // Perform template argument deduction to try to match the
2538 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002539 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002540 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2541 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002542 continue;
2543 } else
2544 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2545
Richard Smithbaa47832016-12-01 02:11:49 +00002546 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2547 ExpectedFunctionType,
2548 /*AdjustExcpetionSpec*/true),
2549 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002550 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002551 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002552
Richard Smithb2f0f052016-10-10 18:54:32 +00002553 if (getLangOpts().CUDA)
2554 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2555 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002556 // C++1y [expr.new]p22:
2557 // For a non-placement allocation function, the normal deallocation
2558 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002559 //
2560 // Per [expr.delete]p10, this lookup prefers a member operator delete
2561 // without a size_t argument, but prefers a non-member operator delete
2562 // with a size_t where possible (which it always is in this case).
2563 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2564 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2565 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2566 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2567 &BestDeallocFns);
2568 if (Selected)
2569 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2570 else {
2571 // If we failed to select an operator, all remaining functions are viable
2572 // but ambiguous.
2573 for (auto Fn : BestDeallocFns)
2574 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002575 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002576 }
2577
2578 // C++ [expr.new]p20:
2579 // [...] If the lookup finds a single matching deallocation
2580 // function, that function will be called; otherwise, no
2581 // deallocation function will be called.
2582 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002583 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002584
Richard Smithb2f0f052016-10-10 18:54:32 +00002585 // C++1z [expr.new]p23:
2586 // If the lookup finds a usual deallocation function (3.7.4.2)
2587 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002588 // as a placement deallocation function, would have been
2589 // selected as a match for the allocation function, the program
2590 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002591 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002592 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002593 UsualDeallocFnInfo Info(*this,
2594 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002595 // Core issue, per mail to core reflector, 2016-10-09:
2596 // If this is a member operator delete, and there is a corresponding
2597 // non-sized member operator delete, this isn't /really/ a sized
2598 // deallocation function, it just happens to have a size_t parameter.
2599 bool IsSizedDelete = Info.HasSizeT;
2600 if (IsSizedDelete && !FoundGlobalDelete) {
2601 auto NonSizedDelete =
2602 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2603 /*WantAlign*/Info.HasAlignValT);
2604 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2605 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2606 IsSizedDelete = false;
2607 }
2608
2609 if (IsSizedDelete) {
2610 SourceRange R = PlaceArgs.empty()
2611 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002612 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002613 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002614 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2615 if (!OperatorDelete->isImplicit())
2616 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2617 << DeleteName;
2618 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002619 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002620
2621 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2622 Matches[0].first);
2623 } else if (!Matches.empty()) {
2624 // We found multiple suitable operators. Per [expr.new]p20, that means we
2625 // call no 'operator delete' function, but we should at least warn the user.
2626 // FIXME: Suppress this warning if the construction cannot throw.
2627 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2628 << DeleteName << AllocElemType;
2629
2630 for (auto &Match : Matches)
2631 Diag(Match.second->getLocation(),
2632 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002633 }
2634
Sebastian Redlfaf68082008-12-03 20:26:15 +00002635 return false;
2636}
2637
2638/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2639/// delete. These are:
2640/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002641/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002642/// void* operator new(std::size_t) throw(std::bad_alloc);
2643/// void* operator new[](std::size_t) throw(std::bad_alloc);
2644/// void operator delete(void *) throw();
2645/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002646/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002647/// void* operator new(std::size_t);
2648/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002649/// void operator delete(void *) noexcept;
2650/// void operator delete[](void *) noexcept;
2651/// // C++1y:
2652/// void* operator new(std::size_t);
2653/// void* operator new[](std::size_t);
2654/// void operator delete(void *) noexcept;
2655/// void operator delete[](void *) noexcept;
2656/// void operator delete(void *, std::size_t) noexcept;
2657/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002658/// @endcode
2659/// Note that the placement and nothrow forms of new are *not* implicitly
2660/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002661void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002662 if (GlobalNewDeleteDeclared)
2663 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002665 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2666 // are not supported.
2667 if (getLangOpts().OpenCLCPlusPlus)
2668 return;
2669
Douglas Gregor87f54062009-09-15 22:30:29 +00002670 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 // [...] The following allocation and deallocation functions (18.4) are
2672 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002673 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002674 //
Sebastian Redl37588092011-03-14 18:08:30 +00002675 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002676 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 // void* operator new[](std::size_t) throw(std::bad_alloc);
2678 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002679 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002680 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002681 // void* operator new(std::size_t);
2682 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002683 // void operator delete(void*) noexcept;
2684 // void operator delete[](void*) noexcept;
2685 // C++1y:
2686 // void* operator new(std::size_t);
2687 // void* operator new[](std::size_t);
2688 // void operator delete(void*) noexcept;
2689 // void operator delete[](void*) noexcept;
2690 // void operator delete(void*, std::size_t) noexcept;
2691 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002692 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002694 // new, operator new[], operator delete, operator delete[].
2695 //
2696 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2697 // "std" or "bad_alloc" as necessary to form the exception specification.
2698 // However, we do not make these implicit declarations visible to name
2699 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002700 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002701 // The "std::bad_alloc" class has not yet been declared, so build it
2702 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2704 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002705 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002707 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002708 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002709 }
Richard Smith59139022016-09-30 22:41:36 +00002710 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002711 // The "std::align_val_t" enum class has not yet been declared, so build it
2712 // implicitly.
2713 auto *AlignValT = EnumDecl::Create(
2714 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2715 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2716 AlignValT->setIntegerType(Context.getSizeType());
2717 AlignValT->setPromotionType(Context.getSizeType());
2718 AlignValT->setImplicit(true);
2719 StdAlignValT = AlignValT;
2720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
Sebastian Redlfaf68082008-12-03 20:26:15 +00002722 GlobalNewDeleteDeclared = true;
2723
2724 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2725 QualType SizeT = Context.getSizeType();
2726
Richard Smith96269c52016-09-29 22:49:46 +00002727 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2728 QualType Return, QualType Param) {
2729 llvm::SmallVector<QualType, 3> Params;
2730 Params.push_back(Param);
2731
2732 // Create up to four variants of the function (sized/aligned).
2733 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2734 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002735 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002736
2737 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2738 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2739 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002740 if (Sized)
2741 Params.push_back(SizeT);
2742
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002743 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002744 if (Aligned)
2745 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2746
2747 DeclareGlobalAllocationFunction(
2748 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2749
2750 if (Aligned)
2751 Params.pop_back();
2752 }
2753 }
2754 };
2755
2756 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2757 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2758 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2759 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002760}
2761
2762/// DeclareGlobalAllocationFunction - Declares a single implicit global
2763/// allocation function if it doesn't already exist.
2764void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002765 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002766 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002767 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2768
2769 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002770 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2771 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2772 Alloc != AllocEnd; ++Alloc) {
2773 // Only look at non-template functions, as it is the predefined,
2774 // non-templated allocation function we are trying to declare here.
2775 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002776 if (Func->getNumParams() == Params.size()) {
2777 llvm::SmallVector<QualType, 3> FuncParams;
2778 for (auto *P : Func->parameters())
2779 FuncParams.push_back(
2780 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2781 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002782 // Make the function visible to name lookup, even if we found it in
2783 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002784 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002785 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002786 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002787 }
Chandler Carruth93538422010-02-03 11:02:14 +00002788 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002789 }
2790 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002791
Richard Smithc015bc22014-02-07 22:39:53 +00002792 FunctionProtoType::ExtProtoInfo EPI;
2793
Richard Smithf8b417c2014-02-08 00:42:45 +00002794 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002796 = (Name.getCXXOverloadedOperator() == OO_New ||
2797 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002798 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002799 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002800 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002801 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002802 EPI.ExceptionSpec.Type = EST_Dynamic;
2803 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002804 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002805 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002806 EPI.ExceptionSpec =
2807 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Artem Belevich07db5cf2016-10-21 20:34:05 +00002810 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2811 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2812 FunctionDecl *Alloc = FunctionDecl::Create(
2813 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2814 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2815 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002816 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002817 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002818
Artem Belevich07db5cf2016-10-21 20:34:05 +00002819 // Implicit sized deallocation functions always have default visibility.
2820 Alloc->addAttr(
2821 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Artem Belevich07db5cf2016-10-21 20:34:05 +00002823 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2824 for (QualType T : Params) {
2825 ParamDecls.push_back(ParmVarDecl::Create(
2826 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2827 /*TInfo=*/nullptr, SC_None, nullptr));
2828 ParamDecls.back()->setImplicit();
2829 }
2830 Alloc->setParams(ParamDecls);
2831 if (ExtraAttr)
2832 Alloc->addAttr(ExtraAttr);
2833 Context.getTranslationUnitDecl()->addDecl(Alloc);
2834 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2835 };
2836
2837 if (!LangOpts.CUDA)
2838 CreateAllocationFunctionDecl(nullptr);
2839 else {
2840 // Host and device get their own declaration so each can be
2841 // defined or re-declared independently.
2842 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2843 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002844 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002845}
2846
Richard Smith1cdec012013-09-29 04:40:38 +00002847FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2848 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002849 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002850 DeclarationName Name) {
2851 DeclareGlobalNewDelete();
2852
2853 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2854 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2855
Richard Smithb2f0f052016-10-10 18:54:32 +00002856 // FIXME: It's possible for this to result in ambiguity, through a
2857 // user-declared variadic operator delete or the enable_if attribute. We
2858 // should probably not consider those cases to be usual deallocation
2859 // functions. But for now we just make an arbitrary choice in that case.
2860 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2861 Overaligned);
2862 assert(Result.FD && "operator delete missing from global scope?");
2863 return Result.FD;
2864}
Richard Smith1cdec012013-09-29 04:40:38 +00002865
Richard Smithb2f0f052016-10-10 18:54:32 +00002866FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2867 CXXRecordDecl *RD) {
2868 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002869
Richard Smithb2f0f052016-10-10 18:54:32 +00002870 FunctionDecl *OperatorDelete = nullptr;
2871 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2872 return nullptr;
2873 if (OperatorDelete)
2874 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002875
Richard Smithb2f0f052016-10-10 18:54:32 +00002876 // If there's no class-specific operator delete, look up the global
2877 // non-array delete.
2878 return FindUsualDeallocationFunction(
2879 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2880 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002881}
2882
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002883bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2884 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002885 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002886 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002887 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002888 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889
John McCall27b18f82009-11-17 02:14:36 +00002890 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002891 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002892
Chandler Carruthb6f99172010-06-28 00:30:51 +00002893 Found.suppressDiagnostics();
2894
Richard Smithb2f0f052016-10-10 18:54:32 +00002895 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002896
Richard Smithb2f0f052016-10-10 18:54:32 +00002897 // C++17 [expr.delete]p10:
2898 // If the deallocation functions have class scope, the one without a
2899 // parameter of type std::size_t is selected.
2900 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2901 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2902 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002903
Richard Smithb2f0f052016-10-10 18:54:32 +00002904 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002905 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002906 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002907
Richard Smithb2f0f052016-10-10 18:54:32 +00002908 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002909 if (Operator->isDeleted()) {
2910 if (Diagnose) {
2911 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002912 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002913 }
2914 return true;
2915 }
2916
Richard Smith921bd202012-02-26 09:11:52 +00002917 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002918 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002919 return true;
2920
John McCall66a87592010-08-04 00:31:26 +00002921 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002922 }
John McCall66a87592010-08-04 00:31:26 +00002923
Richard Smithb2f0f052016-10-10 18:54:32 +00002924 // We found multiple suitable operators; complain about the ambiguity.
2925 // FIXME: The standard doesn't say to do this; it appears that the intent
2926 // is that this should never happen.
2927 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002928 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002929 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2930 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002931 for (auto &Match : Matches)
2932 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002933 }
John McCall66a87592010-08-04 00:31:26 +00002934 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002935 }
2936
2937 // We did find operator delete/operator delete[] declarations, but
2938 // none of them were suitable.
2939 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002940 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002941 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2942 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
Richard Smithb2f0f052016-10-10 18:54:32 +00002944 for (NamedDecl *D : Found)
2945 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002946 diag::note_member_declared_here) << Name;
2947 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002948 return true;
2949 }
2950
Craig Topperc3ec1492014-05-26 06:22:03 +00002951 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002952 return false;
2953}
2954
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002955namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002956/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002957/// initializing deletee have the same array form.
2958class MismatchingNewDeleteDetector {
2959public:
2960 enum MismatchResult {
2961 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2962 NoMismatch,
2963 /// Indicates that variable is initialized with mismatching form of \a new.
2964 VarInitMismatches,
2965 /// Indicates that member is initialized with mismatching form of \a new.
2966 MemberInitMismatches,
2967 /// Indicates that 1 or more constructors' definitions could not been
2968 /// analyzed, and they will be checked again at the end of translation unit.
2969 AnalyzeLater
2970 };
2971
2972 /// \param EndOfTU True, if this is the final analysis at the end of
2973 /// translation unit. False, if this is the initial analysis at the point
2974 /// delete-expression was encountered.
2975 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002976 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002977 HasUndefinedConstructors(false) {}
2978
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002979 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002980 /// matching form of new-expression.
2981 ///
2982 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2983 /// point where delete-expression is encountered, then a warning will be
2984 /// issued immediately. If return value is \c AnalyzeLater at the point where
2985 /// delete-expression is seen, then member will be analyzed at the end of
2986 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2987 /// couldn't be analyzed. If at least one constructor initializes the member
2988 /// with matching type of new, the return value is \c NoMismatch.
2989 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002990 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002991 /// \param Field Class member to analyze.
2992 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2993 /// for deleting the \p Field.
2994 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002995 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002996 /// List of mismatching new-expressions used for initialization of the pointee
2997 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2998 /// Indicates whether delete-expression was in array form.
2999 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003000
3001private:
3002 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003003 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003004 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003005 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003006 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003007 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003008 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003009 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003010 /// \c new either by the member initializer or in-class initialization.
3011 ///
3012 /// If bodies of all constructors are not visible at the end of translation
3013 /// unit or at least one constructor initializes member with the matching
3014 /// form of \c new, mismatch cannot be proven, and this function will return
3015 /// \c NoMismatch.
3016 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003017 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003018 /// \c new.
3019 ///
3020 /// If variable is initialized with matching form of \c new or variable is not
3021 /// initialized with a \c new expression, this function will return true.
3022 /// If variable is initialized with mismatching form of \c new, returns false.
3023 /// \param D Variable to analyze.
3024 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003025 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003026 /// form of \c new.
3027 ///
3028 /// Returns true, if member is initialized with matching form of \c new in
3029 /// member initializer list. Returns false, if member is initialized with the
3030 /// matching form of \c new in this constructor's initializer or given
3031 /// constructor isn't defined at the point where delete-expression is seen, or
3032 /// member isn't initialized by the constructor.
3033 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003034 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003035 /// \c new in member initializer list.
3036 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3037 /// Checks whether member is initialized with mismatching form of \c new by
3038 /// in-class initializer.
3039 MismatchResult analyzeInClassInitializer();
3040};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003041}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003042
3043MismatchingNewDeleteDetector::MismatchResult
3044MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3045 NewExprs.clear();
3046 assert(DE && "Expected delete-expression");
3047 IsArrayForm = DE->isArrayForm();
3048 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3049 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3050 return analyzeMemberExpr(ME);
3051 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3052 if (!hasMatchingVarInit(D))
3053 return VarInitMismatches;
3054 }
3055 return NoMismatch;
3056}
3057
3058const CXXNewExpr *
3059MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3060 assert(E != nullptr && "Expected a valid initializer expression");
3061 E = E->IgnoreParenImpCasts();
3062 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3063 if (ILE->getNumInits() == 1)
3064 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3065 }
3066
3067 return dyn_cast_or_null<const CXXNewExpr>(E);
3068}
3069
3070bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3071 const CXXCtorInitializer *CI) {
3072 const CXXNewExpr *NE = nullptr;
3073 if (Field == CI->getMember() &&
3074 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3075 if (NE->isArray() == IsArrayForm)
3076 return true;
3077 else
3078 NewExprs.push_back(NE);
3079 }
3080 return false;
3081}
3082
3083bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3084 const CXXConstructorDecl *CD) {
3085 if (CD->isImplicit())
3086 return false;
3087 const FunctionDecl *Definition = CD;
3088 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3089 HasUndefinedConstructors = true;
3090 return EndOfTU;
3091 }
3092 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3093 if (hasMatchingNewInCtorInit(CI))
3094 return true;
3095 }
3096 return false;
3097}
3098
3099MismatchingNewDeleteDetector::MismatchResult
3100MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3101 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003102 const Expr *InitExpr = Field->getInClassInitializer();
3103 if (!InitExpr)
3104 return EndOfTU ? NoMismatch : AnalyzeLater;
3105 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003106 if (NE->isArray() != IsArrayForm) {
3107 NewExprs.push_back(NE);
3108 return MemberInitMismatches;
3109 }
3110 }
3111 return NoMismatch;
3112}
3113
3114MismatchingNewDeleteDetector::MismatchResult
3115MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3116 bool DeleteWasArrayForm) {
3117 assert(Field != nullptr && "Analysis requires a valid class member.");
3118 this->Field = Field;
3119 IsArrayForm = DeleteWasArrayForm;
3120 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3121 for (const auto *CD : RD->ctors()) {
3122 if (hasMatchingNewInCtor(CD))
3123 return NoMismatch;
3124 }
3125 if (HasUndefinedConstructors)
3126 return EndOfTU ? NoMismatch : AnalyzeLater;
3127 if (!NewExprs.empty())
3128 return MemberInitMismatches;
3129 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3130 : NoMismatch;
3131}
3132
3133MismatchingNewDeleteDetector::MismatchResult
3134MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3135 assert(ME != nullptr && "Expected a member expression");
3136 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3137 return analyzeField(F, IsArrayForm);
3138 return NoMismatch;
3139}
3140
3141bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3142 const CXXNewExpr *NE = nullptr;
3143 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3144 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3145 NE->isArray() != IsArrayForm) {
3146 NewExprs.push_back(NE);
3147 }
3148 }
3149 return NewExprs.empty();
3150}
3151
3152static void
3153DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3154 const MismatchingNewDeleteDetector &Detector) {
3155 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3156 FixItHint H;
3157 if (!Detector.IsArrayForm)
3158 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3159 else {
3160 SourceLocation RSquare = Lexer::findLocationAfterToken(
3161 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3162 SemaRef.getLangOpts(), true);
3163 if (RSquare.isValid())
3164 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3165 }
3166 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3167 << Detector.IsArrayForm << H;
3168
3169 for (const auto *NE : Detector.NewExprs)
3170 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3171 << Detector.IsArrayForm;
3172}
3173
3174void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3175 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3176 return;
3177 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3178 switch (Detector.analyzeDeleteExpr(DE)) {
3179 case MismatchingNewDeleteDetector::VarInitMismatches:
3180 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003181 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003182 break;
3183 }
3184 case MismatchingNewDeleteDetector::AnalyzeLater: {
3185 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003186 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003187 break;
3188 }
3189 case MismatchingNewDeleteDetector::NoMismatch:
3190 break;
3191 }
3192}
3193
3194void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3195 bool DeleteWasArrayForm) {
3196 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3197 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3198 case MismatchingNewDeleteDetector::VarInitMismatches:
3199 llvm_unreachable("This analysis should have been done for class members.");
3200 case MismatchingNewDeleteDetector::AnalyzeLater:
3201 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3202 "translation unit.");
3203 case MismatchingNewDeleteDetector::MemberInitMismatches:
3204 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3205 break;
3206 case MismatchingNewDeleteDetector::NoMismatch:
3207 break;
3208 }
3209}
3210
Sebastian Redlbd150f42008-11-21 19:14:01 +00003211/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3212/// @code ::delete ptr; @endcode
3213/// or
3214/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003215ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003216Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003217 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003218 // C++ [expr.delete]p1:
3219 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003220 // non-explicit conversion function to a pointer type. The result has type
3221 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003222 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003223 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3224
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003225 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003226 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003227 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003228 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003229
John Wiegley01296292011-04-08 18:41:53 +00003230 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003231 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003232 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003233 if (Ex.isInvalid())
3234 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003235
John Wiegley01296292011-04-08 18:41:53 +00003236 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003237
Richard Smithccc11812013-05-21 19:05:48 +00003238 class DeleteConverter : public ContextualImplicitConverter {
3239 public:
3240 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241
Craig Toppere14c0f82014-03-12 04:55:44 +00003242 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003243 // FIXME: If we have an operator T* and an operator void*, we must pick
3244 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003245 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003246 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003247 return true;
3248 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003249 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003250
Richard Smithccc11812013-05-21 19:05:48 +00003251 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003252 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003253 return S.Diag(Loc, diag::err_delete_operand) << T;
3254 }
3255
3256 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003257 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003258 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3259 }
3260
3261 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003262 QualType T,
3263 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003264 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3265 }
3266
3267 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003268 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003269 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3270 << ConvTy;
3271 }
3272
3273 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003274 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003275 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3276 }
3277
3278 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003279 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003280 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3281 << ConvTy;
3282 }
3283
3284 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003285 QualType T,
3286 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003287 llvm_unreachable("conversion functions are permitted");
3288 }
3289 } Converter;
3290
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003291 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003292 if (Ex.isInvalid())
3293 return ExprError();
3294 Type = Ex.get()->getType();
3295 if (!Converter.match(Type))
3296 // FIXME: PerformContextualImplicitConversion should return ExprError
3297 // itself in this case.
3298 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003299
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003300 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003301 QualType PointeeElem = Context.getBaseElementType(Pointee);
3302
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003303 if (Pointee.getAddressSpace() != LangAS::Default &&
3304 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003305 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003306 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003307 << Pointee.getUnqualifiedType()
3308 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003309
Craig Topperc3ec1492014-05-26 06:22:03 +00003310 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003311 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003313 // effectively bans deletion of "void*". However, most compilers support
3314 // this, so we treat it as a warning unless we're in a SFINAE context.
3315 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003316 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003317 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003318 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003319 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003320 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003321 // FIXME: This can result in errors if the definition was imported from a
3322 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003323 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003324 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003325 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3326 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3327 }
3328 }
3329
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003330 if (Pointee->isArrayType() && !ArrayForm) {
3331 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003332 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003333 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003334 ArrayForm = true;
3335 }
3336
Anders Carlssona471db02009-08-16 20:29:29 +00003337 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3338 ArrayForm ? OO_Array_Delete : OO_Delete);
3339
Eli Friedmanae4280f2011-07-26 22:25:31 +00003340 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003342 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3343 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003344 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
John McCall284c48f2011-01-27 09:37:56 +00003346 // If we're allocating an array of records, check whether the
3347 // usual operator delete[] has a size_t parameter.
3348 if (ArrayForm) {
3349 // If the user specifically asked to use the global allocator,
3350 // we'll need to do the lookup into the class.
3351 if (UseGlobal)
3352 UsualArrayDeleteWantsSize =
3353 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3354
3355 // Otherwise, the usual operator delete[] should be the
3356 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003357 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003358 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003359 UsualDeallocFnInfo(*this,
3360 DeclAccessPair::make(OperatorDelete, AS_public))
3361 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003362 }
3363
Richard Smitheec915d62012-02-18 04:13:32 +00003364 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003365 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003366 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003367 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003368 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3369 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003370 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003371
Nico Weber5a9259c2016-01-15 21:45:31 +00003372 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3373 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3374 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3375 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377
Richard Smithb2f0f052016-10-10 18:54:32 +00003378 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003379 if (getLangOpts().OpenCLCPlusPlus) {
3380 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3381 return ExprError();
3382 }
3383
Richard Smithb2f0f052016-10-10 18:54:32 +00003384 bool IsComplete = isCompleteType(StartLoc, Pointee);
3385 bool CanProvideSize =
3386 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3387 Pointee.isDestructedType());
3388 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3389
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003390 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003391 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3392 Overaligned, DeleteName);
3393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Eli Friedmanfa0df832012-02-02 03:46:19 +00003395 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003396
Richard Smith5b349582017-10-13 01:55:36 +00003397 // Check access and ambiguity of destructor if we're going to call it.
3398 // Note that this is required even for a virtual delete.
3399 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003400 if (PointeeRD) {
3401 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003402 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3403 PDiag(diag::err_access_dtor) << PointeeElem);
3404 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003405 }
3406 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003407
3408 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3409 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003410
3411 // Convert the operand to the type of the first parameter of operator
3412 // delete. This is only necessary if we selected a destroying operator
3413 // delete that we are going to call (non-virtually); converting to void*
3414 // is trivial and left to AST consumers to handle.
3415 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3416 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003417 Qualifiers Qs = Pointee.getQualifiers();
3418 if (Qs.hasCVRQualifiers()) {
3419 // Qualifiers are irrelevant to this conversion; we're only looking
3420 // for access and ambiguity.
3421 Qs.removeCVRQualifiers();
3422 QualType Unqual = Context.getPointerType(
3423 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3424 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3425 }
Richard Smith5b349582017-10-13 01:55:36 +00003426 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3427 if (Ex.isInvalid())
3428 return ExprError();
3429 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003430 }
3431
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003432 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003433 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3434 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003435 AnalyzeDeleteExprMismatch(Result);
3436 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003437}
3438
Eric Fiselierfa752f22018-03-21 19:19:48 +00003439static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3440 bool IsDelete,
3441 FunctionDecl *&Operator) {
3442
3443 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3444 IsDelete ? OO_Delete : OO_New);
3445
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003446 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003447 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3448 assert(!R.empty() && "implicitly declared allocation functions not found");
3449 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3450
3451 // We do our own custom access checks below.
3452 R.suppressDiagnostics();
3453
3454 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3455 OverloadCandidateSet Candidates(R.getNameLoc(),
3456 OverloadCandidateSet::CSK_Normal);
3457 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3458 FnOvl != FnOvlEnd; ++FnOvl) {
3459 // Even member operator new/delete are implicitly treated as
3460 // static, so don't use AddMemberCandidate.
3461 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3462
3463 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3464 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3465 /*ExplicitTemplateArgs=*/nullptr, Args,
3466 Candidates,
3467 /*SuppressUserConversions=*/false);
3468 continue;
3469 }
3470
3471 FunctionDecl *Fn = cast<FunctionDecl>(D);
3472 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3473 /*SuppressUserConversions=*/false);
3474 }
3475
3476 SourceRange Range = TheCall->getSourceRange();
3477
3478 // Do the resolution.
3479 OverloadCandidateSet::iterator Best;
3480 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3481 case OR_Success: {
3482 // Got one!
3483 FunctionDecl *FnDecl = Best->Function;
3484 assert(R.getNamingClass() == nullptr &&
3485 "class members should not be considered");
3486
3487 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3488 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3489 << (IsDelete ? 1 : 0) << Range;
3490 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3491 << R.getLookupName() << FnDecl->getSourceRange();
3492 return true;
3493 }
3494
3495 Operator = FnDecl;
3496 return false;
3497 }
3498
3499 case OR_No_Viable_Function:
3500 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3501 << R.getLookupName() << Range;
3502 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3503 return true;
3504
3505 case OR_Ambiguous:
3506 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3507 << R.getLookupName() << Range;
3508 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3509 return true;
3510
3511 case OR_Deleted: {
3512 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3513 << Best->Function->isDeleted() << R.getLookupName()
3514 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3515 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3516 return true;
3517 }
3518 }
3519 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3520}
3521
3522ExprResult
3523Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3524 bool IsDelete) {
3525 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3526 if (!getLangOpts().CPlusPlus) {
3527 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3528 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3529 << "C++";
3530 return ExprError();
3531 }
3532 // CodeGen assumes it can find the global new and delete to call,
3533 // so ensure that they are declared.
3534 DeclareGlobalNewDelete();
3535
3536 FunctionDecl *OperatorNewOrDelete = nullptr;
3537 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3538 OperatorNewOrDelete))
3539 return ExprError();
3540 assert(OperatorNewOrDelete && "should be found");
3541
3542 TheCall->setType(OperatorNewOrDelete->getReturnType());
3543 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3544 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3545 InitializedEntity Entity =
3546 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3547 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003548 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003549 if (Arg.isInvalid())
3550 return ExprError();
3551 TheCall->setArg(i, Arg.get());
3552 }
3553 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3554 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3555 "Callee expected to be implicit cast to a builtin function pointer");
3556 Callee->setType(OperatorNewOrDelete->getType());
3557
3558 return TheCallResult;
3559}
3560
Nico Weber5a9259c2016-01-15 21:45:31 +00003561void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3562 bool IsDelete, bool CallCanBeVirtual,
3563 bool WarnOnNonAbstractTypes,
3564 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003565 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003566 return;
3567
3568 // C++ [expr.delete]p3:
3569 // In the first alternative (delete object), if the static type of the
3570 // object to be deleted is different from its dynamic type, the static
3571 // type shall be a base class of the dynamic type of the object to be
3572 // deleted and the static type shall have a virtual destructor or the
3573 // behavior is undefined.
3574 //
3575 const CXXRecordDecl *PointeeRD = dtor->getParent();
3576 // Note: a final class cannot be derived from, no issue there
3577 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3578 return;
3579
Nico Weberbf2260c2017-08-31 06:17:08 +00003580 // If the superclass is in a system header, there's nothing that can be done.
3581 // The `delete` (where we emit the warning) can be in a system header,
3582 // what matters for this warning is where the deleted type is defined.
3583 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3584 return;
3585
Nico Weber5a9259c2016-01-15 21:45:31 +00003586 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3587 if (PointeeRD->isAbstract()) {
3588 // If the class is abstract, we warn by default, because we're
3589 // sure the code has undefined behavior.
3590 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3591 << ClassType;
3592 } else if (WarnOnNonAbstractTypes) {
3593 // Otherwise, if this is not an array delete, it's a bit suspect,
3594 // but not necessarily wrong.
3595 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3596 << ClassType;
3597 }
3598 if (!IsDelete) {
3599 std::string TypeStr;
3600 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3601 Diag(DtorLoc, diag::note_delete_non_virtual)
3602 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3603 }
3604}
3605
Richard Smith03a4aa32016-06-23 19:02:52 +00003606Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3607 SourceLocation StmtLoc,
3608 ConditionKind CK) {
3609 ExprResult E =
3610 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3611 if (E.isInvalid())
3612 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003613 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3614 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003615}
3616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003617/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003618/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003619ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003620 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003621 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003622 if (ConditionVar->isInvalidDecl())
3623 return ExprError();
3624
Douglas Gregor633caca2009-11-23 23:44:04 +00003625 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626
Douglas Gregor633caca2009-11-23 23:44:04 +00003627 // C++ [stmt.select]p2:
3628 // The declarator shall not specify a function or an array.
3629 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003631 diag::err_invalid_use_of_function_type)
3632 << ConditionVar->getSourceRange());
3633 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003635 diag::err_invalid_use_of_array_type)
3636 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003637
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003638 ExprResult Condition = DeclRefExpr::Create(
3639 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3640 /*enclosing*/ false, ConditionVar->getLocation(),
3641 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003642
Eli Friedmanfa0df832012-02-02 03:46:19 +00003643 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003644
Richard Smith03a4aa32016-06-23 19:02:52 +00003645 switch (CK) {
3646 case ConditionKind::Boolean:
3647 return CheckBooleanCondition(StmtLoc, Condition.get());
3648
Richard Smithb130fe72016-06-23 19:16:49 +00003649 case ConditionKind::ConstexprIf:
3650 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3651
Richard Smith03a4aa32016-06-23 19:02:52 +00003652 case ConditionKind::Switch:
3653 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Richard Smith03a4aa32016-06-23 19:02:52 +00003656 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003657}
3658
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003659/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003660ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003661 // C++ 6.4p4:
3662 // The value of a condition that is an initialized declaration in a statement
3663 // other than a switch statement is the value of the declared variable
3664 // implicitly converted to type bool. If that conversion is ill-formed, the
3665 // program is ill-formed.
3666 // The value of a condition that is an expression is the value of the
3667 // expression, implicitly converted to bool.
3668 //
Richard Smithb130fe72016-06-23 19:16:49 +00003669 // FIXME: Return this value to the caller so they don't need to recompute it.
3670 llvm::APSInt Value(/*BitWidth*/1);
3671 return (IsConstexpr && !CondExpr->isValueDependent())
3672 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3673 CCEK_ConstexprIf)
3674 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003675}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003676
3677/// Helper function to determine whether this is the (deprecated) C++
3678/// conversion from a string literal to a pointer to non-const char or
3679/// non-const wchar_t (for narrow and wide string literals,
3680/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003681bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003682Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3683 // Look inside the implicit cast, if it exists.
3684 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3685 From = Cast->getSubExpr();
3686
3687 // A string literal (2.13.4) that is not a wide string literal can
3688 // be converted to an rvalue of type "pointer to char"; a wide
3689 // string literal can be converted to an rvalue of type "pointer
3690 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003691 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003692 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003693 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003694 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003695 // This conversion is considered only when there is an
3696 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003697 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3698 switch (StrLit->getKind()) {
3699 case StringLiteral::UTF8:
3700 case StringLiteral::UTF16:
3701 case StringLiteral::UTF32:
3702 // We don't allow UTF literals to be implicitly converted
3703 break;
3704 case StringLiteral::Ascii:
3705 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3706 ToPointeeType->getKind() == BuiltinType::Char_S);
3707 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003708 return Context.typesAreCompatible(Context.getWideCharType(),
3709 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003710 }
3711 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003712 }
3713
3714 return false;
3715}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003716
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003718 SourceLocation CastLoc,
3719 QualType Ty,
3720 CastKind Kind,
3721 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003722 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003723 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003724 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003725 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003726 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003727 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003728 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003729 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Richard Smith72d74052013-07-20 19:41:36 +00003731 if (S.RequireNonAbstractType(CastLoc, Ty,
3732 diag::err_allocation_of_abstract_type))
3733 return ExprError();
3734
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003735 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003736 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Richard Smith5179eb72016-06-28 19:03:57 +00003738 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3739 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003740 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003741 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003742
Richard Smithf8adcdc2014-07-17 05:12:35 +00003743 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003744 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003745 ConstructorArgs, HadMultipleCandidates,
3746 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3747 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003748 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003749 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003751 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753
John McCalle3027922010-08-25 11:45:40 +00003754 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003755 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Richard Smithd3f2d322015-02-24 21:16:19 +00003757 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003758 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003759 return ExprError();
3760
Douglas Gregora4253922010-04-16 22:17:36 +00003761 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003762 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3763 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003764 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003765 if (Result.isInvalid())
3766 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003767 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003768 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3769 CK_UserDefinedConversion, Result.get(),
3770 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Douglas Gregor668443e2011-01-20 00:18:04 +00003772 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003773 }
3774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775}
Douglas Gregora4253922010-04-16 22:17:36 +00003776
Douglas Gregor5fb53972009-01-14 15:45:31 +00003777/// PerformImplicitConversion - Perform an implicit conversion of the
3778/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003779/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003780/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003781/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003782ExprResult
3783Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003784 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003785 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003786 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003787 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3788 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3789 return From;
3790
John McCall0d1da222010-01-12 00:44:57 +00003791 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003792 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003793 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3794 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003795 if (Res.isInvalid())
3796 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003797 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003798 break;
John Wiegley01296292011-04-08 18:41:53 +00003799 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003800
Anders Carlsson110b07b2009-09-15 06:28:28 +00003801 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003802
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003803 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003804 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003805 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003806 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003807 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003808 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Anders Carlsson110b07b2009-09-15 06:28:28 +00003810 // If the user-defined conversion is specified by a conversion function,
3811 // the initial standard conversion sequence converts the source type to
3812 // the implicit object parameter of the conversion function.
3813 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003814 } else {
3815 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003816 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003817 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003818 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003820 // initial standard conversion sequence converts the source type to
3821 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003822 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 }
Richard Smith72d74052013-07-20 19:41:36 +00003825 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003826 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003827 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003828 PerformImplicitConversion(From, BeforeToType,
3829 ICS.UserDefined.Before, AA_Converting,
3830 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003831 if (Res.isInvalid())
3832 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003833 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003836 ExprResult CastArg = BuildCXXCastArgument(
3837 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3838 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3839 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003840
3841 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003842 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003843
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003844 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003845
Richard Smith1ef75542018-06-27 20:30:34 +00003846 // C++ [over.match.oper]p7:
3847 // [...] the second standard conversion sequence of a user-defined
3848 // conversion sequence is not applied.
3849 if (CCK == CCK_ForBuiltinOverloadedOp)
3850 return From;
3851
Richard Smith507840d2011-11-29 22:48:16 +00003852 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3853 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003854 }
John McCall0d1da222010-01-12 00:44:57 +00003855
3856 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003857 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003858 PDiag(diag::err_typecheck_ambiguous_condition)
3859 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003860 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861
Douglas Gregor39c16d42008-10-24 04:54:22 +00003862 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003863 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003864
3865 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003866 bool Diagnosed =
3867 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3868 From->getType(), From, Action);
3869 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003870 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003871 }
3872
3873 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003874 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003875}
3876
Richard Smith507840d2011-11-29 22:48:16 +00003877/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003878/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003879/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003880/// expression. Flavor is the context in which we're performing this
3881/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003882ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003883Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003884 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003885 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003886 CheckedConversionKind CCK) {
3887 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003888
Mike Stump87c57ac2009-05-16 07:39:55 +00003889 // Overall FIXME: we are recomputing too many types here and doing far too
3890 // much extra work. What this means is that we need to keep track of more
3891 // information that is computed when we try the implicit conversion initially,
3892 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003893 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003894
Douglas Gregor2fe98832008-11-03 19:09:14 +00003895 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003896 // FIXME: When can ToType be a reference type?
3897 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003898 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003899 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003900 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003901 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003902 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003903 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003904 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003905 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3906 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003907 ConstructorArgs, /*HadMultipleCandidates*/ false,
3908 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3909 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003910 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003911 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003912 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3913 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003914 From, /*HadMultipleCandidates*/ false,
3915 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3916 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003917 }
3918
Douglas Gregor980fb162010-04-29 18:24:40 +00003919 // Resolve overloaded function references.
3920 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3921 DeclAccessPair Found;
3922 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3923 true, Found);
3924 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003925 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003926
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003927 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003928 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor980fb162010-04-29 18:24:40 +00003930 From = FixOverloadedFunctionReference(From, Found, Fn);
3931 FromType = From->getType();
3932 }
3933
Richard Smitha23ab512013-05-23 00:30:41 +00003934 // If we're converting to an atomic type, first convert to the corresponding
3935 // non-atomic type.
3936 QualType ToAtomicType;
3937 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3938 ToAtomicType = ToType;
3939 ToType = ToAtomic->getValueType();
3940 }
3941
George Burgess IV8d141e02015-12-14 22:00:49 +00003942 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003943 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003944 switch (SCS.First) {
3945 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003946 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3947 FromType = FromAtomic->getValueType().getUnqualifiedType();
3948 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3949 From, /*BasePath=*/nullptr, VK_RValue);
3950 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003951 break;
3952
Eli Friedman946b7b52012-01-24 22:51:26 +00003953 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003954 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003955 ExprResult FromRes = DefaultLvalueConversion(From);
3956 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003957 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003958 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003959 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003960 }
John McCall34376a62010-12-04 03:47:34 +00003961
Douglas Gregor39c16d42008-10-24 04:54:22 +00003962 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003963 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003964 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003965 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003966 break;
3967
3968 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003969 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003970 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003971 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003972 break;
3973
3974 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003975 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003976 }
3977
Richard Smith507840d2011-11-29 22:48:16 +00003978 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003979 switch (SCS.Second) {
3980 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003981 // C++ [except.spec]p5:
3982 // [For] assignment to and initialization of pointers to functions,
3983 // pointers to member functions, and references to functions: the
3984 // target entity shall allow at least the exceptions allowed by the
3985 // source value in the assignment or initialization.
3986 switch (Action) {
3987 case AA_Assigning:
3988 case AA_Initializing:
3989 // Note, function argument passing and returning are initialization.
3990 case AA_Passing:
3991 case AA_Returning:
3992 case AA_Sending:
3993 case AA_Passing_CFAudited:
3994 if (CheckExceptionSpecCompatibility(From, ToType))
3995 return ExprError();
3996 break;
3997
3998 case AA_Casting:
3999 case AA_Converting:
4000 // Casts and implicit conversions are not initialization, so are not
4001 // checked for exception specification mismatches.
4002 break;
4003 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004004 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004005 break;
4006
4007 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004008 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004009 if (ToType->isBooleanType()) {
4010 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4011 SCS.Second == ICK_Integral_Promotion &&
4012 "only enums with fixed underlying type can promote to bool");
4013 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004014 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004015 } else {
4016 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004017 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004018 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004019 break;
4020
4021 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004022 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004023 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004024 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004025 break;
4026
4027 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004028 case ICK_Complex_Conversion: {
4029 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4030 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4031 CastKind CK;
4032 if (FromEl->isRealFloatingType()) {
4033 if (ToEl->isRealFloatingType())
4034 CK = CK_FloatingComplexCast;
4035 else
4036 CK = CK_FloatingComplexToIntegralComplex;
4037 } else if (ToEl->isRealFloatingType()) {
4038 CK = CK_IntegralComplexToFloatingComplex;
4039 } else {
4040 CK = CK_IntegralComplexCast;
4041 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004042 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004043 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004044 break;
John McCall8cb679e2010-11-15 09:13:47 +00004045 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004046
Douglas Gregor39c16d42008-10-24 04:54:22 +00004047 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004048 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004049 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004050 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004051 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004052 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004053 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004054 break;
4055
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004056 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004057 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004058 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004059 break;
4060
John McCall31168b02011-06-15 23:02:42 +00004061 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004062 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004063 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004064 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004065 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004066 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004067 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004068 << ToType << From->getType() << Action << From->getSourceRange()
4069 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004070 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004071 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004072 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004073 << From->getType() << ToType << Action << From->getSourceRange()
4074 << 0;
John McCall31168b02011-06-15 23:02:42 +00004075
Douglas Gregor33823722011-06-11 01:09:30 +00004076 if (From->getType()->isObjCObjectPointerType() &&
4077 ToType->isObjCObjectPointerType())
4078 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004079 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4080 !CheckObjCARCUnavailableWeakConversion(ToType,
4081 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004082 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004083 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004084 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004085 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4086 << (Action == AA_Casting) << From->getType() << ToType
4087 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004088 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004089
Richard Smith354abec2017-12-08 23:29:59 +00004090 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004091 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004092 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004093 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004094
4095 // Make sure we extend blocks if necessary.
4096 // FIXME: doing this here is really ugly.
4097 if (Kind == CK_BlockPointerToObjCPointerCast) {
4098 ExprResult E = From;
4099 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004100 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004101 }
Brian Kelley11352a82017-03-29 18:09:02 +00004102 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4103 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004104 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004105 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004106 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004109 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004110 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004111 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004112 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004113 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004114 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004115 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004116
4117 // We may not have been able to figure out what this member pointer resolved
4118 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004119 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004120 (void)isCompleteType(From->getExprLoc(), From->getType());
4121 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004122 }
David Majnemerd96b9972014-08-08 00:10:39 +00004123
Richard Smith507840d2011-11-29 22:48:16 +00004124 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004125 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004126 break;
4127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004129 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004130 // Perform half-to-boolean conversion via float.
4131 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004132 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004133 FromType = Context.FloatTy;
4134 }
4135
Richard Smith507840d2011-11-29 22:48:16 +00004136 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004137 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004138 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004139 break;
4140
Douglas Gregor88d292c2010-05-13 16:44:06 +00004141 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004142 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004143 if (CheckDerivedToBaseConversion(
4144 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4145 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004146 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004147
Richard Smith507840d2011-11-29 22:48:16 +00004148 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4149 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004150 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004151 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004152 }
4153
Douglas Gregor46188682010-05-18 22:42:18 +00004154 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004155 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004156 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004157 break;
4158
George Burgess IVdf1ed002016-01-13 01:52:39 +00004159 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004160 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004161 Expr *Elem = prepareVectorSplat(ToType, From).get();
4162 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4163 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004164 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166
Douglas Gregor46188682010-05-18 22:42:18 +00004167 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004168 // Case 1. x -> _Complex y
4169 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4170 QualType ElType = ToComplex->getElementType();
4171 bool isFloatingComplex = ElType->isRealFloatingType();
4172
4173 // x -> y
4174 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4175 // do nothing
4176 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004177 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004178 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004179 } else {
4180 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004181 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004182 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004183 }
4184 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004185 From = ImpCastExprToType(From, ToType,
4186 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004187 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004188
4189 // Case 2. _Complex x -> y
4190 } else {
4191 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4192 assert(FromComplex);
4193
4194 QualType ElType = FromComplex->getElementType();
4195 bool isFloatingComplex = ElType->isRealFloatingType();
4196
4197 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004198 From = ImpCastExprToType(From, ElType,
4199 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004200 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004201 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004202
4203 // x -> y
4204 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4205 // do nothing
4206 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004207 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004208 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004209 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004210 } else {
4211 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004212 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004213 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004214 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004215 }
4216 }
Douglas Gregor46188682010-05-18 22:42:18 +00004217 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004218
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004219 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004220 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004221 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004222 break;
4223 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004224
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004225 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004226 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004227 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004228 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4229 if (FromRes.isInvalid())
4230 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004231 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004232 assert ((ConvTy == Sema::Compatible) &&
4233 "Improper transparent union conversion");
4234 (void)ConvTy;
4235 break;
4236 }
4237
Guy Benyei259f9f42013-02-07 16:05:33 +00004238 case ICK_Zero_Event_Conversion:
4239 From = ImpCastExprToType(From, ToType,
4240 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004241 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004242 break;
4243
Egor Churaev89831422016-12-23 14:55:49 +00004244 case ICK_Zero_Queue_Conversion:
4245 From = ImpCastExprToType(From, ToType,
4246 CK_ZeroToOCLQueue,
4247 From->getValueKind()).get();
4248 break;
4249
Douglas Gregor46188682010-05-18 22:42:18 +00004250 case ICK_Lvalue_To_Rvalue:
4251 case ICK_Array_To_Pointer:
4252 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004253 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004254 case ICK_Qualification:
4255 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004256 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004257 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004258 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004259 }
4260
4261 switch (SCS.Third) {
4262 case ICK_Identity:
4263 // Nothing to do.
4264 break;
4265
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004266 case ICK_Function_Conversion:
4267 // If both sides are functions (or pointers/references to them), there could
4268 // be incompatible exception declarations.
4269 if (CheckExceptionSpecCompatibility(From, ToType))
4270 return ExprError();
4271
4272 From = ImpCastExprToType(From, ToType, CK_NoOp,
4273 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4274 break;
4275
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004276 case ICK_Qualification: {
4277 // The qualification keeps the category of the inner expression, unless the
4278 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004279 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004280 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004281 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004282 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004283
Douglas Gregore981bb02011-03-14 16:13:32 +00004284 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004285 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004286 Diag(From->getBeginLoc(),
4287 getLangOpts().CPlusPlus11
4288 ? diag::ext_deprecated_string_literal_conversion
4289 : diag::warn_deprecated_string_literal_conversion)
4290 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004291 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004292
Douglas Gregor39c16d42008-10-24 04:54:22 +00004293 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004294 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004295
Douglas Gregor39c16d42008-10-24 04:54:22 +00004296 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004297 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004298 }
4299
Douglas Gregor298f43d2012-04-12 20:42:30 +00004300 // If this conversion sequence involved a scalar -> atomic conversion, perform
4301 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004302 if (!ToAtomicType.isNull()) {
4303 assert(Context.hasSameType(
4304 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4305 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004306 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004307 }
4308
George Burgess IV8d141e02015-12-14 22:00:49 +00004309 // If this conversion sequence succeeded and involved implicitly converting a
4310 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004311 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004312 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004313 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004314
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004315 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004316}
4317
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004318/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004319///
4320/// If the particular type trait requires a complete type, tries to complete
4321/// it. If completing the type fails, a diagnostic is emitted and false
4322/// returned. If completing the type succeeds or no completion was required,
4323/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004324static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004325 SourceLocation Loc,
4326 QualType ArgTy) {
4327 // C++0x [meta.unary.prop]p3:
4328 // For all of the class templates X declared in this Clause, instantiating
4329 // that template with a template argument that is a class template
4330 // specialization may result in the implicit instantiation of the template
4331 // argument if and only if the semantics of X require that the argument
4332 // must be a complete type.
4333 // We apply this rule to all the type trait expressions used to implement
4334 // these class templates. We also try to follow any GCC documented behavior
4335 // in these expressions to ensure portability of standard libraries.
4336 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004337 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004338 // is_complete_type somewhat obviously cannot require a complete type.
4339 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004340 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004341
4342 // These traits are modeled on the type predicates in C++0x
4343 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4344 // requiring a complete type, as whether or not they return true cannot be
4345 // impacted by the completeness of the type.
4346 case UTT_IsVoid:
4347 case UTT_IsIntegral:
4348 case UTT_IsFloatingPoint:
4349 case UTT_IsArray:
4350 case UTT_IsPointer:
4351 case UTT_IsLvalueReference:
4352 case UTT_IsRvalueReference:
4353 case UTT_IsMemberFunctionPointer:
4354 case UTT_IsMemberObjectPointer:
4355 case UTT_IsEnum:
4356 case UTT_IsUnion:
4357 case UTT_IsClass:
4358 case UTT_IsFunction:
4359 case UTT_IsReference:
4360 case UTT_IsArithmetic:
4361 case UTT_IsFundamental:
4362 case UTT_IsObject:
4363 case UTT_IsScalar:
4364 case UTT_IsCompound:
4365 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004366 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004367
4368 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4369 // which requires some of its traits to have the complete type. However,
4370 // the completeness of the type cannot impact these traits' semantics, and
4371 // so they don't require it. This matches the comments on these traits in
4372 // Table 49.
4373 case UTT_IsConst:
4374 case UTT_IsVolatile:
4375 case UTT_IsSigned:
4376 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004377
4378 // This type trait always returns false, checking the type is moot.
4379 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004380 return true;
4381
David Majnemer213bea32015-11-16 06:58:51 +00004382 // C++14 [meta.unary.prop]:
4383 // If T is a non-union class type, T shall be a complete type.
4384 case UTT_IsEmpty:
4385 case UTT_IsPolymorphic:
4386 case UTT_IsAbstract:
4387 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4388 if (!RD->isUnion())
4389 return !S.RequireCompleteType(
4390 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4391 return true;
4392
4393 // C++14 [meta.unary.prop]:
4394 // If T is a class type, T shall be a complete type.
4395 case UTT_IsFinal:
4396 case UTT_IsSealed:
4397 if (ArgTy->getAsCXXRecordDecl())
4398 return !S.RequireCompleteType(
4399 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4400 return true;
4401
Richard Smithf03e9082017-06-01 00:28:16 +00004402 // C++1z [meta.unary.prop]:
4403 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004404 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004405 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004406 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004407 case UTT_IsStandardLayout:
4408 case UTT_IsPOD:
4409 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004410 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4411 // or an array of unknown bound. But GCC actually imposes the same constraints
4412 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004413 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004414 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004415 case UTT_HasNothrowConstructor:
4416 case UTT_HasNothrowCopy:
4417 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004418 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004419 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004420 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004421 case UTT_HasTrivialCopy:
4422 case UTT_HasTrivialDestructor:
4423 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004424 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4425 LLVM_FALLTHROUGH;
4426
4427 // C++1z [meta.unary.prop]:
4428 // T shall be a complete type, cv void, or an array of unknown bound.
4429 case UTT_IsDestructible:
4430 case UTT_IsNothrowDestructible:
4431 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004432 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004433 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004434 return true;
4435
4436 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004437 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004438 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004439}
4440
Joao Matosc9523d42013-03-27 01:34:16 +00004441static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4442 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004443 bool (CXXRecordDecl::*HasTrivial)() const,
4444 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004445 bool (CXXMethodDecl::*IsDesiredOp)() const)
4446{
4447 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4448 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4449 return true;
4450
4451 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4452 DeclarationNameInfo NameInfo(Name, KeyLoc);
4453 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4454 if (Self.LookupQualifiedName(Res, RD)) {
4455 bool FoundOperator = false;
4456 Res.suppressDiagnostics();
4457 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4458 Op != OpEnd; ++Op) {
4459 if (isa<FunctionTemplateDecl>(*Op))
4460 continue;
4461
4462 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4463 if((Operator->*IsDesiredOp)()) {
4464 FoundOperator = true;
4465 const FunctionProtoType *CPT =
4466 Operator->getType()->getAs<FunctionProtoType>();
4467 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004468 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004469 return false;
4470 }
4471 }
4472 return FoundOperator;
4473 }
4474 return false;
4475}
4476
Alp Toker95e7ff22014-01-01 05:57:51 +00004477static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004478 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004479 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004480
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004481 ASTContext &C = Self.Context;
4482 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004483 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004484 // Type trait expressions corresponding to the primary type category
4485 // predicates in C++0x [meta.unary.cat].
4486 case UTT_IsVoid:
4487 return T->isVoidType();
4488 case UTT_IsIntegral:
4489 return T->isIntegralType(C);
4490 case UTT_IsFloatingPoint:
4491 return T->isFloatingType();
4492 case UTT_IsArray:
4493 return T->isArrayType();
4494 case UTT_IsPointer:
4495 return T->isPointerType();
4496 case UTT_IsLvalueReference:
4497 return T->isLValueReferenceType();
4498 case UTT_IsRvalueReference:
4499 return T->isRValueReferenceType();
4500 case UTT_IsMemberFunctionPointer:
4501 return T->isMemberFunctionPointerType();
4502 case UTT_IsMemberObjectPointer:
4503 return T->isMemberDataPointerType();
4504 case UTT_IsEnum:
4505 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004506 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004507 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004508 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004509 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004510 case UTT_IsFunction:
4511 return T->isFunctionType();
4512
4513 // Type trait expressions which correspond to the convenient composition
4514 // predicates in C++0x [meta.unary.comp].
4515 case UTT_IsReference:
4516 return T->isReferenceType();
4517 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004518 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004519 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004520 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004521 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004522 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004523 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004524 // Note: semantic analysis depends on Objective-C lifetime types to be
4525 // considered scalar types. However, such types do not actually behave
4526 // like scalar types at run time (since they may require retain/release
4527 // operations), so we report them as non-scalar.
4528 if (T->isObjCLifetimeType()) {
4529 switch (T.getObjCLifetime()) {
4530 case Qualifiers::OCL_None:
4531 case Qualifiers::OCL_ExplicitNone:
4532 return true;
4533
4534 case Qualifiers::OCL_Strong:
4535 case Qualifiers::OCL_Weak:
4536 case Qualifiers::OCL_Autoreleasing:
4537 return false;
4538 }
4539 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004540
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004541 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004542 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004543 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004544 case UTT_IsMemberPointer:
4545 return T->isMemberPointerType();
4546
4547 // Type trait expressions which correspond to the type property predicates
4548 // in C++0x [meta.unary.prop].
4549 case UTT_IsConst:
4550 return T.isConstQualified();
4551 case UTT_IsVolatile:
4552 return T.isVolatileQualified();
4553 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004554 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004555 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004556 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004557 case UTT_IsStandardLayout:
4558 return T->isStandardLayoutType();
4559 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004560 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004561 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004562 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004563 case UTT_IsEmpty:
4564 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4565 return !RD->isUnion() && RD->isEmpty();
4566 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004567 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004568 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004569 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004570 return false;
4571 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004572 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004573 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004574 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004575 case UTT_IsAggregate:
4576 // Report vector extensions and complex types as aggregates because they
4577 // support aggregate initialization. GCC mirrors this behavior for vectors
4578 // but not _Complex.
4579 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4580 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004581 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4582 // even then only when it is used with the 'interface struct ...' syntax
4583 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004584 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004585 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004586 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004587 case UTT_IsSealed:
4588 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004589 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004590 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004591 case UTT_IsSigned:
4592 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004593 case UTT_IsUnsigned:
4594 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004595
4596 // Type trait expressions which query classes regarding their construction,
4597 // destruction, and copying. Rather than being based directly on the
4598 // related type predicates in the standard, they are specified by both
4599 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4600 // specifications.
4601 //
4602 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4603 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004604 //
4605 // Note that these builtins do not behave as documented in g++: if a class
4606 // has both a trivial and a non-trivial special member of a particular kind,
4607 // they return false! For now, we emulate this behavior.
4608 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4609 // does not correctly compute triviality in the presence of multiple special
4610 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004611 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004612 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4613 // If __is_pod (type) is true then the trait is true, else if type is
4614 // a cv class or union type (or array thereof) with a trivial default
4615 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004616 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004617 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004618 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4619 return RD->hasTrivialDefaultConstructor() &&
4620 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004621 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004622 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004623 // This trait is implemented by MSVC 2012 and needed to parse the
4624 // standard library headers. Specifically this is used as the logic
4625 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004626 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004627 return true;
4628 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4629 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4630 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004631 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004632 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4633 // If __is_pod (type) is true or type is a reference type then
4634 // the trait is true, else if type is a cv class or union type
4635 // with a trivial copy constructor ([class.copy]) then the trait
4636 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004637 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004638 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004639 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4640 return RD->hasTrivialCopyConstructor() &&
4641 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004642 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004643 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004644 // This trait is implemented by MSVC 2012 and needed to parse the
4645 // standard library headers. Specifically it is used as the logic
4646 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004647 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004648 return true;
4649 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4650 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4651 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004652 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004653 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4654 // If type is const qualified or is a reference type then the
4655 // trait is false. Otherwise if __is_pod (type) is true then the
4656 // trait is true, else if type is a cv class or union type with
4657 // a trivial copy assignment ([class.copy]) then the trait is
4658 // true, else it is false.
4659 // Note: the const and reference restrictions are interesting,
4660 // given that const and reference members don't prevent a class
4661 // from having a trivial copy assignment operator (but do cause
4662 // errors if the copy assignment operator is actually used, q.v.
4663 // [class.copy]p12).
4664
Richard Smith92f241f2012-12-08 02:53:02 +00004665 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004666 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004667 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004668 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004669 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4670 return RD->hasTrivialCopyAssignment() &&
4671 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004672 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004673 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004674 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004675 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004676 // C++14 [meta.unary.prop]:
4677 // For reference types, is_destructible<T>::value is true.
4678 if (T->isReferenceType())
4679 return true;
4680
4681 // Objective-C++ ARC: autorelease types don't require destruction.
4682 if (T->isObjCLifetimeType() &&
4683 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4684 return true;
4685
4686 // C++14 [meta.unary.prop]:
4687 // For incomplete types and function types, is_destructible<T>::value is
4688 // false.
4689 if (T->isIncompleteType() || T->isFunctionType())
4690 return false;
4691
Richard Smithf03e9082017-06-01 00:28:16 +00004692 // A type that requires destruction (via a non-trivial destructor or ARC
4693 // lifetime semantics) is not trivially-destructible.
4694 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4695 return false;
4696
David Majnemerac73de92015-08-11 03:03:28 +00004697 // C++14 [meta.unary.prop]:
4698 // For object types and given U equal to remove_all_extents_t<T>, if the
4699 // expression std::declval<U&>().~U() is well-formed when treated as an
4700 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4701 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4702 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4703 if (!Destructor)
4704 return false;
4705 // C++14 [dcl.fct.def.delete]p2:
4706 // A program that refers to a deleted function implicitly or
4707 // explicitly, other than to declare it, is ill-formed.
4708 if (Destructor->isDeleted())
4709 return false;
4710 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4711 return false;
4712 if (UTT == UTT_IsNothrowDestructible) {
4713 const FunctionProtoType *CPT =
4714 Destructor->getType()->getAs<FunctionProtoType>();
4715 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004716 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004717 return false;
4718 }
4719 }
4720 return true;
4721
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004722 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004723 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004724 // If __is_pod (type) is true or type is a reference type
4725 // then the trait is true, else if type is a cv class or union
4726 // type (or array thereof) with a trivial destructor
4727 // ([class.dtor]) then the trait is true, else it is
4728 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004729 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004730 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004731
John McCall31168b02011-06-15 23:02:42 +00004732 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004733 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004734 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4735 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004736
Richard Smith92f241f2012-12-08 02:53:02 +00004737 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4738 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004739 return false;
4740 // TODO: Propagate nothrowness for implicitly declared special members.
4741 case UTT_HasNothrowAssign:
4742 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4743 // If type is const qualified or is a reference type then the
4744 // trait is false. Otherwise if __has_trivial_assign (type)
4745 // is true then the trait is true, else if type is a cv class
4746 // or union type with copy assignment operators that are known
4747 // not to throw an exception then the trait is true, else it is
4748 // false.
4749 if (C.getBaseElementType(T).isConstQualified())
4750 return false;
4751 if (T->isReferenceType())
4752 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004753 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004754 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004755
Joao Matosc9523d42013-03-27 01:34:16 +00004756 if (const RecordType *RT = T->getAs<RecordType>())
4757 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4758 &CXXRecordDecl::hasTrivialCopyAssignment,
4759 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4760 &CXXMethodDecl::isCopyAssignmentOperator);
4761 return false;
4762 case UTT_HasNothrowMoveAssign:
4763 // This trait is implemented by MSVC 2012 and needed to parse the
4764 // standard library headers. Specifically this is used as the logic
4765 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004766 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004767 return true;
4768
4769 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4770 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4771 &CXXRecordDecl::hasTrivialMoveAssignment,
4772 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4773 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004774 return false;
4775 case UTT_HasNothrowCopy:
4776 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4777 // If __has_trivial_copy (type) is true then the trait is true, else
4778 // if type is a cv class or union type with copy constructors that are
4779 // known not to throw an exception then the trait is true, else it is
4780 // false.
John McCall31168b02011-06-15 23:02:42 +00004781 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004782 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004783 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4784 if (RD->hasTrivialCopyConstructor() &&
4785 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004786 return true;
4787
4788 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004789 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004790 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004791 // A template constructor is never a copy constructor.
4792 // FIXME: However, it may actually be selected at the actual overload
4793 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004794 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004795 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004796 // UsingDecl itself is not a constructor
4797 if (isa<UsingDecl>(ND))
4798 continue;
4799 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004800 if (Constructor->isCopyConstructor(FoundTQs)) {
4801 FoundConstructor = true;
4802 const FunctionProtoType *CPT
4803 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004804 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4805 if (!CPT)
4806 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004807 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004808 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004809 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004810 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004811 }
4812 }
4813
Richard Smith938f40b2011-06-11 17:19:42 +00004814 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004815 }
4816 return false;
4817 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004818 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004819 // If __has_trivial_constructor (type) is true then the trait is
4820 // true, else if type is a cv class or union type (or array
4821 // thereof) with a default constructor that is known not to
4822 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004823 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004824 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004825 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4826 if (RD->hasTrivialDefaultConstructor() &&
4827 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004828 return true;
4829
Alp Tokerb4bca412014-01-20 00:23:47 +00004830 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004831 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004832 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004833 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004834 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004835 // UsingDecl itself is not a constructor
4836 if (isa<UsingDecl>(ND))
4837 continue;
4838 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004839 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004840 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004841 const FunctionProtoType *CPT
4842 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004843 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4844 if (!CPT)
4845 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004846 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004847 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004848 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004849 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004850 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004851 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004852 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004853 }
4854 return false;
4855 case UTT_HasVirtualDestructor:
4856 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4857 // If type is a class type with a virtual destructor ([class.dtor])
4858 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004859 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004860 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004861 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004862 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004863
4864 // These type trait expressions are modeled on the specifications for the
4865 // Embarcadero C++0x type trait functions:
4866 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4867 case UTT_IsCompleteType:
4868 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4869 // Returns True if and only if T is a complete type at the point of the
4870 // function call.
4871 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004872 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004873 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004874 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004875}
Sebastian Redl5822f082009-02-07 20:10:22 +00004876
Alp Tokercbb90342013-12-13 20:49:58 +00004877static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4878 QualType RhsT, SourceLocation KeyLoc);
4879
Douglas Gregor29c42f22012-02-24 07:38:34 +00004880static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4881 ArrayRef<TypeSourceInfo *> Args,
4882 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004883 if (Kind <= UTT_Last)
4884 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4885
Eric Fiselier1af6c112018-01-12 00:09:37 +00004886 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4887 // traits to avoid duplication.
4888 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004889 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4890 Args[1]->getType(), RParenLoc);
4891
Douglas Gregor29c42f22012-02-24 07:38:34 +00004892 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004893 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004894 case clang::TT_IsConstructible:
4895 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004896 case clang::TT_IsTriviallyConstructible: {
4897 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004898 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004899 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004900 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004901 // definition for is_constructible, as defined below, is known to call
4902 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004903 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004904 // The predicate condition for a template specialization
4905 // is_constructible<T, Args...> shall be satisfied if and only if the
4906 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004907 // variable t:
4908 //
4909 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004910 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004911
4912 // Precondition: T and all types in the parameter pack Args shall be
4913 // complete types, (possibly cv-qualified) void, or arrays of
4914 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004915 for (const auto *TSI : Args) {
4916 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004917 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004918 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004919
Simon Pilgrim75c26882016-09-30 14:25:09 +00004920 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004921 diag::err_incomplete_type_used_in_type_trait_expr))
4922 return false;
4923 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004924
David Majnemer9658ecc2015-11-13 05:32:43 +00004925 // Make sure the first argument is not incomplete nor a function type.
4926 QualType T = Args[0]->getType();
4927 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004928 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004929
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004930 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004931 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004932 if (RD && RD->isAbstract())
4933 return false;
4934
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004935 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4936 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004937 ArgExprs.reserve(Args.size() - 1);
4938 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004939 QualType ArgTy = Args[I]->getType();
4940 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4941 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004942 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004943 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004944 ArgTy.getNonLValueExprType(S.Context),
4945 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004946 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004947 for (Expr &E : OpaqueArgExprs)
4948 ArgExprs.push_back(&E);
4949
Simon Pilgrim75c26882016-09-30 14:25:09 +00004950 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004951 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004952 EnterExpressionEvaluationContext Unevaluated(
4953 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004954 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4955 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4956 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4957 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4958 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004959 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004960 if (Init.Failed())
4961 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004962
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004963 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004964 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4965 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004966
Alp Toker73287bf2014-01-20 00:24:09 +00004967 if (Kind == clang::TT_IsConstructible)
4968 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004969
Eric Fiselier1af6c112018-01-12 00:09:37 +00004970 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4971 if (!T->isReferenceType())
4972 return false;
4973
4974 return !Init.isDirectReferenceBinding();
4975 }
4976
Alp Toker73287bf2014-01-20 00:24:09 +00004977 if (Kind == clang::TT_IsNothrowConstructible)
4978 return S.canThrow(Result.get()) == CT_Cannot;
4979
4980 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004981 // Under Objective-C ARC and Weak, if the destination has non-trivial
4982 // Objective-C lifetime, this is a non-trivial construction.
4983 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004984 return false;
4985
4986 // The initialization succeeded; now make sure there are no non-trivial
4987 // calls.
4988 return !Result.get()->hasNonTrivialCall(S.Context);
4989 }
4990
4991 llvm_unreachable("unhandled type trait");
4992 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004993 }
Alp Tokercbb90342013-12-13 20:49:58 +00004994 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004995 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004996
Douglas Gregor29c42f22012-02-24 07:38:34 +00004997 return false;
4998}
4999
Simon Pilgrim75c26882016-09-30 14:25:09 +00005000ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5001 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005002 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005003 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005004
Alp Toker95e7ff22014-01-01 05:57:51 +00005005 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5006 *this, Kind, KWLoc, Args[0]->getType()))
5007 return ExprError();
5008
Douglas Gregor29c42f22012-02-24 07:38:34 +00005009 bool Dependent = false;
5010 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5011 if (Args[I]->getType()->isDependentType()) {
5012 Dependent = true;
5013 break;
5014 }
5015 }
Alp Tokercbb90342013-12-13 20:49:58 +00005016
5017 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005018 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005019 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5020
5021 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5022 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005023}
5024
Alp Toker88f64e62013-12-13 21:19:30 +00005025ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5026 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005027 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005028 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005029 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005030
Douglas Gregor29c42f22012-02-24 07:38:34 +00005031 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5032 TypeSourceInfo *TInfo;
5033 QualType T = GetTypeFromParser(Args[I], &TInfo);
5034 if (!TInfo)
5035 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005036
5037 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005038 }
Alp Tokercbb90342013-12-13 20:49:58 +00005039
Douglas Gregor29c42f22012-02-24 07:38:34 +00005040 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5041}
5042
Alp Tokercbb90342013-12-13 20:49:58 +00005043static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5044 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005045 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5046 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005047
5048 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005049 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005050 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005051 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005052 // Base and Derived are not unions and name the same class type without
5053 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005054
John McCall388ef532011-01-28 22:02:36 +00005055 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005056 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005057 if (!rhsRecord || !lhsRecord) {
5058 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5059 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5060 if (!LHSObjTy || !RHSObjTy)
5061 return false;
5062
5063 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5064 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5065 if (!BaseInterface || !DerivedInterface)
5066 return false;
5067
5068 if (Self.RequireCompleteType(
5069 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5070 return false;
5071
5072 return BaseInterface->isSuperClassOf(DerivedInterface);
5073 }
John McCall388ef532011-01-28 22:02:36 +00005074
5075 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5076 == (lhsRecord == rhsRecord));
5077
5078 if (lhsRecord == rhsRecord)
5079 return !lhsRecord->getDecl()->isUnion();
5080
5081 // C++0x [meta.rel]p2:
5082 // If Base and Derived are class types and are different types
5083 // (ignoring possible cv-qualifiers) then Derived shall be a
5084 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005085 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005086 diag::err_incomplete_type_used_in_type_trait_expr))
5087 return false;
5088
5089 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5090 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5091 }
John Wiegley65497cc2011-04-27 23:09:49 +00005092 case BTT_IsSame:
5093 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005094 case BTT_TypeCompatible: {
5095 // GCC ignores cv-qualifiers on arrays for this builtin.
5096 Qualifiers LhsQuals, RhsQuals;
5097 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5098 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5099 return Self.Context.typesAreCompatible(Lhs, Rhs);
5100 }
John Wiegley65497cc2011-04-27 23:09:49 +00005101 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005102 case BTT_IsConvertibleTo: {
5103 // C++0x [meta.rel]p4:
5104 // Given the following function prototype:
5105 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005106 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005107 // typename add_rvalue_reference<T>::type create();
5108 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005109 // the predicate condition for a template specialization
5110 // is_convertible<From, To> shall be satisfied if and only if
5111 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005112 // well-formed, including any implicit conversions to the return
5113 // type of the function:
5114 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005115 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005116 // return create<From>();
5117 // }
5118 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005119 // Access checking is performed as if in a context unrelated to To and
5120 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005121 // of the return-statement (including conversions to the return type)
5122 // is considered.
5123 //
5124 // We model the initialization as a copy-initialization of a temporary
5125 // of the appropriate type, which for this expression is identical to the
5126 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005127
5128 // Functions aren't allowed to return function or array types.
5129 if (RhsT->isFunctionType() || RhsT->isArrayType())
5130 return false;
5131
5132 // A return statement in a void function must have void type.
5133 if (RhsT->isVoidType())
5134 return LhsT->isVoidType();
5135
5136 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005137 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005138 return false;
5139
5140 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005141 if (LhsT->isObjectType() || LhsT->isFunctionType())
5142 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005143
5144 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005145 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005146 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005147 Expr::getValueKindForType(LhsT));
5148 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005149 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005150 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005151
5152 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005153 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005154 EnterExpressionEvaluationContext Unevaluated(
5155 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005156 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5157 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005158 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005159 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005160 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005161
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005162 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005163 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5164 }
Alp Toker73287bf2014-01-20 00:24:09 +00005165
David Majnemerb3d96882016-05-23 17:21:55 +00005166 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005167 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005168 case BTT_IsTriviallyAssignable: {
5169 // C++11 [meta.unary.prop]p3:
5170 // is_trivially_assignable is defined as:
5171 // is_assignable<T, U>::value is true and the assignment, as defined by
5172 // is_assignable, is known to call no operation that is not trivial
5173 //
5174 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005175 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005176 // treated as an unevaluated operand (Clause 5).
5177 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005178 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005179 // void, or arrays of unknown bound.
5180 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005181 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005182 diag::err_incomplete_type_used_in_type_trait_expr))
5183 return false;
5184 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005185 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005186 diag::err_incomplete_type_used_in_type_trait_expr))
5187 return false;
5188
5189 // cv void is never assignable.
5190 if (LhsT->isVoidType() || RhsT->isVoidType())
5191 return false;
5192
Simon Pilgrim75c26882016-09-30 14:25:09 +00005193 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005194 // declval<U>().
5195 if (LhsT->isObjectType() || LhsT->isFunctionType())
5196 LhsT = Self.Context.getRValueReferenceType(LhsT);
5197 if (RhsT->isObjectType() || RhsT->isFunctionType())
5198 RhsT = Self.Context.getRValueReferenceType(RhsT);
5199 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5200 Expr::getValueKindForType(LhsT));
5201 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5202 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005203
5204 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005205 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005206 EnterExpressionEvaluationContext Unevaluated(
5207 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005208 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005209 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005210 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5211 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005212 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5213 return false;
5214
David Majnemerb3d96882016-05-23 17:21:55 +00005215 if (BTT == BTT_IsAssignable)
5216 return true;
5217
Alp Toker73287bf2014-01-20 00:24:09 +00005218 if (BTT == BTT_IsNothrowAssignable)
5219 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005220
Alp Toker73287bf2014-01-20 00:24:09 +00005221 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005222 // Under Objective-C ARC and Weak, if the destination has non-trivial
5223 // Objective-C lifetime, this is a non-trivial assignment.
5224 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005225 return false;
5226
5227 return !Result.get()->hasNonTrivialCall(Self.Context);
5228 }
5229
5230 llvm_unreachable("unhandled type trait");
5231 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005232 }
Alp Tokercbb90342013-12-13 20:49:58 +00005233 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005234 }
5235 llvm_unreachable("Unknown type trait or not implemented");
5236}
5237
John Wiegley6242b6a2011-04-28 00:16:57 +00005238ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5239 SourceLocation KWLoc,
5240 ParsedType Ty,
5241 Expr* DimExpr,
5242 SourceLocation RParen) {
5243 TypeSourceInfo *TSInfo;
5244 QualType T = GetTypeFromParser(Ty, &TSInfo);
5245 if (!TSInfo)
5246 TSInfo = Context.getTrivialTypeSourceInfo(T);
5247
5248 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5249}
5250
5251static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5252 QualType T, Expr *DimExpr,
5253 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005254 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005255
5256 switch(ATT) {
5257 case ATT_ArrayRank:
5258 if (T->isArrayType()) {
5259 unsigned Dim = 0;
5260 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5261 ++Dim;
5262 T = AT->getElementType();
5263 }
5264 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005265 }
John Wiegleyd3522222011-04-28 02:06:46 +00005266 return 0;
5267
John Wiegley6242b6a2011-04-28 00:16:57 +00005268 case ATT_ArrayExtent: {
5269 llvm::APSInt Value;
5270 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005271 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005272 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005273 false).isInvalid())
5274 return 0;
5275 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005276 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5277 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005278 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005279 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005280 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005281
5282 if (T->isArrayType()) {
5283 unsigned D = 0;
5284 bool Matched = false;
5285 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5286 if (Dim == D) {
5287 Matched = true;
5288 break;
5289 }
5290 ++D;
5291 T = AT->getElementType();
5292 }
5293
John Wiegleyd3522222011-04-28 02:06:46 +00005294 if (Matched && T->isArrayType()) {
5295 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5296 return CAT->getSize().getLimitedValue();
5297 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005298 }
John Wiegleyd3522222011-04-28 02:06:46 +00005299 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005300 }
5301 }
5302 llvm_unreachable("Unknown type trait or not implemented");
5303}
5304
5305ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5306 SourceLocation KWLoc,
5307 TypeSourceInfo *TSInfo,
5308 Expr* DimExpr,
5309 SourceLocation RParen) {
5310 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005311
Chandler Carruthc5276e52011-05-01 08:48:21 +00005312 // FIXME: This should likely be tracked as an APInt to remove any host
5313 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005314 uint64_t Value = 0;
5315 if (!T->isDependentType())
5316 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5317
Chandler Carruthc5276e52011-05-01 08:48:21 +00005318 // While the specification for these traits from the Embarcadero C++
5319 // compiler's documentation says the return type is 'unsigned int', Clang
5320 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5321 // compiler, there is no difference. On several other platforms this is an
5322 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005323 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5324 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005325}
5326
John Wiegleyf9f65842011-04-25 06:54:41 +00005327ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005328 SourceLocation KWLoc,
5329 Expr *Queried,
5330 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005331 // If error parsing the expression, ignore.
5332 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005333 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005334
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005335 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005336
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005337 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005338}
5339
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005340static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5341 switch (ET) {
5342 case ET_IsLValueExpr: return E->isLValue();
5343 case ET_IsRValueExpr: return E->isRValue();
5344 }
5345 llvm_unreachable("Expression trait not covered by switch");
5346}
5347
John Wiegleyf9f65842011-04-25 06:54:41 +00005348ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005349 SourceLocation KWLoc,
5350 Expr *Queried,
5351 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005352 if (Queried->isTypeDependent()) {
5353 // Delay type-checking for type-dependent expressions.
5354 } else if (Queried->getType()->isPlaceholderType()) {
5355 ExprResult PE = CheckPlaceholderExpr(Queried);
5356 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005357 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005358 }
5359
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005360 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005361
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005362 return new (Context)
5363 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005364}
5365
Richard Trieu82402a02011-09-15 21:56:47 +00005366QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005367 ExprValueKind &VK,
5368 SourceLocation Loc,
5369 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005370 assert(!LHS.get()->getType()->isPlaceholderType() &&
5371 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005372 "placeholders should have been weeded out by now");
5373
Richard Smith4baaa5a2016-12-03 01:14:32 +00005374 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5375 // temporary materialization conversion otherwise.
5376 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005377 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005378 else if (LHS.get()->isRValue())
5379 LHS = TemporaryMaterializationConversion(LHS.get());
5380 if (LHS.isInvalid())
5381 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005382
5383 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005384 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005385 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005386
Sebastian Redl5822f082009-02-07 20:10:22 +00005387 const char *OpSpelling = isIndirect ? "->*" : ".*";
5388 // C++ 5.5p2
5389 // The binary operator .* [p3: ->*] binds its second operand, which shall
5390 // be of type "pointer to member of T" (where T is a completely-defined
5391 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005392 QualType RHSType = RHS.get()->getType();
5393 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005394 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005395 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005396 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005397 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005398 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005399
Sebastian Redl5822f082009-02-07 20:10:22 +00005400 QualType Class(MemPtr->getClass(), 0);
5401
Douglas Gregord07ba342010-10-13 20:41:14 +00005402 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5403 // member pointer points must be completely-defined. However, there is no
5404 // reason for this semantic distinction, and the rule is not enforced by
5405 // other compilers. Therefore, we do not check this property, as it is
5406 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005407
Sebastian Redl5822f082009-02-07 20:10:22 +00005408 // C++ 5.5p2
5409 // [...] to its first operand, which shall be of class T or of a class of
5410 // which T is an unambiguous and accessible base class. [p3: a pointer to
5411 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005412 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005413 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005414 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5415 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005416 else {
5417 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005418 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005419 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005420 return QualType();
5421 }
5422 }
5423
Richard Trieu82402a02011-09-15 21:56:47 +00005424 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005425 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005426 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5427 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005428 return QualType();
5429 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005430
Richard Smith0f59cb32015-12-18 21:45:41 +00005431 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005432 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005433 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005434 return QualType();
5435 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005436
5437 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005438 if (CheckDerivedToBaseConversion(
5439 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005440 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005441 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005442 return QualType();
5443
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005444 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005445 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5446 if (isIndirect)
5447 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005448 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005449 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005450 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005451 }
5452
Richard Trieu82402a02011-09-15 21:56:47 +00005453 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005454 // Diagnose use of pointer-to-member type which when used as
5455 // the functional cast in a pointer-to-member expression.
5456 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5457 return QualType();
5458 }
John McCall7decc9e2010-11-18 06:31:45 +00005459
Sebastian Redl5822f082009-02-07 20:10:22 +00005460 // C++ 5.5p2
5461 // The result is an object or a function of the type specified by the
5462 // second operand.
5463 // The cv qualifiers are the union of those in the pointer and the left side,
5464 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005465 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005466 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005467
Douglas Gregor1d042092011-01-26 16:40:18 +00005468 // C++0x [expr.mptr.oper]p6:
5469 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470 // ill-formed if the second operand is a pointer to member function with
5471 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5472 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005473 // is a pointer to member function with ref-qualifier &&.
5474 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5475 switch (Proto->getRefQualifier()) {
5476 case RQ_None:
5477 // Do nothing
5478 break;
5479
5480 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005481 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005482 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5483 // is (exactly) 'const'.
5484 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005485 Diag(Loc, getLangOpts().CPlusPlus2a
5486 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5487 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5488 else
5489 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5490 << RHSType << 1 << LHS.get()->getSourceRange();
5491 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005492 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493
Douglas Gregor1d042092011-01-26 16:40:18 +00005494 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005495 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005496 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005497 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005498 break;
5499 }
5500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501
John McCall7decc9e2010-11-18 06:31:45 +00005502 // C++ [expr.mptr.oper]p6:
5503 // The result of a .* expression whose second operand is a pointer
5504 // to a data member is of the same value category as its
5505 // first operand. The result of a .* expression whose second
5506 // operand is a pointer to a member function is a prvalue. The
5507 // result of an ->* expression is an lvalue if its second operand
5508 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005509 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005510 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005511 return Context.BoundMemberTy;
5512 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005513 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005514 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005515 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005516 }
John McCall7decc9e2010-11-18 06:31:45 +00005517
Sebastian Redl5822f082009-02-07 20:10:22 +00005518 return Result;
5519}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005520
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005521/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005522///
5523/// This is part of the parameter validation for the ? operator. If either
5524/// value operand is a class type, the two operands are attempted to be
5525/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005526/// It returns true if the program is ill-formed and has already been diagnosed
5527/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005528static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5529 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005530 bool &HaveConversion,
5531 QualType &ToType) {
5532 HaveConversion = false;
5533 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005535 InitializationKind Kind =
5536 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005537 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005538 // The process for determining whether an operand expression E1 of type T1
5539 // can be converted to match an operand expression E2 of type T2 is defined
5540 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005541 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5542 // implicitly converted to type "lvalue reference to T2", subject to the
5543 // constraint that in the conversion the reference must bind directly to
5544 // an lvalue.
5545 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005546 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005547 // the constraint that the reference must bind directly.
5548 if (To->isLValue() || To->isXValue()) {
5549 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5550 : Self.Context.getRValueReferenceType(ToType);
5551
Douglas Gregor838fcc32010-03-26 20:14:36 +00005552 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005553
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005554 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005555 if (InitSeq.isDirectReferenceBinding()) {
5556 ToType = T;
5557 HaveConversion = true;
5558 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560
Douglas Gregor838fcc32010-03-26 20:14:36 +00005561 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005562 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005563 }
John McCall65eb8792010-02-25 01:37:24 +00005564
Sebastian Redl1a99f442009-04-16 17:51:27 +00005565 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5566 // -- if E1 and E2 have class type, and the underlying class types are
5567 // the same or one is a base class of the other:
5568 QualType FTy = From->getType();
5569 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005570 const RecordType *FRec = FTy->getAs<RecordType>();
5571 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005572 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005573 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5574 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5575 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005576 // E1 can be converted to match E2 if the class of T2 is the
5577 // same type as, or a base class of, the class of T1, and
5578 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005579 if (FRec == TRec || FDerivedFromT) {
5580 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005581 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005582 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005583 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005584 HaveConversion = true;
5585 return false;
5586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587
Douglas Gregor838fcc32010-03-26 20:14:36 +00005588 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005589 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005590 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregor838fcc32010-03-26 20:14:36 +00005593 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595
Douglas Gregor838fcc32010-03-26 20:14:36 +00005596 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5597 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005599 // an rvalue).
5600 //
5601 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5602 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005603 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
Douglas Gregor838fcc32010-03-26 20:14:36 +00005605 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005606 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005607 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005608 ToType = TTy;
5609 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005610 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005611
Sebastian Redl1a99f442009-04-16 17:51:27 +00005612 return false;
5613}
5614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005615/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005616///
5617/// This is part of the parameter validation for the ? operator. If either
5618/// value operand is a class type, overload resolution is used to find a
5619/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005620static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005621 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005622 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005623 OverloadCandidateSet CandidateSet(QuestionLoc,
5624 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005625 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005626 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005627
5628 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005629 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005630 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005631 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005632 ExprResult LHSRes = Self.PerformImplicitConversion(
5633 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5634 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005635 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005636 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005637 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005638
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005639 ExprResult RHSRes = Self.PerformImplicitConversion(
5640 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5641 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005642 if (RHSRes.isInvalid())
5643 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005644 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005645 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005646 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005647 return false;
John Wiegley01296292011-04-08 18:41:53 +00005648 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005649
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005650 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005651
5652 // Emit a better diagnostic if one of the expressions is a null pointer
5653 // constant and the other is a pointer type. In this case, the user most
5654 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005655 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005656 return true;
5657
5658 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005659 << LHS.get()->getType() << RHS.get()->getType()
5660 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005661 return true;
5662
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005663 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005664 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005665 << LHS.get()->getType() << RHS.get()->getType()
5666 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005667 // FIXME: Print the possible common types by printing the return types of
5668 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005669 break;
5670
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005671 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005672 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005673 }
5674 return true;
5675}
5676
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005677/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005678/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005679static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005680 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005681 InitializationKind Kind =
5682 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005683 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005684 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005685 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005686 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005687 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688
John Wiegley01296292011-04-08 18:41:53 +00005689 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005690 return false;
5691}
5692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005693/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005694///
5695/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5696/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005697QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5698 ExprResult &RHS, ExprValueKind &VK,
5699 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005700 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005701 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5702 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005703
Richard Smith45edb702012-08-07 22:06:48 +00005704 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005705 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005706 //
5707 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5708 // a is that of a integer vector with the same number of elements and
5709 // size as the vectors of b and c. If one of either b or c is a scalar
5710 // it is implicitly converted to match the type of the vector.
5711 // Otherwise the expression is ill-formed. If both b and c are scalars,
5712 // then b and c are checked and converted to the type of a if possible.
5713 // Unlike the OpenCL ?: operator, the expression is evaluated as
5714 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005715 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005716 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005717 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005718 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005719 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005720 }
5721
John McCall7decc9e2010-11-18 06:31:45 +00005722 // Assume r-value.
5723 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005724 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005725
Sebastian Redl1a99f442009-04-16 17:51:27 +00005726 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005727 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005728 return Context.DependentTy;
5729
Richard Smith45edb702012-08-07 22:06:48 +00005730 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005731 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005732 QualType LTy = LHS.get()->getType();
5733 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005734 bool LVoid = LTy->isVoidType();
5735 bool RVoid = RTy->isVoidType();
5736 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005737 // ... one of the following shall hold:
5738 // -- The second or the third operand (but not both) is a (possibly
5739 // parenthesized) throw-expression; the result is of the type
5740 // and value category of the other.
5741 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5742 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5743 if (LThrow != RThrow) {
5744 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5745 VK = NonThrow->getValueKind();
5746 // DR (no number yet): the result is a bit-field if the
5747 // non-throw-expression operand is a bit-field.
5748 OK = NonThrow->getObjectKind();
5749 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005750 }
5751
Sebastian Redl1a99f442009-04-16 17:51:27 +00005752 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005753 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005754 if (LVoid && RVoid)
5755 return Context.VoidTy;
5756
5757 // Neither holds, error.
5758 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5759 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005760 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005761 return QualType();
5762 }
5763
5764 // Neither is void.
5765
Richard Smithf2b084f2012-08-08 06:13:49 +00005766 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005767 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005768 // either has (cv) class type [...] an attempt is made to convert each of
5769 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005771 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005772 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005773 QualType L2RType, R2LType;
5774 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005775 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005776 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005777 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005778 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779
Sebastian Redl1a99f442009-04-16 17:51:27 +00005780 // If both can be converted, [...] the program is ill-formed.
5781 if (HaveL2R && HaveR2L) {
5782 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005783 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005784 return QualType();
5785 }
5786
5787 // If exactly one conversion is possible, that conversion is applied to
5788 // the chosen operand and the converted operands are used in place of the
5789 // original operands for the remainder of this section.
5790 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005791 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005792 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005793 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005794 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005795 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005796 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005797 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005798 }
5799 }
5800
Richard Smithf2b084f2012-08-08 06:13:49 +00005801 // C++11 [expr.cond]p3
5802 // if both are glvalues of the same value category and the same type except
5803 // for cv-qualification, an attempt is made to convert each of those
5804 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005805 // FIXME:
5806 // Resolving a defect in P0012R1: we extend this to cover all cases where
5807 // one of the operands is reference-compatible with the other, in order
5808 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005809 ExprValueKind LVK = LHS.get()->getValueKind();
5810 ExprValueKind RVK = RHS.get()->getValueKind();
5811 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005812 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005813 // DerivedToBase was already handled by the class-specific case above.
5814 // FIXME: Should we allow ObjC conversions here?
5815 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5816 if (CompareReferenceRelationship(
5817 QuestionLoc, LTy, RTy, DerivedToBase,
5818 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005819 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5820 // [...] subject to the constraint that the reference must bind
5821 // directly [...]
5822 !RHS.get()->refersToBitField() &&
5823 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005824 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005825 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005826 } else if (CompareReferenceRelationship(
5827 QuestionLoc, RTy, LTy, DerivedToBase,
5828 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005829 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5830 !LHS.get()->refersToBitField() &&
5831 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005832 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5833 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005834 }
5835 }
5836
5837 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005838 // If the second and third operands are glvalues of the same value
5839 // category and have the same type, the result is of that type and
5840 // value category and it is a bit-field if the second or the third
5841 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005842 // We only extend this to bitfields, not to the crazy other kinds of
5843 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005844 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005845 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005846 LHS.get()->isOrdinaryOrBitFieldObject() &&
5847 RHS.get()->isOrdinaryOrBitFieldObject()) {
5848 VK = LHS.get()->getValueKind();
5849 if (LHS.get()->getObjectKind() == OK_BitField ||
5850 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005851 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005852
5853 // If we have function pointer types, unify them anyway to unify their
5854 // exception specifications, if any.
5855 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5856 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005857 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005858 /*ConvertArgs*/false);
5859 LTy = Context.getQualifiedType(LTy, Qs);
5860
5861 assert(!LTy.isNull() && "failed to find composite pointer type for "
5862 "canonically equivalent function ptr types");
5863 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5864 }
5865
John McCall7decc9e2010-11-18 06:31:45 +00005866 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005867 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005868
Richard Smithf2b084f2012-08-08 06:13:49 +00005869 // C++11 [expr.cond]p5
5870 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005871 // do not have the same type, and either has (cv) class type, ...
5872 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5873 // ... overload resolution is used to determine the conversions (if any)
5874 // to be applied to the operands. If the overload resolution fails, the
5875 // program is ill-formed.
5876 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5877 return QualType();
5878 }
5879
Richard Smithf2b084f2012-08-08 06:13:49 +00005880 // C++11 [expr.cond]p6
5881 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005882 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005883 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5884 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005885 if (LHS.isInvalid() || RHS.isInvalid())
5886 return QualType();
5887 LTy = LHS.get()->getType();
5888 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005889
5890 // After those conversions, one of the following shall hold:
5891 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005892 // is of that type. If the operands have class type, the result
5893 // is a prvalue temporary of the result type, which is
5894 // copy-initialized from either the second operand or the third
5895 // operand depending on the value of the first operand.
5896 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5897 if (LTy->isRecordType()) {
5898 // The operands have class type. Make a temporary copy.
5899 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005900
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005901 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5902 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005903 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005904 if (LHSCopy.isInvalid())
5905 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
5907 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5908 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005909 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005910 if (RHSCopy.isInvalid())
5911 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
John Wiegley01296292011-04-08 18:41:53 +00005913 LHS = LHSCopy;
5914 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005915 }
5916
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005917 // If we have function pointer types, unify them anyway to unify their
5918 // exception specifications, if any.
5919 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5920 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5921 assert(!LTy.isNull() && "failed to find composite pointer type for "
5922 "canonically equivalent function ptr types");
5923 }
5924
Sebastian Redl1a99f442009-04-16 17:51:27 +00005925 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005926 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005927
Douglas Gregor46188682010-05-18 22:42:18 +00005928 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005930 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5931 /*AllowBothBool*/true,
5932 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005933
Sebastian Redl1a99f442009-04-16 17:51:27 +00005934 // -- The second and third operands have arithmetic or enumeration type;
5935 // the usual arithmetic conversions are performed to bring them to a
5936 // common type, and the result is of that type.
5937 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005938 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005939 if (LHS.isInvalid() || RHS.isInvalid())
5940 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005941 if (ResTy.isNull()) {
5942 Diag(QuestionLoc,
5943 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5944 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5945 return QualType();
5946 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005947
5948 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5949 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5950
5951 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005952 }
5953
5954 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005955 // type and the other is a null pointer constant, or both are null
5956 // pointer constants, at least one of which is non-integral; pointer
5957 // conversions and qualification conversions are performed to bring them
5958 // to their composite pointer type. The result is of the composite
5959 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005960 // -- The second and third operands have pointer to member type, or one has
5961 // pointer to member type and the other is a null pointer constant;
5962 // pointer to member conversions and qualification conversions are
5963 // performed to bring them to a common type, whose cv-qualification
5964 // shall match the cv-qualification of either the second or the third
5965 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005966 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5967 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005968 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005969
Douglas Gregor697a3912010-04-01 22:47:07 +00005970 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005971 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5972 if (!Composite.isNull())
5973 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005974
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005975 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005976 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005977 return QualType();
5978
Sebastian Redl1a99f442009-04-16 17:51:27 +00005979 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005980 << LHS.get()->getType() << RHS.get()->getType()
5981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005982 return QualType();
5983}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005984
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005985static FunctionProtoType::ExceptionSpecInfo
5986mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5987 FunctionProtoType::ExceptionSpecInfo ESI2,
5988 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5989 ExceptionSpecificationType EST1 = ESI1.Type;
5990 ExceptionSpecificationType EST2 = ESI2.Type;
5991
5992 // If either of them can throw anything, that is the result.
5993 if (EST1 == EST_None) return ESI1;
5994 if (EST2 == EST_None) return ESI2;
5995 if (EST1 == EST_MSAny) return ESI1;
5996 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005997 if (EST1 == EST_NoexceptFalse) return ESI1;
5998 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005999
6000 // If either of them is non-throwing, the result is the other.
6001 if (EST1 == EST_DynamicNone) return ESI2;
6002 if (EST2 == EST_DynamicNone) return ESI1;
6003 if (EST1 == EST_BasicNoexcept) return ESI2;
6004 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006005 if (EST1 == EST_NoexceptTrue) return ESI2;
6006 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006007
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006008 // If we're left with value-dependent computed noexcept expressions, we're
6009 // stuck. Before C++17, we can just drop the exception specification entirely,
6010 // since it's not actually part of the canonical type. And this should never
6011 // happen in C++17, because it would mean we were computing the composite
6012 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006013 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006014 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006015 "computing composite pointer type of dependent types");
6016 return FunctionProtoType::ExceptionSpecInfo();
6017 }
6018
6019 // Switch over the possibilities so that people adding new values know to
6020 // update this function.
6021 switch (EST1) {
6022 case EST_None:
6023 case EST_DynamicNone:
6024 case EST_MSAny:
6025 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006026 case EST_DependentNoexcept:
6027 case EST_NoexceptFalse:
6028 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006029 llvm_unreachable("handled above");
6030
6031 case EST_Dynamic: {
6032 // This is the fun case: both exception specifications are dynamic. Form
6033 // the union of the two lists.
6034 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6035 llvm::SmallPtrSet<QualType, 8> Found;
6036 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6037 for (QualType E : Exceptions)
6038 if (Found.insert(S.Context.getCanonicalType(E)).second)
6039 ExceptionTypeStorage.push_back(E);
6040
6041 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6042 Result.Exceptions = ExceptionTypeStorage;
6043 return Result;
6044 }
6045
6046 case EST_Unevaluated:
6047 case EST_Uninstantiated:
6048 case EST_Unparsed:
6049 llvm_unreachable("shouldn't see unresolved exception specifications here");
6050 }
6051
6052 llvm_unreachable("invalid ExceptionSpecificationType");
6053}
6054
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006055/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006056///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006057/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006058/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006059/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006060/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006061///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006062/// \param Loc The location of the operator requiring these two expressions to
6063/// be converted to the composite pointer type.
6064///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006065/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006066QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006067 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006068 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006069 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006070
6071 // C++1z [expr]p14:
6072 // The composite pointer type of two operands p1 and p2 having types T1
6073 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006074 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006075
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006076 // where at least one is a pointer or pointer to member type or
6077 // std::nullptr_t is:
6078 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6079 T1->isNullPtrType();
6080 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6081 T2->isNullPtrType();
6082 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006083 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006084
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006085 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6086 // This can't actually happen, following the standard, but we also use this
6087 // to implement the end of [expr.conv], which hits this case.
6088 //
6089 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6090 if (T1IsPointerLike &&
6091 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006092 if (ConvertArgs)
6093 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6094 ? CK_NullToMemberPointer
6095 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006096 return T1;
6097 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006098 if (T2IsPointerLike &&
6099 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006100 if (ConvertArgs)
6101 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6102 ? CK_NullToMemberPointer
6103 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006104 return T2;
6105 }
Mike Stump11289f42009-09-09 15:08:12 +00006106
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006107 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006108 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006109 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006110 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6111 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006112
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006113 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6114 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6115 // the union of cv1 and cv2;
6116 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6117 // "pointer to function", where the function types are otherwise the same,
6118 // "pointer to function";
6119 // FIXME: This rule is defective: it should also permit removing noexcept
6120 // from a pointer to member function. As a Clang extension, we also
6121 // permit removing 'noreturn', so we generalize this rule to;
6122 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6123 // "pointer to member function" and the pointee types can be unified
6124 // by a function pointer conversion, that conversion is applied
6125 // before checking the following rules.
6126 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6127 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6128 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6129 // respectively;
6130 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6131 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6132 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6133 // T1 or the cv-combined type of T1 and T2, respectively;
6134 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6135 // T2;
6136 //
6137 // If looked at in the right way, these bullets all do the same thing.
6138 // What we do here is, we build the two possible cv-combined types, and try
6139 // the conversions in both directions. If only one works, or if the two
6140 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006141 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006142 //
6143 // Note that this will fail to find a composite pointer type for "pointer
6144 // to void" and "pointer to function". We can't actually perform the final
6145 // conversion in this case, even though a composite pointer type formally
6146 // exists.
6147 SmallVector<unsigned, 4> QualifierUnion;
6148 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006149 QualType Composite1 = T1;
6150 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006151 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006152 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006153 const PointerType *Ptr1, *Ptr2;
6154 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6155 (Ptr2 = Composite2->getAs<PointerType>())) {
6156 Composite1 = Ptr1->getPointeeType();
6157 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006158
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006159 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006160 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006161 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006162 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006163
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006164 QualifierUnion.push_back(
6165 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006166 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006167 continue;
6168 }
Mike Stump11289f42009-09-09 15:08:12 +00006169
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006170 const MemberPointerType *MemPtr1, *MemPtr2;
6171 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6172 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6173 Composite1 = MemPtr1->getPointeeType();
6174 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006175
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006176 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006177 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006178 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006179 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006180
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006181 QualifierUnion.push_back(
6182 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6183 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6184 MemPtr2->getClass()));
6185 continue;
6186 }
Mike Stump11289f42009-09-09 15:08:12 +00006187
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006188 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006189
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006190 // Cannot unwrap any more types.
6191 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006192 }
Mike Stump11289f42009-09-09 15:08:12 +00006193
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006194 // Apply the function pointer conversion to unify the types. We've already
6195 // unwrapped down to the function types, and we want to merge rather than
6196 // just convert, so do this ourselves rather than calling
6197 // IsFunctionConversion.
6198 //
6199 // FIXME: In order to match the standard wording as closely as possible, we
6200 // currently only do this under a single level of pointers. Ideally, we would
6201 // allow this in general, and set NeedConstBefore to the relevant depth on
6202 // the side(s) where we changed anything.
6203 if (QualifierUnion.size() == 1) {
6204 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6205 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6206 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6207 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6208
6209 // The result is noreturn if both operands are.
6210 bool Noreturn =
6211 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6212 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6213 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6214
6215 // The result is nothrow if both operands are.
6216 SmallVector<QualType, 8> ExceptionTypeStorage;
6217 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6218 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6219 ExceptionTypeStorage);
6220
6221 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6222 FPT1->getParamTypes(), EPI1);
6223 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6224 FPT2->getParamTypes(), EPI2);
6225 }
6226 }
6227 }
6228
Richard Smith5e9746f2016-10-21 22:00:42 +00006229 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006230 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006231 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006232 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006233 for (unsigned I = 0; I != NeedConstBefore; ++I)
6234 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006235 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006237
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006238 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006239 auto MOC = MemberOfClass.rbegin();
6240 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6241 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6242 auto Classes = *MOC++;
6243 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006244 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006245 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006246 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006247 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006248 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006249 } else {
6250 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006251 Composite1 =
6252 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6253 Composite2 =
6254 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006255 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006256 }
6257
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006258 struct Conversion {
6259 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006260 Expr *&E1, *&E2;
6261 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006262 InitializedEntity Entity;
6263 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006264 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006265 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006266
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006267 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6268 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006269 : S(S), E1(E1), E2(E2), Composite(Composite),
6270 Entity(InitializedEntity::InitializeTemporary(Composite)),
6271 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6272 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6273 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006274
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006275 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006276 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6277 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006278 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006279 E1 = E1Result.getAs<Expr>();
6280
6281 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6282 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006283 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006284 E2 = E2Result.getAs<Expr>();
6285
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006286 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006287 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006288 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006289
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006290 // Try to convert to each composite pointer type.
6291 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006292 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6293 if (ConvertArgs && C1.perform())
6294 return QualType();
6295 return C1.Composite;
6296 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006297 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006298
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006299 if (C1.Viable == C2.Viable) {
6300 // Either Composite1 and Composite2 are viable and are different, or
6301 // neither is viable.
6302 // FIXME: How both be viable and different?
6303 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006304 }
6305
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006306 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006307 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6308 return QualType();
6309
6310 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006311}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006312
John McCalldadc5752010-08-24 06:29:42 +00006313ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006314 if (!E)
6315 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316
John McCall31168b02011-06-15 23:02:42 +00006317 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6318
6319 // If the result is a glvalue, we shouldn't bind it.
6320 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006321 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006322
John McCall31168b02011-06-15 23:02:42 +00006323 // In ARC, calls that return a retainable type can return retained,
6324 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006325 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006326 E->getType()->isObjCRetainableType()) {
6327
6328 bool ReturnsRetained;
6329
6330 // For actual calls, we compute this by examining the type of the
6331 // called value.
6332 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6333 Expr *Callee = Call->getCallee()->IgnoreParens();
6334 QualType T = Callee->getType();
6335
6336 if (T == Context.BoundMemberTy) {
6337 // Handle pointer-to-members.
6338 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6339 T = BinOp->getRHS()->getType();
6340 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6341 T = Mem->getMemberDecl()->getType();
6342 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006343
John McCall31168b02011-06-15 23:02:42 +00006344 if (const PointerType *Ptr = T->getAs<PointerType>())
6345 T = Ptr->getPointeeType();
6346 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6347 T = Ptr->getPointeeType();
6348 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6349 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006350
John McCall31168b02011-06-15 23:02:42 +00006351 const FunctionType *FTy = T->getAs<FunctionType>();
6352 assert(FTy && "call to value not of function type?");
6353 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6354
6355 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6356 // type always produce a +1 object.
6357 } else if (isa<StmtExpr>(E)) {
6358 ReturnsRetained = true;
6359
Ted Kremeneke65b0862012-03-06 20:05:56 +00006360 // We hit this case with the lambda conversion-to-block optimization;
6361 // we don't want any extra casts here.
6362 } else if (isa<CastExpr>(E) &&
6363 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006364 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006365
John McCall31168b02011-06-15 23:02:42 +00006366 // For message sends and property references, we try to find an
6367 // actual method. FIXME: we should infer retention by selector in
6368 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006369 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006370 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006371 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6372 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006373 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6374 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006375 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006376 // Don't do reclaims if we're using the zero-element array
6377 // constant.
6378 if (ArrayLit->getNumElements() == 0 &&
6379 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6380 return E;
6381
Ted Kremeneke65b0862012-03-06 20:05:56 +00006382 D = ArrayLit->getArrayWithObjectsMethod();
6383 } else if (ObjCDictionaryLiteral *DictLit
6384 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006385 // Don't do reclaims if we're using the zero-element dictionary
6386 // constant.
6387 if (DictLit->getNumElements() == 0 &&
6388 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6389 return E;
6390
Ted Kremeneke65b0862012-03-06 20:05:56 +00006391 D = DictLit->getDictWithObjectsMethod();
6392 }
John McCall31168b02011-06-15 23:02:42 +00006393
6394 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006395
6396 // Don't do reclaims on performSelector calls; despite their
6397 // return type, the invoked method doesn't necessarily actually
6398 // return an object.
6399 if (!ReturnsRetained &&
6400 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006401 return E;
John McCall31168b02011-06-15 23:02:42 +00006402 }
6403
John McCall16de4d22011-11-14 19:53:16 +00006404 // Don't reclaim an object of Class type.
6405 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006406 return E;
John McCall16de4d22011-11-14 19:53:16 +00006407
Tim Shen4a05bb82016-06-21 20:29:17 +00006408 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006409
John McCall2d637d22011-09-10 06:18:15 +00006410 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6411 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006412 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6413 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006414 }
6415
David Blaikiebbafb8a2012-03-11 07:00:24 +00006416 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006417 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006418
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006419 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6420 // a fast path for the common case that the type is directly a RecordType.
6421 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006422 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006423 while (!RT) {
6424 switch (T->getTypeClass()) {
6425 case Type::Record:
6426 RT = cast<RecordType>(T);
6427 break;
6428 case Type::ConstantArray:
6429 case Type::IncompleteArray:
6430 case Type::VariableArray:
6431 case Type::DependentSizedArray:
6432 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6433 break;
6434 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006435 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006436 }
6437 }
Mike Stump11289f42009-09-09 15:08:12 +00006438
Richard Smithfd555f62012-02-22 02:04:18 +00006439 // That should be enough to guarantee that this type is complete, if we're
6440 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006441 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006442 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006443 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006444
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006445 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6446 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006447 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006448
John McCall31168b02011-06-15 23:02:42 +00006449 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006450 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006451 CheckDestructorAccess(E->getExprLoc(), Destructor,
6452 PDiag(diag::err_access_dtor_temp)
6453 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006454 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6455 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006456
Richard Smithfd555f62012-02-22 02:04:18 +00006457 // If destructor is trivial, we can avoid the extra copy.
6458 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006459 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006460
John McCall28fc7092011-11-10 05:35:25 +00006461 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006462 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006463 }
Richard Smitheec915d62012-02-18 04:13:32 +00006464
6465 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006466 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6467
6468 if (IsDecltype)
6469 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6470
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006471 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006472}
6473
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474ExprResult
John McCall5d413782010-12-06 08:20:24 +00006475Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006476 if (SubExpr.isInvalid())
6477 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006478
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006479 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006480}
6481
John McCall28fc7092011-11-10 05:35:25 +00006482Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006483 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006484
Eli Friedman3bda6b12012-02-02 23:15:15 +00006485 CleanupVarDeclMarking();
6486
John McCall28fc7092011-11-10 05:35:25 +00006487 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6488 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006489 assert(Cleanup.exprNeedsCleanups() ||
6490 ExprCleanupObjects.size() == FirstCleanup);
6491 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006492 return SubExpr;
6493
Craig Topper5fc8fc22014-08-27 06:28:36 +00006494 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6495 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006496
Tim Shen4a05bb82016-06-21 20:29:17 +00006497 auto *E = ExprWithCleanups::Create(
6498 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006499 DiscardCleanupsInEvaluationContext();
6500
6501 return E;
6502}
6503
John McCall5d413782010-12-06 08:20:24 +00006504Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006505 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006506
Eli Friedman3bda6b12012-02-02 23:15:15 +00006507 CleanupVarDeclMarking();
6508
Tim Shen4a05bb82016-06-21 20:29:17 +00006509 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006510 return SubStmt;
6511
6512 // FIXME: In order to attach the temporaries, wrap the statement into
6513 // a StmtExpr; currently this is only used for asm statements.
6514 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6515 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006516 CompoundStmt *CompStmt = CompoundStmt::Create(
6517 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006518 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6519 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006520 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006521}
6522
Richard Smithfd555f62012-02-22 02:04:18 +00006523/// Process the expression contained within a decltype. For such expressions,
6524/// certain semantic checks on temporaries are delayed until this point, and
6525/// are omitted for the 'topmost' call in the decltype expression. If the
6526/// topmost call bound a temporary, strip that temporary off the expression.
6527ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006528 assert(ExprEvalContexts.back().ExprContext ==
6529 ExpressionEvaluationContextRecord::EK_Decltype &&
6530 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006531
6532 // C++11 [expr.call]p11:
6533 // If a function call is a prvalue of object type,
6534 // -- if the function call is either
6535 // -- the operand of a decltype-specifier, or
6536 // -- the right operand of a comma operator that is the operand of a
6537 // decltype-specifier,
6538 // a temporary object is not introduced for the prvalue.
6539
6540 // Recursively rebuild ParenExprs and comma expressions to strip out the
6541 // outermost CXXBindTemporaryExpr, if any.
6542 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6543 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6544 if (SubExpr.isInvalid())
6545 return ExprError();
6546 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006547 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006548 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006549 }
6550 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6551 if (BO->getOpcode() == BO_Comma) {
6552 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6553 if (RHS.isInvalid())
6554 return ExprError();
6555 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006556 return E;
6557 return new (Context) BinaryOperator(
6558 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006559 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006560 }
6561 }
6562
6563 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006564 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6565 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006566 if (TopCall)
6567 E = TopCall;
6568 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006569 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006570
6571 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006572 ExprEvalContexts.back().ExprContext =
6573 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006574
Richard Smithf86b0ae2012-07-28 19:54:11 +00006575 // In MS mode, don't perform any extra checking of call return types within a
6576 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006577 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006578 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006579
Richard Smithfd555f62012-02-22 02:04:18 +00006580 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006581 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6582 I != N; ++I) {
6583 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006584 if (Call == TopCall)
6585 continue;
6586
David Majnemerced8bdf2015-02-25 17:36:15 +00006587 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006588 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006589 return ExprError();
6590 }
6591
6592 // Now all relevant types are complete, check the destructors are accessible
6593 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006594 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6595 I != N; ++I) {
6596 CXXBindTemporaryExpr *Bind =
6597 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006598 if (Bind == TopBind)
6599 continue;
6600
6601 CXXTemporary *Temp = Bind->getTemporary();
6602
6603 CXXRecordDecl *RD =
6604 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6605 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6606 Temp->setDestructor(Destructor);
6607
Richard Smith7d847b12012-05-11 22:20:10 +00006608 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6609 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006610 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006611 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006612 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6613 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006614
6615 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006616 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006617 }
6618
6619 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006620 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006621}
6622
Richard Smith79c927b2013-11-06 19:31:51 +00006623/// Note a set of 'operator->' functions that were used for a member access.
6624static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006625 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006626 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6627 // FIXME: Make this configurable?
6628 unsigned Limit = 9;
6629 if (OperatorArrows.size() > Limit) {
6630 // Produce Limit-1 normal notes and one 'skipping' note.
6631 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6632 SkipCount = OperatorArrows.size() - (Limit - 1);
6633 }
6634
6635 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6636 if (I == SkipStart) {
6637 S.Diag(OperatorArrows[I]->getLocation(),
6638 diag::note_operator_arrows_suppressed)
6639 << SkipCount;
6640 I += SkipCount;
6641 } else {
6642 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6643 << OperatorArrows[I]->getCallResultType();
6644 ++I;
6645 }
6646 }
6647}
6648
Nico Weber964d3322015-02-16 22:35:45 +00006649ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6650 SourceLocation OpLoc,
6651 tok::TokenKind OpKind,
6652 ParsedType &ObjectType,
6653 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006654 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006655 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006656 if (Result.isInvalid()) return ExprError();
6657 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006658
John McCall526ab472011-10-25 17:37:35 +00006659 Result = CheckPlaceholderExpr(Base);
6660 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006661 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006662
John McCallb268a282010-08-23 23:25:46 +00006663 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006664 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006665 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006666 // If we have a pointer to a dependent type and are using the -> operator,
6667 // the object type is the type that the pointer points to. We might still
6668 // have enough information about that type to do something useful.
6669 if (OpKind == tok::arrow)
6670 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6671 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672
John McCallba7bf592010-08-24 05:47:05 +00006673 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006674 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006675 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006676 }
Mike Stump11289f42009-09-09 15:08:12 +00006677
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006678 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006679 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006680 // returned, with the original second operand.
6681 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006682 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006683 bool NoArrowOperatorFound = false;
6684 bool FirstIteration = true;
6685 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006686 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006687 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006688 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006689 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006691 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006692 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6693 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006694 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006695 noteOperatorArrows(*this, OperatorArrows);
6696 Diag(OpLoc, diag::note_operator_arrow_depth)
6697 << getLangOpts().ArrowDepth;
6698 return ExprError();
6699 }
6700
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006701 Result = BuildOverloadedArrowExpr(
6702 S, Base, OpLoc,
6703 // When in a template specialization and on the first loop iteration,
6704 // potentially give the default diagnostic (with the fixit in a
6705 // separate note) instead of having the error reported back to here
6706 // and giving a diagnostic with a fixit attached to the error itself.
6707 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006708 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006709 : &NoArrowOperatorFound);
6710 if (Result.isInvalid()) {
6711 if (NoArrowOperatorFound) {
6712 if (FirstIteration) {
6713 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006714 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006715 << FixItHint::CreateReplacement(OpLoc, ".");
6716 OpKind = tok::period;
6717 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006718 }
6719 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6720 << BaseType << Base->getSourceRange();
6721 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006722 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006723 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006724 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006725 }
6726 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006727 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006728 }
John McCallb268a282010-08-23 23:25:46 +00006729 Base = Result.get();
6730 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006731 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006732 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006733 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006734 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006735 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6736 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006737 return ExprError();
6738 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006739 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006740 }
Mike Stump11289f42009-09-09 15:08:12 +00006741
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006742 if (OpKind == tok::arrow &&
6743 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006744 BaseType = BaseType->getPointeeType();
6745 }
Mike Stump11289f42009-09-09 15:08:12 +00006746
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006747 // Objective-C properties allow "." access on Objective-C pointer types,
6748 // so adjust the base type to the object type itself.
6749 if (BaseType->isObjCObjectPointerType())
6750 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006751
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006752 // C++ [basic.lookup.classref]p2:
6753 // [...] If the type of the object expression is of pointer to scalar
6754 // type, the unqualified-id is looked up in the context of the complete
6755 // postfix-expression.
6756 //
6757 // This also indicates that we could be parsing a pseudo-destructor-name.
6758 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006759 // expressions or normal member (ivar or property) access expressions, and
6760 // it's legal for the type to be incomplete if this is a pseudo-destructor
6761 // call. We'll do more incomplete-type checks later in the lookup process,
6762 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006763 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006764 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006765 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006766 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006767 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006768 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006769 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006770 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
Douglas Gregor3024f072012-04-16 07:05:22 +00006773 // The object type must be complete (or dependent), or
6774 // C++11 [expr.prim.general]p3:
6775 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006776 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006777 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006778 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006779 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006780 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006781 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006783 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006784 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006785 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006786 // type C (or of pointer to a class type C), the unqualified-id is looked
6787 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006788 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006789 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006790}
6791
Simon Pilgrim75c26882016-09-30 14:25:09 +00006792static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006793 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006794 if (Base->hasPlaceholderType()) {
6795 ExprResult result = S.CheckPlaceholderExpr(Base);
6796 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006797 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006798 }
6799 ObjectType = Base->getType();
6800
David Blaikie1d578782011-12-16 16:03:09 +00006801 // C++ [expr.pseudo]p2:
6802 // The left-hand side of the dot operator shall be of scalar type. The
6803 // left-hand side of the arrow operator shall be of pointer to scalar type.
6804 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006805 // Note that this is rather different from the normal handling for the
6806 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006807 if (OpKind == tok::arrow) {
6808 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6809 ObjectType = Ptr->getPointeeType();
6810 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006811 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006812 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6813 << ObjectType << true
6814 << FixItHint::CreateReplacement(OpLoc, ".");
6815 if (S.isSFINAEContext())
6816 return true;
6817
6818 OpKind = tok::period;
6819 }
6820 }
6821
6822 return false;
6823}
6824
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006825/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006826/// pointer objects.
6827static bool
6828canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6829 QualType DestructedType) {
6830 // If this is a record type, check if its destructor is callable.
6831 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6832 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6833 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6834 return false;
6835 }
6836
6837 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6838 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6839 DestructedType->isVectorType();
6840}
6841
John McCalldadc5752010-08-24 06:29:42 +00006842ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006843 SourceLocation OpLoc,
6844 tok::TokenKind OpKind,
6845 const CXXScopeSpec &SS,
6846 TypeSourceInfo *ScopeTypeInfo,
6847 SourceLocation CCLoc,
6848 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006849 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006850 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851
Eli Friedman0ce4de42012-01-25 04:35:06 +00006852 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006853 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6854 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006855
Douglas Gregorc5c57342012-09-10 14:57:06 +00006856 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6857 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006858 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006859 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006860 else {
Nico Weber58829272012-01-23 05:50:57 +00006861 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6862 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006863 return ExprError();
6864 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006865 }
6866
6867 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006868 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006869 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006870 if (DestructedTypeInfo) {
6871 QualType DestructedType = DestructedTypeInfo->getType();
6872 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006873 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006874 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6875 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006876 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6877 // Foo *foo;
6878 // foo.~Foo();
6879 if (OpKind == tok::period && ObjectType->isPointerType() &&
6880 Context.hasSameUnqualifiedType(DestructedType,
6881 ObjectType->getPointeeType())) {
6882 auto Diagnostic =
6883 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6884 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006885
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006886 // Issue a fixit only when the destructor is valid.
6887 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6888 *this, DestructedType))
6889 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6890
6891 // Recover by setting the object type to the destructed type and the
6892 // operator to '->'.
6893 ObjectType = DestructedType;
6894 OpKind = tok::arrow;
6895 } else {
6896 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6897 << ObjectType << DestructedType << Base->getSourceRange()
6898 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6899
6900 // Recover by setting the destructed type to the object type.
6901 DestructedType = ObjectType;
6902 DestructedTypeInfo =
6903 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6904 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6905 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006906 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006907 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006908
John McCall31168b02011-06-15 23:02:42 +00006909 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6910 // Okay: just pretend that the user provided the correctly-qualified
6911 // type.
6912 } else {
6913 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6914 << ObjectType << DestructedType << Base->getSourceRange()
6915 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6916 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006917
John McCall31168b02011-06-15 23:02:42 +00006918 // Recover by setting the destructed type to the object type.
6919 DestructedType = ObjectType;
6920 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6921 DestructedTypeStart);
6922 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6923 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006924 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006926
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006927 // C++ [expr.pseudo]p2:
6928 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6929 // form
6930 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006931 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006932 //
6933 // shall designate the same scalar type.
6934 if (ScopeTypeInfo) {
6935 QualType ScopeType = ScopeTypeInfo->getType();
6936 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006937 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006938
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006939 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006940 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006941 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006942 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006944 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006945 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006946 }
6947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006948
John McCallb268a282010-08-23 23:25:46 +00006949 Expr *Result
6950 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6951 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006952 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006953 ScopeTypeInfo,
6954 CCLoc,
6955 TildeLoc,
6956 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
David Majnemerced8bdf2015-02-25 17:36:15 +00006958 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006959}
6960
John McCalldadc5752010-08-24 06:29:42 +00006961ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006962 SourceLocation OpLoc,
6963 tok::TokenKind OpKind,
6964 CXXScopeSpec &SS,
6965 UnqualifiedId &FirstTypeName,
6966 SourceLocation CCLoc,
6967 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006968 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006969 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6970 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006971 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006972 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6973 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006974 "Invalid second type name in pseudo-destructor");
6975
Eli Friedman0ce4de42012-01-25 04:35:06 +00006976 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006977 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6978 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006979
6980 // Compute the object type that we should use for name lookup purposes. Only
6981 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006982 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006983 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006984 if (ObjectType->isRecordType())
6985 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006986 else if (ObjectType->isDependentType())
6987 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989
6990 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006991 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006992 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006993 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006994 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006995 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006996 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006997 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006998 S, &SS, true, false, ObjectTypePtrForLookup,
6999 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007001 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7002 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007004 // couldn't find anything useful in scope. Just store the identifier and
7005 // it's location, and we'll perform (qualified) name lookup again at
7006 // template instantiation time.
7007 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7008 SecondTypeName.StartLocation);
7009 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007011 diag::err_pseudo_dtor_destructor_non_type)
7012 << SecondTypeName.Identifier << ObjectType;
7013 if (isSFINAEContext())
7014 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007015
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007016 // Recover by assuming we had the right type all along.
7017 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007018 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007019 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007020 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007021 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007022 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007023 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007024 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007025 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007026 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007027 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007028 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007029 TemplateId->TemplateNameLoc,
7030 TemplateId->LAngleLoc,
7031 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007032 TemplateId->RAngleLoc,
7033 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007034 if (T.isInvalid() || !T.get()) {
7035 // Recover by assuming we had the right type all along.
7036 DestructedType = ObjectType;
7037 } else
7038 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007040
7041 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007042 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007043 if (!DestructedType.isNull()) {
7044 if (!DestructedTypeInfo)
7045 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007046 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007047 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007049
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007050 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007051 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007052 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007053 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007054 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007055 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007056 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007057 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007058 S, &SS, true, false, ObjectTypePtrForLookup,
7059 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007060 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007062 diag::err_pseudo_dtor_destructor_non_type)
7063 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007064
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007065 if (isSFINAEContext())
7066 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007067
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007068 // Just drop this type. It's unnecessary anyway.
7069 ScopeType = QualType();
7070 } else
7071 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007072 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007073 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007074 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007075 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007076 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007077 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007078 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007079 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007080 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007081 TemplateId->TemplateNameLoc,
7082 TemplateId->LAngleLoc,
7083 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007084 TemplateId->RAngleLoc,
7085 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007086 if (T.isInvalid() || !T.get()) {
7087 // Recover by dropping this type.
7088 ScopeType = QualType();
7089 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007090 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007091 }
7092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Douglas Gregor90ad9222010-02-24 23:02:30 +00007094 if (!ScopeType.isNull() && !ScopeTypeInfo)
7095 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7096 FirstTypeName.StartLocation);
7097
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098
John McCallb268a282010-08-23 23:25:46 +00007099 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007100 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007101 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007102}
7103
David Blaikie1d578782011-12-16 16:03:09 +00007104ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7105 SourceLocation OpLoc,
7106 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007107 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007108 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007109 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007110 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7111 return ExprError();
7112
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007113 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7114 false);
David Blaikie1d578782011-12-16 16:03:09 +00007115
7116 TypeLocBuilder TLB;
7117 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7118 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7119 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7120 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7121
7122 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007123 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007124 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007125}
7126
John Wiegley01296292011-04-08 18:41:53 +00007127ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007128 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007129 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007130 // Convert the expression to match the conversion function's implicit object
7131 // parameter.
7132 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7133 FoundDecl, Method);
7134 if (Exp.isInvalid())
7135 return true;
7136
Eli Friedman98b01ed2012-03-01 04:01:32 +00007137 if (Method->getParent()->isLambda() &&
7138 Method->getConversionType()->isBlockPointerType()) {
7139 // This is a lambda coversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007140 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007141 Expr *SubE = E;
7142 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7143 if (CE && CE->getCastKind() == CK_NoOp)
7144 SubE = CE->getSubExpr();
7145 SubE = SubE->IgnoreParens();
7146 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7147 SubE = BE->getSubExpr();
7148 if (isa<LambdaExpr>(SubE)) {
7149 // For the conversion to block pointer on a lambda expression, we
7150 // construct a special BlockLiteral instead; this doesn't really make
7151 // a difference in ARC, but outside of ARC the resulting block literal
7152 // follows the normal lifetime rules for block literals instead of being
7153 // autoreleased.
7154 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007155 PushExpressionEvaluationContext(
7156 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007157 ExprResult BlockExp = BuildBlockForLambdaConversion(
7158 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007159 PopExpressionEvaluationContext();
7160
Richard Smith7ed5fb22018-07-27 17:13:18 +00007161 if (BlockExp.isInvalid())
7162 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7163 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007164 }
7165 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007166
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007167 MemberExpr *ME = new (Context) MemberExpr(
7168 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7169 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007170 if (HadMultipleCandidates)
7171 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007172 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007173
Alp Toker314cc812014-01-25 16:55:45 +00007174 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007175 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7176 ResultType = ResultType.getNonLValueExprType(Context);
7177
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007178 CXXMemberCallExpr *CE = new (Context) CXXMemberCallExpr(
7179 Context, ME, None, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007180
7181 if (CheckFunctionCall(Method, CE,
7182 Method->getType()->castAs<FunctionProtoType>()))
7183 return ExprError();
7184
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007185 return CE;
7186}
7187
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007188ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7189 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007190 // If the operand is an unresolved lookup expression, the expression is ill-
7191 // formed per [over.over]p1, because overloaded function names cannot be used
7192 // without arguments except in explicit contexts.
7193 ExprResult R = CheckPlaceholderExpr(Operand);
7194 if (R.isInvalid())
7195 return R;
7196
7197 // The operand may have been modified when checking the placeholder type.
7198 Operand = R.get();
7199
Richard Smith51ec0cf2017-02-21 01:17:38 +00007200 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007201 // The expression operand for noexcept is in an unevaluated expression
7202 // context, so side effects could result in unintended consequences.
7203 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7204 }
7205
Richard Smithf623c962012-04-17 00:58:00 +00007206 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007207 return new (Context)
7208 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007209}
7210
7211ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7212 Expr *Operand, SourceLocation RParen) {
7213 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007214}
7215
Eli Friedmanf798f652012-05-24 22:04:19 +00007216static bool IsSpecialDiscardedValue(Expr *E) {
7217 // In C++11, discarded-value expressions of a certain form are special,
7218 // according to [expr]p10:
7219 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7220 // expression is an lvalue of volatile-qualified type and it has
7221 // one of the following forms:
7222 E = E->IgnoreParens();
7223
Eli Friedmanc49c2262012-05-24 22:36:31 +00007224 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007225 if (isa<DeclRefExpr>(E))
7226 return true;
7227
Eli Friedmanc49c2262012-05-24 22:36:31 +00007228 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007229 if (isa<ArraySubscriptExpr>(E))
7230 return true;
7231
Eli Friedmanc49c2262012-05-24 22:36:31 +00007232 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007233 if (isa<MemberExpr>(E))
7234 return true;
7235
Eli Friedmanc49c2262012-05-24 22:36:31 +00007236 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007237 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7238 if (UO->getOpcode() == UO_Deref)
7239 return true;
7240
7241 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007242 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007243 if (BO->isPtrMemOp())
7244 return true;
7245
Eli Friedmanc49c2262012-05-24 22:36:31 +00007246 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007247 if (BO->getOpcode() == BO_Comma)
7248 return IsSpecialDiscardedValue(BO->getRHS());
7249 }
7250
Eli Friedmanc49c2262012-05-24 22:36:31 +00007251 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007252 // operands are one of the above, or
7253 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7254 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7255 IsSpecialDiscardedValue(CO->getFalseExpr());
7256 // The related edge case of "*x ?: *x".
7257 if (BinaryConditionalOperator *BCO =
7258 dyn_cast<BinaryConditionalOperator>(E)) {
7259 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7260 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7261 IsSpecialDiscardedValue(BCO->getFalseExpr());
7262 }
7263
7264 // Objective-C++ extensions to the rule.
7265 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7266 return true;
7267
7268 return false;
7269}
7270
John McCall34376a62010-12-04 03:47:34 +00007271/// Perform the conversions required for an expression used in a
7272/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007273ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007274 if (E->hasPlaceholderType()) {
7275 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007276 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007277 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007278 }
7279
John McCallfee942d2010-12-02 02:07:15 +00007280 // C99 6.3.2.1:
7281 // [Except in specific positions,] an lvalue that does not have
7282 // array type is converted to the value stored in the
7283 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007284 if (E->isRValue()) {
7285 // In C, function designators (i.e. expressions of function type)
7286 // are r-values, but we still want to do function-to-pointer decay
7287 // on them. This is both technically correct and convenient for
7288 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007289 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007290 return DefaultFunctionArrayConversion(E);
7291
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007292 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007293 }
John McCallfee942d2010-12-02 02:07:15 +00007294
Eli Friedmanf798f652012-05-24 22:04:19 +00007295 if (getLangOpts().CPlusPlus) {
7296 // The C++11 standard defines the notion of a discarded-value expression;
7297 // normally, we don't need to do anything to handle it, but if it is a
7298 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7299 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007300 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007301 E->getType().isVolatileQualified() &&
7302 IsSpecialDiscardedValue(E)) {
7303 ExprResult Res = DefaultLvalueConversion(E);
7304 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007305 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007306 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007307 }
Richard Smith122f88d2016-12-06 23:52:28 +00007308
7309 // C++1z:
7310 // If the expression is a prvalue after this optional conversion, the
7311 // temporary materialization conversion is applied.
7312 //
7313 // We skip this step: IR generation is able to synthesize the storage for
7314 // itself in the aggregate case, and adding the extra node to the AST is
7315 // just clutter.
7316 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7317 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007318 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007319 }
John McCall34376a62010-12-04 03:47:34 +00007320
7321 // GCC seems to also exclude expressions of incomplete enum type.
7322 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7323 if (!T->getDecl()->isComplete()) {
7324 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007325 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007326 return E;
John McCall34376a62010-12-04 03:47:34 +00007327 }
7328 }
7329
John Wiegley01296292011-04-08 18:41:53 +00007330 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7331 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007332 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007333 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007334
John McCallca61b652010-12-04 12:29:11 +00007335 if (!E->getType()->isVoidType())
7336 RequireCompleteType(E->getExprLoc(), E->getType(),
7337 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007338 return E;
John McCall34376a62010-12-04 03:47:34 +00007339}
7340
Faisal Valia17d19f2013-11-07 05:17:06 +00007341// If we can unambiguously determine whether Var can never be used
7342// in a constant expression, return true.
7343// - if the variable and its initializer are non-dependent, then
7344// we can unambiguously check if the variable is a constant expression.
7345// - if the initializer is not value dependent - we can determine whether
7346// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007347// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007348// never be a constant expression.
7349// - FXIME: if the initializer is dependent, we can still do some analysis and
7350// identify certain cases unambiguously as non-const by using a Visitor:
7351// - such as those that involve odr-use of a ParmVarDecl, involve a new
7352// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007353static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007354 ASTContext &Context) {
7355 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007356 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007357
7358 // If there is no initializer - this can not be a constant expression.
7359 if (!Var->getAnyInitializer(DefVD)) return true;
7360 assert(DefVD);
7361 if (DefVD->isWeak()) return false;
7362 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007363
Faisal Valia17d19f2013-11-07 05:17:06 +00007364 Expr *Init = cast<Expr>(Eval->Value);
7365
7366 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007367 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7368 // of value-dependent expressions, and use it here to determine whether the
7369 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007370 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007371 }
7372
Simon Pilgrim75c26882016-09-30 14:25:09 +00007373 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007374}
7375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007376/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007377/// that must be captured by any of its enclosing lambdas that are ready to
7378/// capture. If there is a lambda that can capture a nested
7379/// potential-capture, go ahead and do so. Also, check to see if any
7380/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007381/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007382
Faisal Valiab3d6462013-12-07 20:22:44 +00007383static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7384 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7385
Simon Pilgrim75c26882016-09-30 14:25:09 +00007386 assert(!S.isUnevaluatedContext());
7387 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007388#ifndef NDEBUG
7389 DeclContext *DC = S.CurContext;
7390 while (DC && isa<CapturedDecl>(DC))
7391 DC = DC->getParent();
7392 assert(
7393 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007394 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007395#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007396
7397 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7398
Faisal Valiab3d6462013-12-07 20:22:44 +00007399 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007400 // lambda (within a generic outer lambda), must be captured by an
7401 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007402 const unsigned NumPotentialCaptures =
7403 CurrentLSI->getNumPotentialVariableCaptures();
7404 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007405 Expr *VarExpr = nullptr;
7406 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007407 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007408 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007409 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007410 // need to check enclosing lambda's for speculative captures.
7411 // For e.g.:
7412 // Even though 'x' is not odr-used, it should be captured.
7413 // int test() {
7414 // const int x = 10;
7415 // auto L = [=](auto a) {
7416 // (void) +x + a;
7417 // };
7418 // }
7419 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007420 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007421 continue;
7422
7423 // If we have a capture-capable lambda for the variable, go ahead and
7424 // capture the variable in that lambda (and all its enclosing lambdas).
7425 if (const Optional<unsigned> Index =
7426 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007427 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007428 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7429 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7430 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007431 }
7432 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007433 VariableCanNeverBeAConstantExpression(Var, S.Context);
7434 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7435 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007436 // can not be used in a constant expression - which means
7437 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007438 // capture violation early, if the variable is un-captureable.
7439 // This is purely for diagnosing errors early. Otherwise, this
7440 // error would get diagnosed when the lambda becomes capture ready.
7441 QualType CaptureType, DeclRefType;
7442 SourceLocation ExprLoc = VarExpr->getExprLoc();
7443 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007444 /*EllipsisLoc*/ SourceLocation(),
7445 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007446 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007447 // We will never be able to capture this variable, and we need
7448 // to be able to in any and all instantiations, so diagnose it.
7449 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007450 /*EllipsisLoc*/ SourceLocation(),
7451 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007452 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007453 }
7454 }
7455 }
7456
Faisal Valiab3d6462013-12-07 20:22:44 +00007457 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007458 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007459 // If we have a capture-capable lambda for 'this', go ahead and capture
7460 // 'this' in that lambda (and all its enclosing lambdas).
7461 if (const Optional<unsigned> Index =
7462 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007463 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007464 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7465 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7466 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7467 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007468 }
7469 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007470
7471 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007472 CurrentLSI->clearPotentialCaptures();
7473}
7474
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007475static ExprResult attemptRecovery(Sema &SemaRef,
7476 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007477 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007478 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7479 Consumer.getLookupResult().getLookupKind());
7480 const CXXScopeSpec *SS = Consumer.getSS();
7481 CXXScopeSpec NewSS;
7482
7483 // Use an approprate CXXScopeSpec for building the expr.
7484 if (auto *NNS = TC.getCorrectionSpecifier())
7485 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7486 else if (SS && !TC.WillReplaceSpecifier())
7487 NewSS = *SS;
7488
Richard Smithde6d6c42015-12-29 19:43:10 +00007489 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007490 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007491 R.addDecl(ND);
7492 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007493 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007494 CXXRecordDecl *Record = nullptr;
7495 if (auto *NNS = TC.getCorrectionSpecifier())
7496 Record = NNS->getAsType()->getAsCXXRecordDecl();
7497 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007498 Record =
7499 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7500 if (Record)
7501 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007502
7503 // Detect and handle the case where the decl might be an implicit
7504 // member.
7505 bool MightBeImplicitMember;
7506 if (!Consumer.isAddressOfOperand())
7507 MightBeImplicitMember = true;
7508 else if (!NewSS.isEmpty())
7509 MightBeImplicitMember = false;
7510 else if (R.isOverloadedResult())
7511 MightBeImplicitMember = false;
7512 else if (R.isUnresolvableResult())
7513 MightBeImplicitMember = true;
7514 else
7515 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7516 isa<IndirectFieldDecl>(ND) ||
7517 isa<MSPropertyDecl>(ND);
7518
7519 if (MightBeImplicitMember)
7520 return SemaRef.BuildPossibleImplicitMemberExpr(
7521 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007522 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007523 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7524 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7525 Ivar->getIdentifier());
7526 }
7527 }
7528
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007529 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7530 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007531}
7532
Kaelyn Takata6c759512014-10-27 18:07:37 +00007533namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007534class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7535 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7536
7537public:
7538 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7539 : TypoExprs(TypoExprs) {}
7540 bool VisitTypoExpr(TypoExpr *TE) {
7541 TypoExprs.insert(TE);
7542 return true;
7543 }
7544};
7545
Kaelyn Takata6c759512014-10-27 18:07:37 +00007546class TransformTypos : public TreeTransform<TransformTypos> {
7547 typedef TreeTransform<TransformTypos> BaseTransform;
7548
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007549 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7550 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007551 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007552 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007553 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007554 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007555
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007556 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007557 /// If the TypoExprs were successfully corrected, then the diagnostics should
7558 /// suggest the corrections. Otherwise the diagnostics will not suggest
7559 /// anything (having been passed an empty TypoCorrection).
7560 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007561 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007562 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007563 if (State.DiagHandler) {
7564 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7565 ExprResult Replacement = TransformCache[TE];
7566
7567 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7568 // TypoCorrection, replacing the existing decls. This ensures the right
7569 // NamedDecl is used in diagnostics e.g. in the case where overload
7570 // resolution was used to select one from several possible decls that
7571 // had been stored in the TypoCorrection.
7572 if (auto *ND = getDeclFromExpr(
7573 Replacement.isInvalid() ? nullptr : Replacement.get()))
7574 TC.setCorrectionDecl(ND);
7575
7576 State.DiagHandler(TC);
7577 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007578 SemaRef.clearDelayedTypo(TE);
7579 }
7580 }
7581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007582 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007583 /// given combination of the other TypoExprs, retry those corrections against
7584 /// the next combination of substitutions for the other TypoExprs by advancing
7585 /// to the next potential correction of the second TypoExpr. For the second
7586 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7587 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7588 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7589 /// TransformCache). Returns true if there is still any untried combinations
7590 /// of corrections.
7591 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7592 for (auto TE : TypoExprs) {
7593 auto &State = SemaRef.getTypoExprState(TE);
7594 TransformCache.erase(TE);
7595 if (!State.Consumer->finished())
7596 return true;
7597 State.Consumer->resetCorrectionStream();
7598 }
7599 return false;
7600 }
7601
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007602 NamedDecl *getDeclFromExpr(Expr *E) {
7603 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7604 E = OverloadResolution[OE];
7605
7606 if (!E)
7607 return nullptr;
7608 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007609 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007610 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007611 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007612 // FIXME: Add any other expr types that could be be seen by the delayed typo
7613 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007614 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007615 return nullptr;
7616 }
7617
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007618 ExprResult TryTransform(Expr *E) {
7619 Sema::SFINAETrap Trap(SemaRef);
7620 ExprResult Res = TransformExpr(E);
7621 if (Trap.hasErrorOccurred() || Res.isInvalid())
7622 return ExprError();
7623
7624 return ExprFilter(Res.get());
7625 }
7626
Kaelyn Takata6c759512014-10-27 18:07:37 +00007627public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007628 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7629 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007630
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007631 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7632 MultiExprArg Args,
7633 SourceLocation RParenLoc,
7634 Expr *ExecConfig = nullptr) {
7635 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7636 RParenLoc, ExecConfig);
7637 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007638 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007639 Expr *ResultCall = Result.get();
7640 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7641 ResultCall = BE->getSubExpr();
7642 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7643 OverloadResolution[OE] = CE->getCallee();
7644 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007645 }
7646 return Result;
7647 }
7648
Kaelyn Takata6c759512014-10-27 18:07:37 +00007649 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7650
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007651 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7652
Kaelyn Takata6c759512014-10-27 18:07:37 +00007653 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007654 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007655 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007656 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007657
Kaelyn Takata6c759512014-10-27 18:07:37 +00007658 // Exit if either the transform was valid or if there were no TypoExprs
7659 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007660 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007661 !CheckAndAdvanceTypoExprCorrectionStreams())
7662 break;
7663 }
7664
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007665 // Ensure none of the TypoExprs have multiple typo correction candidates
7666 // with the same edit length that pass all the checks and filters.
7667 // TODO: Properly handle various permutations of possible corrections when
7668 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007669 // Also, disable typo correction while attempting the transform when
7670 // handling potentially ambiguous typo corrections as any new TypoExprs will
7671 // have been introduced by the application of one of the correction
7672 // candidates and add little to no value if corrected.
7673 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007674 while (!AmbiguousTypoExprs.empty()) {
7675 auto TE = AmbiguousTypoExprs.back();
7676 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007677 auto &State = SemaRef.getTypoExprState(TE);
7678 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007679 TransformCache.erase(TE);
7680 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007681 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007682 TransformCache.erase(TE);
7683 Res = ExprError();
7684 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007685 }
7686 AmbiguousTypoExprs.remove(TE);
7687 State.Consumer->restoreSavedPosition();
7688 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007689 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007690 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007691
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007692 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007693 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007694 FindTypoExprs(TypoExprs).TraverseStmt(E);
7695
Kaelyn Takata6c759512014-10-27 18:07:37 +00007696 EmitAllDiagnostics();
7697
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007698 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007699 }
7700
7701 ExprResult TransformTypoExpr(TypoExpr *E) {
7702 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7703 // cached transformation result if there is one and the TypoExpr isn't the
7704 // first one that was encountered.
7705 auto &CacheEntry = TransformCache[E];
7706 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7707 return CacheEntry;
7708 }
7709
7710 auto &State = SemaRef.getTypoExprState(E);
7711 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7712
7713 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7714 // typo correction and return it.
7715 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007716 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007717 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007718 // FIXME: If we would typo-correct to an invalid declaration, it's
7719 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007720 ExprResult NE = State.RecoveryHandler ?
7721 State.RecoveryHandler(SemaRef, E, TC) :
7722 attemptRecovery(SemaRef, *State.Consumer, TC);
7723 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007724 // Check whether there may be a second viable correction with the same
7725 // edit distance; if so, remember this TypoExpr may have an ambiguous
7726 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007727 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007728 if ((Next = State.Consumer->peekNextCorrection()) &&
7729 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7730 AmbiguousTypoExprs.insert(E);
7731 } else {
7732 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007733 }
7734 assert(!NE.isUnset() &&
7735 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007736 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007737 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007738 }
7739 return CacheEntry = ExprError();
7740 }
7741};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007742}
Faisal Valia17d19f2013-11-07 05:17:06 +00007743
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007744ExprResult
7745Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7746 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007747 // If the current evaluation context indicates there are uncorrected typos
7748 // and the current expression isn't guaranteed to not have typos, try to
7749 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007750 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007751 (E->isTypeDependent() || E->isValueDependent() ||
7752 E->isInstantiationDependent())) {
7753 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007754 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007755 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007756 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007757 ExprEvalContexts.back().NumTypos -= TyposResolved;
7758 return Result;
7759 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007760 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007761 }
7762 return E;
7763}
7764
Richard Smith945f8d32013-01-14 22:39:08 +00007765ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007766 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007767 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007768 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007769 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007770
7771 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007772 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007773
7774 // If we are an init-expression in a lambdas init-capture, we should not
7775 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007776 // containing full-expression is done).
7777 // template<class ... Ts> void test(Ts ... t) {
7778 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7779 // return a;
7780 // }() ...);
7781 // }
7782 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7783 // when we parse the lambda introducer, and teach capturing (but not
7784 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7785 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7786 // lambda where we've entered the introducer but not the body, or represent a
7787 // lambda where we've entered the body, depending on where the
7788 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007789 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007790 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007791 return ExprError();
7792
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007793 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007794 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007795 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007796 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007797 if (FullExpr.isInvalid())
7798 return ExprError();
7799 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007800
Richard Smith945f8d32013-01-14 22:39:08 +00007801 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007802 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007803 if (FullExpr.isInvalid())
7804 return ExprError();
7805
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007806 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007807 if (FullExpr.isInvalid())
7808 return ExprError();
7809 }
John Wiegley01296292011-04-08 18:41:53 +00007810
Kaelyn Takata49d84322014-11-11 23:26:56 +00007811 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7812 if (FullExpr.isInvalid())
7813 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007814
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007815 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007816
Simon Pilgrim75c26882016-09-30 14:25:09 +00007817 // At the end of this full expression (which could be a deeply nested
7818 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007819 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007820 // Consider the following code:
7821 // void f(int, int);
7822 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007823 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007824 // const int x = 10, y = 20;
7825 // auto L = [=](auto a) {
7826 // auto M = [=](auto b) {
7827 // f(x, b); <-- requires x to be captured by L and M
7828 // f(y, a); <-- requires y to be captured by L, but not all Ms
7829 // };
7830 // };
7831 // }
7832
Simon Pilgrim75c26882016-09-30 14:25:09 +00007833 // FIXME: Also consider what happens for something like this that involves
7834 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007835 // void f() {
7836 // const int n = 0;
7837 // auto L = [&](auto a) {
7838 // +n + ({ 0; a; });
7839 // };
7840 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007841 //
7842 // Here, we see +n, and then the full-expression 0; ends, so we don't
7843 // capture n (and instead remove it from our list of potential captures),
7844 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007845 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007846
Alexey Bataev31939e32016-11-11 12:36:20 +00007847 LambdaScopeInfo *const CurrentLSI =
7848 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007849 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007850 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007851 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007852 // By ensuring we are in the context of a lambda's call operator
7853 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007854 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007855 // PR, a proper fix would entail :
7856 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007857 // - Add to Sema an integer holding the smallest (outermost) scope
7858 // index that we are *lexically* within, and save/restore/set to
7859 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007860 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007861 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007862 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007863 DeclContext *DC = CurContext;
7864 while (DC && isa<CapturedDecl>(DC))
7865 DC = DC->getParent();
7866 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007867 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007868 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007869 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7870 *this);
John McCall5d413782010-12-06 08:20:24 +00007871 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007872}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007873
7874StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7875 if (!FullStmt) return StmtError();
7876
John McCall5d413782010-12-06 08:20:24 +00007877 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007878}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007879
Simon Pilgrim75c26882016-09-30 14:25:09 +00007880Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007881Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7882 CXXScopeSpec &SS,
7883 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007884 DeclarationName TargetName = TargetNameInfo.getName();
7885 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007886 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007887
Douglas Gregor43edb322011-10-24 22:31:10 +00007888 // If the name itself is dependent, then the result is dependent.
7889 if (TargetName.isDependentName())
7890 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007891
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007892 // Do the redeclaration lookup in the current scope.
7893 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7894 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007895 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007896 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007897
Douglas Gregor43edb322011-10-24 22:31:10 +00007898 switch (R.getResultKind()) {
7899 case LookupResult::Found:
7900 case LookupResult::FoundOverloaded:
7901 case LookupResult::FoundUnresolvedValue:
7902 case LookupResult::Ambiguous:
7903 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007904
Douglas Gregor43edb322011-10-24 22:31:10 +00007905 case LookupResult::NotFound:
7906 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007907
Douglas Gregor43edb322011-10-24 22:31:10 +00007908 case LookupResult::NotFoundInCurrentInstantiation:
7909 return IER_Dependent;
7910 }
David Blaikie8a40f702012-01-17 06:56:22 +00007911
7912 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007913}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007914
Simon Pilgrim75c26882016-09-30 14:25:09 +00007915Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007916Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7917 bool IsIfExists, CXXScopeSpec &SS,
7918 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007919 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007920
Richard Smith151c4562016-12-20 21:35:28 +00007921 // Check for an unexpanded parameter pack.
7922 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7923 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7924 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007925 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007926
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007927 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7928}