blob: d977ea3453885158f977812ed89aef8596ac54d2 [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,
85 Scope *S, CXXScopeSpec &SS) {
86 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
87 assert(CurClass && &II == CurClass->getIdentifier() &&
88 "not a constructor name");
89
90 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
91 return ParsedType();
92
93 // Find the injected-class-name declaration. Note that we make no attempt to
94 // diagnose cases where the injected-class-name is shadowed: the only
95 // declaration that can validly shadow the injected-class-name is a
96 // non-static data member, and if the class contains both a non-static data
97 // member and a constructor then it is ill-formed (we check that in
98 // CheckCompletedCXXClass).
99 CXXRecordDecl *InjectedClassName = nullptr;
100 for (NamedDecl *ND : CurClass->lookup(&II)) {
101 auto *RD = dyn_cast<CXXRecordDecl>(ND);
102 if (RD && RD->isInjectedClassName()) {
103 InjectedClassName = RD;
104 break;
105 }
106 }
107 assert(InjectedClassName && "couldn't find injected class name");
108
109 QualType T = Context.getTypeDeclType(InjectedClassName);
110 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
111 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
112
113 return ParsedType::make(T);
114}
115
John McCallba7bf592010-08-24 05:47:05 +0000116ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000117 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000118 SourceLocation NameLoc,
119 Scope *S, CXXScopeSpec &SS,
120 ParsedType ObjectTypePtr,
121 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000122 // Determine where to perform name lookup.
123
124 // FIXME: This area of the standard is very messy, and the current
125 // wording is rather unclear about which scopes we search for the
126 // destructor name; see core issues 399 and 555. Issue 399 in
127 // particular shows where the current description of destructor name
128 // lookup is completely out of line with existing practice, e.g.,
129 // this appears to be ill-formed:
130 //
131 // namespace N {
132 // template <typename T> struct S {
133 // ~S();
134 // };
135 // }
136 //
137 // void f(N::S<int>* s) {
138 // s->N::S<int>::~S();
139 // }
140 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000141 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000142 // For this reason, we're currently only doing the C++03 version of this
143 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000144 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000145 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000146 bool isDependent = false;
147 bool LookInScope = false;
148
Richard Smith64e033f2015-01-15 00:48:52 +0000149 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000150 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000151
Douglas Gregorfe17d252010-02-16 19:09:40 +0000152 // If we have an object type, it's because we are in a
153 // pseudo-destructor-expression or a member access expression, and
154 // we know what type we're looking for.
155 if (ObjectTypePtr)
156 SearchType = GetTypeFromParser(ObjectTypePtr);
157
158 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000159 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000160
Douglas Gregor46841e12010-02-23 00:15:22 +0000161 bool AlreadySearched = false;
162 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000163 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000164 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000165 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000166 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000167 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000168 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000169 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000170 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000171 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000172 // Here, we determine whether the code below is permitted to look at the
173 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000174 DeclContext *DC = computeDeclContext(SS, EnteringContext);
175 if (DC && DC->isFileContext()) {
176 AlreadySearched = true;
177 LookupCtx = DC;
178 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000179 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000180 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000181 LookInScope = true;
182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000183
Sebastian Redla771d222010-07-07 23:17:38 +0000184 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000186 if (AlreadySearched) {
187 // Nothing left to do.
188 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
189 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000190 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000191 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
192 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000193 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000194 LookupCtx = computeDeclContext(SearchType);
195 isDependent = SearchType->isDependentType();
196 } else {
197 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000198 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000199 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000200 } else if (ObjectTypePtr) {
201 // C++ [basic.lookup.classref]p3:
202 // If the unqualified-id is ~type-name, the type-name is looked up
203 // in the context of the entire postfix-expression. If the type T
204 // of the object expression is of a class type C, the type-name is
205 // also looked up in the scope of class C. At least one of the
206 // lookups shall find a name that refers to (possibly
207 // cv-qualified) T.
208 LookupCtx = computeDeclContext(SearchType);
209 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000210 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211 "Caller should have completed object type");
212
213 LookInScope = true;
214 } else {
215 // Perform lookup into the current scope (only).
216 LookInScope = true;
217 }
218
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000220 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
221 for (unsigned Step = 0; Step != 2; ++Step) {
222 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000223 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000224 // we're allowed to look there).
225 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000226 if (Step == 0 && LookupCtx) {
227 if (RequireCompleteDeclContext(SS, LookupCtx))
228 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000229 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000230 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000231 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000232 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000233 continue;
John McCallcb731542017-06-11 20:33:00 +0000234 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000235
236 // FIXME: Should we be suppressing ambiguities here?
237 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000238 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000239
240 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
241 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000242 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000243
244 if (SearchType.isNull() || SearchType->isDependentType() ||
245 Context.hasSameUnqualifiedType(T, SearchType)) {
246 // We found our type!
247
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(T,
249 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000251
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000252 if (!SearchType.isNull())
253 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000254 }
255
256 // If the name that we found is a class template name, and it is
257 // the same name as the template name in the last part of the
258 // nested-name-specifier (if present) or the object type, then
259 // this is the destructor for that class.
260 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000261 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000262 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
263 QualType MemberOfType;
264 if (SS.isSet()) {
265 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
266 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000267 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
268 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000269 }
270 }
271 if (MemberOfType.isNull())
272 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273
Douglas Gregorfe17d252010-02-16 19:09:40 +0000274 if (MemberOfType.isNull())
275 continue;
276
277 // We're referring into a class template specialization. If the
278 // class template we found is the same as the template being
279 // specialized, we found what we are looking for.
280 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
281 if (ClassTemplateSpecializationDecl *Spec
282 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
283 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
284 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000285 return CreateParsedType(
286 MemberOfType,
287 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000288 }
289
290 continue;
291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292
Douglas Gregorfe17d252010-02-16 19:09:40 +0000293 // We're referring to an unresolved class template
294 // specialization. Determine whether we class template we found
295 // is the same as the template being specialized or, if we don't
296 // know which template is being specialized, that it at least
297 // has the same name.
298 if (const TemplateSpecializationType *SpecType
299 = MemberOfType->getAs<TemplateSpecializationType>()) {
300 TemplateName SpecName = SpecType->getTemplateName();
301
302 // The class template we found is the same template being
303 // specialized.
304 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
305 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000306 return CreateParsedType(
307 MemberOfType,
308 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000309
310 continue;
311 }
312
313 // The class template we found has the same name as the
314 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000315 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000316 = SpecName.getAsDependentTemplateName()) {
317 if (DepTemplate->isIdentifier() &&
318 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000319 return CreateParsedType(
320 MemberOfType,
321 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
323 continue;
324 }
325 }
326 }
327 }
328
329 if (isDependent) {
330 // We didn't find our type, but that's okay: it's dependent
331 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000332
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000333 // FIXME: What if we have no nested-name-specifier?
334 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
335 SS.getWithLocInContext(Context),
336 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000337 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000338 }
339
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000340 if (NonMatchingTypeDecl) {
341 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
342 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
343 << T << SearchType;
344 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
345 << T;
346 } else if (ObjectTypePtr)
347 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000348 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000349 else {
350 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
351 diag::err_destructor_class_name);
352 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000353 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000354 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
355 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
356 Class->getNameAsString());
357 }
358 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000359
David Blaikieefdccaa2016-01-15 23:43:34 +0000360 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000361}
362
Richard Smithef2cd8f2017-02-08 20:39:08 +0000363ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
364 ParsedType ObjectType) {
365 if (DS.getTypeSpecType() == DeclSpec::TST_error)
366 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000367
Richard Smithef2cd8f2017-02-08 20:39:08 +0000368 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
369 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
370 return nullptr;
371 }
372
373 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
374 "unexpected type in getDestructorType");
375 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
376
377 // If we know the type of the object, check that the correct destructor
378 // type was named now; we can give better diagnostics this way.
379 QualType SearchType = GetTypeFromParser(ObjectType);
380 if (!SearchType.isNull() && !SearchType->isDependentType() &&
381 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000382 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
383 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000384 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000385 }
386
387 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000388}
389
Richard Smithd091dc12013-12-05 00:58:33 +0000390bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
391 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000392 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000393
394 if (!SS.isValid())
395 return false;
396
397 switch (SS.getScopeRep()->getKind()) {
398 case NestedNameSpecifier::Identifier:
399 case NestedNameSpecifier::TypeSpec:
400 case NestedNameSpecifier::TypeSpecWithTemplate:
401 // Per C++11 [over.literal]p2, literal operators can only be declared at
402 // namespace scope. Therefore, this unqualified-id cannot name anything.
403 // Reject it early, because we have no AST representation for this in the
404 // case where the scope is dependent.
405 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
406 << SS.getScopeRep();
407 return true;
408
409 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000410 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000411 case NestedNameSpecifier::Namespace:
412 case NestedNameSpecifier::NamespaceAlias:
413 return false;
414 }
415
416 llvm_unreachable("unknown nested name specifier kind");
417}
418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000419/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000420ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000421 SourceLocation TypeidLoc,
422 TypeSourceInfo *Operand,
423 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000424 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000426 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000428 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000429 Qualifiers Quals;
430 QualType T
431 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
432 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 if (T->getAs<RecordType>() &&
434 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
435 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436
David Majnemer6f3150a2014-11-21 21:09:12 +0000437 if (T->isVariablyModifiedType())
438 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
439
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
441 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000442}
443
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000444/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000445ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000446 SourceLocation TypeidLoc,
447 Expr *E,
448 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000449 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000451 if (E->getType()->isPlaceholderType()) {
452 ExprResult result = CheckPlaceholderExpr(E);
453 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000454 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000455 }
456
Douglas Gregor9da64192010-04-26 22:37:10 +0000457 QualType T = E->getType();
458 if (const RecordType *RecordT = T->getAs<RecordType>()) {
459 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
460 // C++ [expr.typeid]p3:
461 // [...] If the type of the expression is a class type, the class
462 // shall be completely-defined.
463 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
464 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465
Douglas Gregor9da64192010-04-26 22:37:10 +0000466 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000467 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 // polymorphic class type [...] [the] expression is an unevaluated
469 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000470 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000471 // The subexpression is potentially evaluated; switch the context
472 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000473 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000474 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000475 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000476
477 // We require a vtable to query the type at run time.
478 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000479 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000480 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482
Douglas Gregor9da64192010-04-26 22:37:10 +0000483 // C++ [expr.typeid]p4:
484 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485 // cv-qualified type, the result of the typeid expression refers to a
486 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000487 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000488 Qualifiers Quals;
489 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
490 if (!Context.hasSameType(T, UnqualT)) {
491 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000492 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000493 }
494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000495
David Majnemer6f3150a2014-11-21 21:09:12 +0000496 if (E->getType()->isVariablyModifiedType())
497 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
498 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000499 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000500 E->HasSideEffects(Context, WasEvaluated)) {
501 // The expression operand for typeid is in an unevaluated expression
502 // context, so side effects could result in unintended consequences.
503 Diag(E->getExprLoc(), WasEvaluated
504 ? diag::warn_side_effects_typeid
505 : diag::warn_side_effects_unevaluated_context);
506 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000507
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000508 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
509 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000510}
511
512/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000513ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000514Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
515 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000516 // OpenCL C++ 1.0 s2.9: typeid is not supported.
517 if (getLangOpts().OpenCLCPlusPlus) {
518 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
519 << "typeid");
520 }
521
Douglas Gregor9da64192010-04-26 22:37:10 +0000522 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000523 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000524 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000525
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000526 if (!CXXTypeInfoDecl) {
527 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
528 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
529 LookupQualifiedName(R, getStdNamespace());
530 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000531 // Microsoft's typeinfo doesn't have type_info in std but in the global
532 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000533 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000534 LookupQualifiedName(R, Context.getTranslationUnitDecl());
535 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
536 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000537 if (!CXXTypeInfoDecl)
538 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Nico Weber1b7f39d2012-05-20 01:27:21 +0000541 if (!getLangOpts().RTTI) {
542 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
543 }
544
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000545 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546
Douglas Gregor9da64192010-04-26 22:37:10 +0000547 if (isType) {
548 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000549 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000550 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
551 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000552 if (T.isNull())
553 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor9da64192010-04-26 22:37:10 +0000555 if (!TInfo)
556 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000557
Douglas Gregor9da64192010-04-26 22:37:10 +0000558 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000559 }
Mike Stump11289f42009-09-09 15:08:12 +0000560
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000562 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000563}
564
David Majnemer1dbc7a72016-03-27 04:46:07 +0000565/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
566/// a single GUID.
567static void
568getUuidAttrOfType(Sema &SemaRef, QualType QT,
569 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
570 // Optionally remove one level of pointer, reference or array indirection.
571 const Type *Ty = QT.getTypePtr();
572 if (QT->isPointerType() || QT->isReferenceType())
573 Ty = QT->getPointeeType().getTypePtr();
574 else if (QT->isArrayType())
575 Ty = Ty->getBaseElementTypeUnsafe();
576
Reid Klecknere516eab2016-12-13 18:58:09 +0000577 const auto *TD = Ty->getAsTagDecl();
578 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000579 return;
580
Reid Klecknere516eab2016-12-13 18:58:09 +0000581 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582 UuidAttrs.insert(Uuid);
583 return;
584 }
585
586 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000587 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000588 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
589 for (const TemplateArgument &TA : TAL.asArray()) {
590 const UuidAttr *UuidForTA = nullptr;
591 if (TA.getKind() == TemplateArgument::Type)
592 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
593 else if (TA.getKind() == TemplateArgument::Declaration)
594 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
595
596 if (UuidForTA)
597 UuidAttrs.insert(UuidForTA);
598 }
599 }
600}
601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000602/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000603ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
604 SourceLocation TypeidLoc,
605 TypeSourceInfo *Operand,
606 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000607 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000608 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000609 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
610 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
611 if (UuidAttrs.empty())
612 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
613 if (UuidAttrs.size() > 1)
614 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000615 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
David Majnemer2041b462016-03-28 03:19:50 +0000618 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000619 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000620}
621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000622/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
624 SourceLocation TypeidLoc,
625 Expr *E,
626 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000627 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000628 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000629 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
630 UuidStr = "00000000-0000-0000-0000-000000000000";
631 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000632 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
633 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
634 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000635 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000636 if (UuidAttrs.size() > 1)
637 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000638 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000639 }
Francois Pichetb7577652010-12-27 01:32:00 +0000640 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000641
David Majnemer2041b462016-03-28 03:19:50 +0000642 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000643 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000644}
645
646/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
647ExprResult
648Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
649 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000651 if (!MSVCGuidDecl) {
652 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
653 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
654 LookupQualifiedName(R, Context.getTranslationUnitDecl());
655 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
656 if (!MSVCGuidDecl)
657 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658 }
659
Francois Pichet9f4f2072010-09-08 12:20:18 +0000660 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Francois Pichet9f4f2072010-09-08 12:20:18 +0000662 if (isType) {
663 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000664 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000665 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
666 &TInfo);
667 if (T.isNull())
668 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Francois Pichet9f4f2072010-09-08 12:20:18 +0000670 if (!TInfo)
671 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
672
673 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
674 }
675
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000677 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
678}
679
Steve Naroff66356bd2007-09-16 14:56:35 +0000680/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000681ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000682Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000683 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000684 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000685 return new (Context)
686 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000687}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000688
Sebastian Redl576fd422009-05-10 18:38:11 +0000689/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000690ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000691Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000692 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000693}
694
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000695/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000696ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000697Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
698 bool IsThrownVarInScope = false;
699 if (Ex) {
700 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000701 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000702 // copy/move construction of a class object [...]
703 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000704 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000705 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000706 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000707 // innermost enclosing try-block (if there is one), the copy/move
708 // operation from the operand to the exception object (15.1) can be
709 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000710 // exception object
711 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
712 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
713 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
714 for( ; S; S = S->getParent()) {
715 if (S->isDeclScope(Var)) {
716 IsThrownVarInScope = true;
717 break;
718 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000719
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000720 if (S->getFlags() &
721 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
722 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
723 Scope::TryScope))
724 break;
725 }
726 }
727 }
728 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000729
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000730 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
731}
732
Simon Pilgrim75c26882016-09-30 14:25:09 +0000733ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000734 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000735 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000736 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +0000737 !getSourceManager().isInSystemHeader(OpLoc) &&
738 (!getLangOpts().OpenMPIsDevice ||
739 !getLangOpts().OpenMPHostCXXExceptions ||
740 isInOpenMPTargetExecutionDirective() ||
741 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000742 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000743
Justin Lebar2a8db342016-09-28 22:45:54 +0000744 // Exceptions aren't allowed in CUDA device code.
745 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000746 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
747 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000748
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000749 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
750 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
751
John Wiegley01296292011-04-08 18:41:53 +0000752 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000753 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
754 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000755 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000756
757 // Initialize the exception result. This implicitly weeds out
758 // abstract types or types with inaccessible copy constructors.
759
760 // C++0x [class.copymove]p31:
761 // When certain criteria are met, an implementation is allowed to omit the
762 // copy/move construction of a class object [...]
763 //
764 // - in a throw-expression, when the operand is the name of a
765 // non-volatile automatic object (other than a function or
766 // catch-clause
767 // parameter) whose scope does not extend beyond the end of the
768 // innermost enclosing try-block (if there is one), the copy/move
769 // operation from the operand to the exception object (15.1) can be
770 // omitted by constructing the automatic object directly into the
771 // exception object
772 const VarDecl *NRVOVariable = nullptr;
773 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000774 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000775
776 InitializedEntity Entity = InitializedEntity::InitializeException(
777 OpLoc, ExceptionObjectTy,
778 /*NRVO=*/NRVOVariable != nullptr);
779 ExprResult Res = PerformMoveOrCopyInitialization(
780 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
781 if (Res.isInvalid())
782 return ExprError();
783 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000784 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000785
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000786 return new (Context)
787 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000788}
789
David Majnemere7a818f2015-03-06 18:53:55 +0000790static void
791collectPublicBases(CXXRecordDecl *RD,
792 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
793 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
794 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
795 bool ParentIsPublic) {
796 for (const CXXBaseSpecifier &BS : RD->bases()) {
797 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
798 bool NewSubobject;
799 // Virtual bases constitute the same subobject. Non-virtual bases are
800 // always distinct subobjects.
801 if (BS.isVirtual())
802 NewSubobject = VBases.insert(BaseDecl).second;
803 else
804 NewSubobject = true;
805
806 if (NewSubobject)
807 ++SubobjectsSeen[BaseDecl];
808
809 // Only add subobjects which have public access throughout the entire chain.
810 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
811 if (PublicPath)
812 PublicSubobjectsSeen.insert(BaseDecl);
813
814 // Recurse on to each base subobject.
815 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
816 PublicPath);
817 }
818}
819
820static void getUnambiguousPublicSubobjects(
821 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
822 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
823 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
824 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
825 SubobjectsSeen[RD] = 1;
826 PublicSubobjectsSeen.insert(RD);
827 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
828 /*ParentIsPublic=*/true);
829
830 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
831 // Skip ambiguous objects.
832 if (SubobjectsSeen[PublicSubobject] > 1)
833 continue;
834
835 Objects.push_back(PublicSubobject);
836 }
837}
838
Sebastian Redl4de47b42009-04-27 20:27:31 +0000839/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000840bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
841 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000842 // If the type of the exception would be an incomplete type or a pointer
843 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000844 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000845 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000846 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000847 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000848 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000849 }
850 if (!isPointer || !Ty->isVoidType()) {
851 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000852 isPointer ? diag::err_throw_incomplete_ptr
853 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000854 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000855 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000856
David Majnemerd09a51c2015-03-03 01:50:05 +0000857 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000858 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000859 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000860 }
861
Eli Friedman91a3d272010-06-03 20:39:03 +0000862 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000863 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
864 if (!RD)
865 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000866
Douglas Gregor88d292c2010-05-13 16:44:06 +0000867 // If we are throwing a polymorphic class type or pointer thereof,
868 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000869 MarkVTableUsed(ThrowLoc, RD);
870
Eli Friedman36ebbec2010-10-12 20:32:36 +0000871 // If a pointer is thrown, the referenced object will not be destroyed.
872 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000873 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000874
Richard Smitheec915d62012-02-18 04:13:32 +0000875 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000876 if (!RD->hasIrrelevantDestructor()) {
877 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
878 MarkFunctionReferenced(E->getExprLoc(), Destructor);
879 CheckDestructorAccess(E->getExprLoc(), Destructor,
880 PDiag(diag::err_access_dtor_exception) << Ty);
881 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000882 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000883 }
884 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000885
David Majnemerdfa6d202015-03-11 18:36:39 +0000886 // The MSVC ABI creates a list of all types which can catch the exception
887 // object. This list also references the appropriate copy constructor to call
888 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000889 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000890 // We are only interested in the public, unambiguous bases contained within
891 // the exception object. Bases which are ambiguous or otherwise
892 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000893 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
894 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000895
David Majnemere7a818f2015-03-06 18:53:55 +0000896 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000897 // Attempt to lookup the copy constructor. Various pieces of machinery
898 // will spring into action, like template instantiation, which means this
899 // cannot be a simple walk of the class's decls. Instead, we must perform
900 // lookup and overload resolution.
901 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
902 if (!CD)
903 continue;
904
905 // Mark the constructor referenced as it is used by this throw expression.
906 MarkFunctionReferenced(E->getExprLoc(), CD);
907
908 // Skip this copy constructor if it is trivial, we don't need to record it
909 // in the catchable type data.
910 if (CD->isTrivial())
911 continue;
912
913 // The copy constructor is non-trivial, create a mapping from this class
914 // type to this constructor.
915 // N.B. The selection of copy constructor is not sensitive to this
916 // particular throw-site. Lookup will be performed at the catch-site to
917 // ensure that the copy constructor is, in fact, accessible (via
918 // friendship or any other means).
919 Context.addCopyConstructorForExceptionObject(Subobject, CD);
920
921 // We don't keep the instantiated default argument expressions around so
922 // we must rebuild them here.
923 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000924 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
925 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000926 }
927 }
928 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000929
David Majnemerba3e5ec2015-03-13 18:26:17 +0000930 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000931}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000932
Faisal Vali67b04462016-06-11 16:41:54 +0000933static QualType adjustCVQualifiersForCXXThisWithinLambda(
934 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
935 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
936
937 QualType ClassType = ThisTy->getPointeeType();
938 LambdaScopeInfo *CurLSI = nullptr;
939 DeclContext *CurDC = CurSemaContext;
940
941 // Iterate through the stack of lambdas starting from the innermost lambda to
942 // the outermost lambda, checking if '*this' is ever captured by copy - since
943 // that could change the cv-qualifiers of the '*this' object.
944 // The object referred to by '*this' starts out with the cv-qualifiers of its
945 // member function. We then start with the innermost lambda and iterate
946 // outward checking to see if any lambda performs a by-copy capture of '*this'
947 // - and if so, any nested lambda must respect the 'constness' of that
948 // capturing lamdbda's call operator.
949 //
950
Faisal Vali999f27e2017-05-02 20:56:34 +0000951 // Since the FunctionScopeInfo stack is representative of the lexical
952 // nesting of the lambda expressions during initial parsing (and is the best
953 // place for querying information about captures about lambdas that are
954 // partially processed) and perhaps during instantiation of function templates
955 // that contain lambda expressions that need to be transformed BUT not
956 // necessarily during instantiation of a nested generic lambda's function call
957 // operator (which might even be instantiated at the end of the TU) - at which
958 // time the DeclContext tree is mature enough to query capture information
959 // reliably - we use a two pronged approach to walk through all the lexically
960 // enclosing lambda expressions:
961 //
962 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
963 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
964 // enclosed by the call-operator of the LSI below it on the stack (while
965 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
966 // the stack represents the innermost lambda.
967 //
968 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
969 // represents a lambda's call operator. If it does, we must be instantiating
970 // a generic lambda's call operator (represented by the Current LSI, and
971 // should be the only scenario where an inconsistency between the LSI and the
972 // DeclContext should occur), so climb out the DeclContexts if they
973 // represent lambdas, while querying the corresponding closure types
974 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000975
Faisal Vali999f27e2017-05-02 20:56:34 +0000976 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000977 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000978 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
979 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
980 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000981 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
982 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000983
984 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000985 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000986
Faisal Vali67b04462016-06-11 16:41:54 +0000987 auto C = CurLSI->getCXXThisCapture();
988
989 if (C.isCopyCapture()) {
990 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
991 if (CurLSI->CallOperator->isConst())
992 ClassType.addConst();
993 return ASTCtx.getPointerType(ClassType);
994 }
995 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000996
997 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
998 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000999 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001000 assert(CurLSI && "While computing 'this' capture-type for a generic "
1001 "lambda, we must have a corresponding LambdaScopeInfo");
1002 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1003 "While computing 'this' capture-type for a generic lambda, when we "
1004 "run out of enclosing LSI's, yet the enclosing DC is a "
1005 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1006 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001007 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001008
Faisal Vali67b04462016-06-11 16:41:54 +00001009 auto IsThisCaptured =
1010 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1011 IsConst = false;
1012 IsByCopy = false;
1013 for (auto &&C : Closure->captures()) {
1014 if (C.capturesThis()) {
1015 if (C.getCaptureKind() == LCK_StarThis)
1016 IsByCopy = true;
1017 if (Closure->getLambdaCallOperator()->isConst())
1018 IsConst = true;
1019 return true;
1020 }
1021 }
1022 return false;
1023 };
1024
1025 bool IsByCopyCapture = false;
1026 bool IsConstCapture = false;
1027 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1028 while (Closure &&
1029 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1030 if (IsByCopyCapture) {
1031 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1032 if (IsConstCapture)
1033 ClassType.addConst();
1034 return ASTCtx.getPointerType(ClassType);
1035 }
1036 Closure = isLambdaCallOperator(Closure->getParent())
1037 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1038 : nullptr;
1039 }
1040 }
1041 return ASTCtx.getPointerType(ClassType);
1042}
1043
Eli Friedman73a04092012-01-07 04:59:52 +00001044QualType Sema::getCurrentThisType() {
1045 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001046 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001047
Richard Smith938f40b2011-06-11 17:19:42 +00001048 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1049 if (method && method->isInstance())
1050 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001051 }
Faisal Validc6b5962016-03-21 09:25:37 +00001052
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001053 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001054 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001055
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001056 assert(isa<CXXRecordDecl>(DC) &&
1057 "Trying to get 'this' type from static method?");
1058
1059 // This is a lambda call operator that is being instantiated as a default
1060 // initializer. DC must point to the enclosing class type, so we can recover
1061 // the 'this' type from it.
1062
1063 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1064 // There are no cv-qualifiers for 'this' within default initializers,
1065 // per [expr.prim.general]p4.
1066 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001067 }
Faisal Vali67b04462016-06-11 16:41:54 +00001068
1069 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1070 // might need to be adjusted if the lambda or any of its enclosing lambda's
1071 // captures '*this' by copy.
1072 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1073 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1074 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001075 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001076}
1077
Simon Pilgrim75c26882016-09-30 14:25:09 +00001078Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001079 Decl *ContextDecl,
1080 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001081 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001082 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1083{
1084 if (!Enabled || !ContextDecl)
1085 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001086
1087 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001088 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1089 Record = Template->getTemplatedDecl();
1090 else
1091 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001092
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001093 // We care only for CVR qualifiers here, so cut everything else.
1094 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001095 S.CXXThisTypeOverride
1096 = S.Context.getPointerType(
1097 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001098
Douglas Gregor3024f072012-04-16 07:05:22 +00001099 this->Enabled = true;
1100}
1101
1102
1103Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1104 if (Enabled) {
1105 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1106 }
1107}
1108
Faisal Validc6b5962016-03-21 09:25:37 +00001109static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1110 QualType ThisTy, SourceLocation Loc,
1111 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001112
Faisal Vali67b04462016-06-11 16:41:54 +00001113 QualType AdjustedThisTy = ThisTy;
1114 // The type of the corresponding data member (not a 'this' pointer if 'by
1115 // copy').
1116 QualType CaptureThisFieldTy = ThisTy;
1117 if (ByCopy) {
1118 // If we are capturing the object referred to by '*this' by copy, ignore any
1119 // cv qualifiers inherited from the type of the member function for the type
1120 // of the closure-type's corresponding data member and any use of 'this'.
1121 CaptureThisFieldTy = ThisTy->getPointeeType();
1122 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1123 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1124 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001125
Faisal Vali67b04462016-06-11 16:41:54 +00001126 FieldDecl *Field = FieldDecl::Create(
1127 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1128 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1129 ICIS_NoInit);
1130
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001131 Field->setImplicit(true);
1132 Field->setAccess(AS_private);
1133 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001134 Expr *This =
1135 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001136 if (ByCopy) {
1137 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1138 UO_Deref,
1139 This).get();
1140 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001141 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001142 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1143 InitializationSequence Init(S, Entity, InitKind, StarThis);
1144 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1145 if (ER.isInvalid()) return nullptr;
1146 return ER.get();
1147 }
1148 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001149}
1150
Simon Pilgrim75c26882016-09-30 14:25:09 +00001151bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001152 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1153 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001154 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001155 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001156 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001157
Faisal Validc6b5962016-03-21 09:25:37 +00001158 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001159
Reid Kleckner87a31802018-03-12 21:43:02 +00001160 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1161 ? *FunctionScopeIndexToStopAt
1162 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001163
Simon Pilgrim75c26882016-09-30 14:25:09 +00001164 // Check that we can capture the *enclosing object* (referred to by '*this')
1165 // by the capturing-entity/closure (lambda/block/etc) at
1166 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1167
1168 // Note: The *enclosing object* can only be captured by-value by a
1169 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001170 // [*this] { ... }.
1171 // Every other capture of the *enclosing object* results in its by-reference
1172 // capture.
1173
1174 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1175 // stack), we can capture the *enclosing object* only if:
1176 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1177 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001178 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001179 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001180 // -- or, there is some enclosing closure 'E' that has already captured the
1181 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001182 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001183 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001184 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001185
1186
Faisal Validc6b5962016-03-21 09:25:37 +00001187 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001188 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001189 if (CapturingScopeInfo *CSI =
1190 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1191 if (CSI->CXXThisCaptureIndex != 0) {
1192 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001193 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001194 break;
1195 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001196 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1197 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1198 // This context can't implicitly capture 'this'; fail out.
1199 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001200 Diag(Loc, diag::err_this_capture)
1201 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001202 return true;
1203 }
Eli Friedman20139d32012-01-11 02:36:31 +00001204 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001205 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001206 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001207 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001208 (Explicit && idx == MaxFunctionScopesIndex)) {
1209 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1210 // iteration through can be an explicit capture, all enclosing closures,
1211 // if any, must perform implicit captures.
1212
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001213 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001214 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001215 continue;
1216 }
Eli Friedman20139d32012-01-11 02:36:31 +00001217 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001218 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001219 Diag(Loc, diag::err_this_capture)
1220 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001221 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001222 }
Eli Friedman73a04092012-01-07 04:59:52 +00001223 break;
1224 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001225 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001226
1227 // If we got here, then the closure at MaxFunctionScopesIndex on the
1228 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1229 // (including implicit by-reference captures in any enclosing closures).
1230
1231 // In the loop below, respect the ByCopy flag only for the closure requesting
1232 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001233 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001234 // implicitly capturing the *enclosing object* by reference (see loop
1235 // above)).
1236 assert((!ByCopy ||
1237 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1238 "Only a lambda can capture the enclosing object (referred to by "
1239 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001240 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1241 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001242 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001243 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1244 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001245 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001246 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001247
Faisal Validc6b5962016-03-21 09:25:37 +00001248 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1249 // For lambda expressions, build a field and an initializing expression,
1250 // and capture the *enclosing object* by copy only if this is the first
1251 // iteration.
1252 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1253 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001254
Faisal Validc6b5962016-03-21 09:25:37 +00001255 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001256 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001257 ThisExpr =
1258 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1259 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001260
Faisal Validc6b5962016-03-21 09:25:37 +00001261 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001262 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001263 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001264 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001265}
1266
Richard Smith938f40b2011-06-11 17:19:42 +00001267ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001268 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1269 /// is a non-lvalue expression whose value is the address of the object for
1270 /// which the function is called.
1271
Douglas Gregor09deffa2011-10-18 16:47:30 +00001272 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001273 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001274
Eli Friedman73a04092012-01-07 04:59:52 +00001275 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001276 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001277}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001278
Douglas Gregor3024f072012-04-16 07:05:22 +00001279bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1280 // If we're outside the body of a member function, then we'll have a specified
1281 // type for 'this'.
1282 if (CXXThisTypeOverride.isNull())
1283 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001284
Douglas Gregor3024f072012-04-16 07:05:22 +00001285 // Determine whether we're looking into a class that's currently being
1286 // defined.
1287 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1288 return Class && Class->isBeingDefined();
1289}
1290
Vedant Kumara14a1f92018-01-17 18:53:51 +00001291/// Parse construction of a specified type.
1292/// Can be interpreted either as function-style casting ("int(x)")
1293/// or class type construction ("ClassType(x,y,z)")
1294/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001295ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001296Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001297 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001298 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001299 SourceLocation RParenOrBraceLoc,
1300 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001301 if (!TypeRep)
1302 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303
John McCall97513962010-01-15 18:39:57 +00001304 TypeSourceInfo *TInfo;
1305 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1306 if (!TInfo)
1307 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001308
Vedant Kumara14a1f92018-01-17 18:53:51 +00001309 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1310 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001311 // Avoid creating a non-type-dependent expression that contains typos.
1312 // Non-type-dependent expressions are liable to be discarded without
1313 // checking for embedded typos.
1314 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1315 !Result.get()->isTypeDependent())
1316 Result = CorrectDelayedTyposInExpr(Result.get());
1317 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001318}
1319
Douglas Gregor2b88c112010-09-08 00:15:04 +00001320ExprResult
1321Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001322 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001323 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001324 SourceLocation RParenOrBraceLoc,
1325 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001326 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001327 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001328
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001329 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001330 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1331 // directly. We work around this by dropping the locations of the braces.
1332 SourceRange Locs = ListInitialization
1333 ? SourceRange()
1334 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1335 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1336 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001337 }
1338
Richard Smith600b5262017-01-26 20:40:47 +00001339 assert((!ListInitialization ||
1340 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1341 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001342 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001343
Richard Smith60437622017-02-09 19:17:44 +00001344 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1345 InitializationKind Kind =
1346 Exprs.size()
1347 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001348 ? InitializationKind::CreateDirectList(
1349 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1350 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1351 RParenOrBraceLoc)
1352 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1353 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001354
1355 // C++1z [expr.type.conv]p1:
1356 // If the type is a placeholder for a deduced class type, [...perform class
1357 // template argument deduction...]
1358 DeducedType *Deduced = Ty->getContainedDeducedType();
1359 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1360 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1361 Kind, Exprs);
1362 if (Ty.isNull())
1363 return ExprError();
1364 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1365 }
1366
Douglas Gregordd04d332009-01-16 18:33:17 +00001367 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001368 // If the expression list is a parenthesized single expression, the type
1369 // conversion expression is equivalent (in definedness, and if defined in
1370 // meaning) to the corresponding cast expression.
1371 if (Exprs.size() == 1 && !ListInitialization &&
1372 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001373 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001374 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1375 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001376 }
1377
Richard Smith49a6b6e2017-03-24 01:14:25 +00001378 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001379 QualType ElemTy = Ty;
1380 if (Ty->isArrayType()) {
1381 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001382 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1383 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001384 ElemTy = Context.getBaseElementType(Ty);
1385 }
1386
Richard Smith49a6b6e2017-03-24 01:14:25 +00001387 // There doesn't seem to be an explicit rule against this but sanity demands
1388 // we only construct objects with object types.
1389 if (Ty->isFunctionType())
1390 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1391 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001392
Richard Smith49a6b6e2017-03-24 01:14:25 +00001393 // C++17 [expr.type.conv]p2:
1394 // If the type is cv void and the initializer is (), the expression is a
1395 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001396 if (!Ty->isVoidType() &&
1397 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001398 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001399 return ExprError();
1400
Richard Smith49a6b6e2017-03-24 01:14:25 +00001401 // Otherwise, the expression is a prvalue of the specified type whose
1402 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001403 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1404 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001405
Richard Smith49a6b6e2017-03-24 01:14:25 +00001406 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001407 return Result;
1408
1409 Expr *Inner = Result.get();
1410 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1411 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001412 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1413 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001414 // If we created a CXXTemporaryObjectExpr, that node also represents the
1415 // functional cast. Otherwise, create an explicit cast to represent
1416 // the syntactic form of a functional-style cast that was used here.
1417 //
1418 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1419 // would give a more consistent AST representation than using a
1420 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1421 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001422 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001423 SourceRange Locs = ListInitialization
1424 ? SourceRange()
1425 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001426 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001427 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1428 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001429 }
1430
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001431 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001432}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001433
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001434/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001435/// deallocation function.
1436static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001437 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1438 return Method->isUsualDeallocationFunction();
1439
1440 if (FD->getOverloadedOperator() != OO_Delete &&
1441 FD->getOverloadedOperator() != OO_Array_Delete)
1442 return false;
1443
1444 unsigned UsualParams = 1;
1445
1446 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1447 S.Context.hasSameUnqualifiedType(
1448 FD->getParamDecl(UsualParams)->getType(),
1449 S.Context.getSizeType()))
1450 ++UsualParams;
1451
1452 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1453 S.Context.hasSameUnqualifiedType(
1454 FD->getParamDecl(UsualParams)->getType(),
1455 S.Context.getTypeDeclType(S.getStdAlignValT())))
1456 ++UsualParams;
1457
1458 return UsualParams == FD->getNumParams();
1459}
1460
1461namespace {
1462 struct UsualDeallocFnInfo {
1463 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001464 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001465 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001466 Destroying(false), HasSizeT(false), HasAlignValT(false),
1467 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001468 // A function template declaration is never a usual deallocation function.
1469 if (!FD)
1470 return;
Richard Smith5b349582017-10-13 01:55:36 +00001471 unsigned NumBaseParams = 1;
1472 if (FD->isDestroyingOperatorDelete()) {
1473 Destroying = true;
1474 ++NumBaseParams;
1475 }
1476 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001477 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001478 else if (FD->getNumParams() == NumBaseParams + 1) {
1479 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001480 HasAlignValT = !HasSizeT;
1481 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001482
1483 // In CUDA, determine how much we'd like / dislike to call this.
1484 if (S.getLangOpts().CUDA)
1485 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1486 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001487 }
1488
Eric Fiselierfa752f22018-03-21 19:19:48 +00001489 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001490
Richard Smithf75dcbe2016-10-11 00:21:10 +00001491 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1492 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001493 // C++ P0722:
1494 // A destroying operator delete is preferred over a non-destroying
1495 // operator delete.
1496 if (Destroying != Other.Destroying)
1497 return Destroying;
1498
Richard Smithf75dcbe2016-10-11 00:21:10 +00001499 // C++17 [expr.delete]p10:
1500 // If the type has new-extended alignment, a function with a parameter
1501 // of type std::align_val_t is preferred; otherwise a function without
1502 // such a parameter is preferred
1503 if (HasAlignValT != Other.HasAlignValT)
1504 return HasAlignValT == WantAlign;
1505
1506 if (HasSizeT != Other.HasSizeT)
1507 return HasSizeT == WantSize;
1508
1509 // Use CUDA call preference as a tiebreaker.
1510 return CUDAPref > Other.CUDAPref;
1511 }
1512
Richard Smithb2f0f052016-10-10 18:54:32 +00001513 DeclAccessPair Found;
1514 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001515 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001516 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001517 };
1518}
1519
1520/// Determine whether a type has new-extended alignment. This may be called when
1521/// the type is incomplete (for a delete-expression with an incomplete pointee
1522/// type), in which case it will conservatively return false if the alignment is
1523/// not known.
1524static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1525 return S.getLangOpts().AlignedAllocation &&
1526 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1527 S.getASTContext().getTargetInfo().getNewAlign();
1528}
1529
1530/// Select the correct "usual" deallocation function to use from a selection of
1531/// deallocation functions (either global or class-scope).
1532static UsualDeallocFnInfo resolveDeallocationOverload(
1533 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1534 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1535 UsualDeallocFnInfo Best;
1536
Richard Smithb2f0f052016-10-10 18:54:32 +00001537 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001538 UsualDeallocFnInfo Info(S, I.getPair());
1539 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1540 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001541 continue;
1542
1543 if (!Best) {
1544 Best = Info;
1545 if (BestFns)
1546 BestFns->push_back(Info);
1547 continue;
1548 }
1549
Richard Smithf75dcbe2016-10-11 00:21:10 +00001550 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001551 continue;
1552
1553 // If more than one preferred function is found, all non-preferred
1554 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001555 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001556 BestFns->clear();
1557
1558 Best = Info;
1559 if (BestFns)
1560 BestFns->push_back(Info);
1561 }
1562
1563 return Best;
1564}
1565
1566/// Determine whether a given type is a class for which 'delete[]' would call
1567/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1568/// we need to store the array size (even if the type is
1569/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001570static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1571 QualType allocType) {
1572 const RecordType *record =
1573 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1574 if (!record) return false;
1575
1576 // Try to find an operator delete[] in class scope.
1577
1578 DeclarationName deleteName =
1579 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1580 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1581 S.LookupQualifiedName(ops, record->getDecl());
1582
1583 // We're just doing this for information.
1584 ops.suppressDiagnostics();
1585
1586 // Very likely: there's no operator delete[].
1587 if (ops.empty()) return false;
1588
1589 // If it's ambiguous, it should be illegal to call operator delete[]
1590 // on this thing, so it doesn't matter if we allocate extra space or not.
1591 if (ops.isAmbiguous()) return false;
1592
Richard Smithb2f0f052016-10-10 18:54:32 +00001593 // C++17 [expr.delete]p10:
1594 // If the deallocation functions have class scope, the one without a
1595 // parameter of type std::size_t is selected.
1596 auto Best = resolveDeallocationOverload(
1597 S, ops, /*WantSize*/false,
1598 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1599 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001600}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001602/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001603///
Sebastian Redld74dd492012-02-12 18:41:05 +00001604/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001605/// @code new (memory) int[size][4] @endcode
1606/// or
1607/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001608///
1609/// \param StartLoc The first location of the expression.
1610/// \param UseGlobal True if 'new' was prefixed with '::'.
1611/// \param PlacementLParen Opening paren of the placement arguments.
1612/// \param PlacementArgs Placement new arguments.
1613/// \param PlacementRParen Closing paren of the placement arguments.
1614/// \param TypeIdParens If the type is in parens, the source range.
1615/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001616/// \param Initializer The initializing expression or initializer-list, or null
1617/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001618ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001619Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001620 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001622 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001623 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001624 // If the specified type is an array, unwrap it and save the expression.
1625 if (D.getNumTypeObjects() > 0 &&
1626 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001627 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001628 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001629 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1630 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001631 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001632 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1633 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001634 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001635 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1636 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001637
Sebastian Redl351bb782008-12-02 14:43:59 +00001638 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001639 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001640 }
1641
Douglas Gregor73341c42009-09-11 00:18:58 +00001642 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001643 if (ArraySize) {
1644 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001645 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1646 break;
1647
1648 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1649 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001650 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001651 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001652 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1653 // shall be a converted constant expression (5.19) of type std::size_t
1654 // and shall evaluate to a strictly positive value.
1655 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1656 assert(IntWidth && "Builtin type of size 0?");
1657 llvm::APSInt Value(IntWidth);
1658 Array.NumElts
1659 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1660 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001661 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001662 } else {
1663 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001664 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001665 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001666 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001667 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001668 if (!Array.NumElts)
1669 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001670 }
1671 }
1672 }
1673 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001674
Craig Topperc3ec1492014-05-26 06:22:03 +00001675 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001676 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001677 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001678 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
Sebastian Redl6047f072012-02-16 12:22:20 +00001680 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001681 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001682 DirectInitRange = List->getSourceRange();
1683
David Blaikie7b97aef2012-11-07 00:12:38 +00001684 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001685 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001686 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001687 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001688 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001689 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001690 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001691 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001692 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001693 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001694}
1695
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001696static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1697 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001698 if (!Init)
1699 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001700 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1701 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001702 if (isa<ImplicitValueInitExpr>(Init))
1703 return true;
1704 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1705 return !CCE->isListInitialization() &&
1706 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001707 else if (Style == CXXNewExpr::ListInit) {
1708 assert(isa<InitListExpr>(Init) &&
1709 "Shouldn't create list CXXConstructExprs for arrays.");
1710 return true;
1711 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001712 return false;
1713}
1714
Akira Hatanakacae83f72017-06-29 18:48:40 +00001715// Emit a diagnostic if an aligned allocation/deallocation function that is not
1716// implemented in the standard library is selected.
1717static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1718 SourceLocation Loc, bool IsDelete,
1719 Sema &S) {
1720 if (!S.getLangOpts().AlignedAllocationUnavailable)
1721 return;
1722
1723 // Return if there is a definition.
1724 if (FD.isDefined())
1725 return;
1726
1727 bool IsAligned = false;
1728 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001729 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1730 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1731 S.getASTContext().getTargetInfo().getPlatformName());
1732
Akira Hatanakacae83f72017-06-29 18:48:40 +00001733 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001734 << IsDelete << FD.getType().getAsString() << OSName
1735 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001736 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1737 }
1738}
1739
John McCalldadc5752010-08-24 06:29:42 +00001740ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001741Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001742 SourceLocation PlacementLParen,
1743 MultiExprArg PlacementArgs,
1744 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001745 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001746 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001747 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001748 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001749 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001750 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001751 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001752 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001753
Sebastian Redl6047f072012-02-16 12:22:20 +00001754 CXXNewExpr::InitializationStyle initStyle;
1755 if (DirectInitRange.isValid()) {
1756 assert(Initializer && "Have parens but no initializer.");
1757 initStyle = CXXNewExpr::CallInit;
1758 } else if (Initializer && isa<InitListExpr>(Initializer))
1759 initStyle = CXXNewExpr::ListInit;
1760 else {
1761 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1762 isa<CXXConstructExpr>(Initializer)) &&
1763 "Initializer expression that cannot have been implicitly created.");
1764 initStyle = CXXNewExpr::NoInit;
1765 }
1766
1767 Expr **Inits = &Initializer;
1768 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001769 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1770 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1771 Inits = List->getExprs();
1772 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001773 }
1774
Richard Smith60437622017-02-09 19:17:44 +00001775 // C++11 [expr.new]p15:
1776 // A new-expression that creates an object of type T initializes that
1777 // object as follows:
1778 InitializationKind Kind
1779 // - If the new-initializer is omitted, the object is default-
1780 // initialized (8.5); if no initialization is performed,
1781 // the object has indeterminate value
1782 = initStyle == CXXNewExpr::NoInit
1783 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1784 // - Otherwise, the new-initializer is interpreted according to the
1785 // initialization rules of 8.5 for direct-initialization.
1786 : initStyle == CXXNewExpr::ListInit
Vedant Kumara14a1f92018-01-17 18:53:51 +00001787 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1788 Initializer->getLocStart(),
1789 Initializer->getLocEnd())
Richard Smith60437622017-02-09 19:17:44 +00001790 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1791 DirectInitRange.getBegin(),
1792 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001793
Richard Smith60437622017-02-09 19:17:44 +00001794 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1795 auto *Deduced = AllocType->getContainedDeducedType();
1796 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1797 if (ArraySize)
1798 return ExprError(Diag(ArraySize->getExprLoc(),
1799 diag::err_deduced_class_template_compound_type)
1800 << /*array*/ 2 << ArraySize->getSourceRange());
1801
1802 InitializedEntity Entity
1803 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1804 AllocType = DeduceTemplateSpecializationFromInitializer(
1805 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1806 if (AllocType.isNull())
1807 return ExprError();
1808 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001809 bool Braced = (initStyle == CXXNewExpr::ListInit);
1810 if (NumInits == 1) {
1811 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1812 Inits = p->getInits();
1813 NumInits = p->getNumInits();
1814 Braced = true;
1815 }
1816 }
1817
Sebastian Redl6047f072012-02-16 12:22:20 +00001818 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001819 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1820 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001821 if (NumInits > 1) {
1822 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001823 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001824 diag::err_auto_new_ctor_multiple_expressions)
1825 << AllocType << TypeRange);
1826 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001827 if (Braced && !getLangOpts().CPlusPlus17)
1828 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1829 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001830 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001831 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001832 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001833 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001834 << AllocType << Deduce->getType()
1835 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001836 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001837 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001838 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001839 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001840
Douglas Gregorcda95f42010-05-16 16:01:03 +00001841 // Per C++0x [expr.new]p5, the type being constructed may be a
1842 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001843 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001844 if (const ConstantArrayType *Array
1845 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001846 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1847 Context.getSizeType(),
1848 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001849 AllocType = Array->getElementType();
1850 }
1851 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001852
Douglas Gregor3999e152010-10-06 16:00:31 +00001853 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1854 return ExprError();
1855
Craig Topperc3ec1492014-05-26 06:22:03 +00001856 if (initStyle == CXXNewExpr::ListInit &&
1857 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001858 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1859 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001860 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001861 }
1862
Simon Pilgrim75c26882016-09-30 14:25:09 +00001863 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001864 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001865 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1866 AllocType->isObjCLifetimeType()) {
1867 AllocType = Context.getLifetimeQualifiedType(AllocType,
1868 AllocType->getObjCARCImplicitLifetime());
1869 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001870
John McCall31168b02011-06-15 23:02:42 +00001871 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001872
John McCall5e77d762013-04-16 07:28:30 +00001873 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1874 ExprResult result = CheckPlaceholderExpr(ArraySize);
1875 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001876 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001877 }
Richard Smith8dd34252012-02-04 07:07:42 +00001878 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1879 // integral or enumeration type with a non-negative value."
1880 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1881 // enumeration type, or a class type for which a single non-explicit
1882 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001883 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001884 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001885 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001886 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001887 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001888 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001889 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1890
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001891 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1892 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001893
Simon Pilgrim75c26882016-09-30 14:25:09 +00001894 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001895 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001896 // Diagnose the compatibility of this conversion.
1897 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1898 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001899 } else {
1900 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1901 protected:
1902 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001903
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001904 public:
1905 SizeConvertDiagnoser(Expr *ArraySize)
1906 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1907 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001908
1909 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1910 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001911 return S.Diag(Loc, diag::err_array_size_not_integral)
1912 << S.getLangOpts().CPlusPlus11 << T;
1913 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001914
1915 SemaDiagnosticBuilder diagnoseIncomplete(
1916 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001917 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1918 << T << ArraySize->getSourceRange();
1919 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001920
1921 SemaDiagnosticBuilder diagnoseExplicitConv(
1922 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001923 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1924 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001925
1926 SemaDiagnosticBuilder noteExplicitConv(
1927 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001928 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1929 << ConvTy->isEnumeralType() << ConvTy;
1930 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001931
1932 SemaDiagnosticBuilder diagnoseAmbiguous(
1933 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001934 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1935 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001936
1937 SemaDiagnosticBuilder noteAmbiguous(
1938 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001939 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1940 << ConvTy->isEnumeralType() << ConvTy;
1941 }
Richard Smithccc11812013-05-21 19:05:48 +00001942
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001943 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1944 QualType T,
1945 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001946 return S.Diag(Loc,
1947 S.getLangOpts().CPlusPlus11
1948 ? diag::warn_cxx98_compat_array_size_conversion
1949 : diag::ext_array_size_conversion)
1950 << T << ConvTy->isEnumeralType() << ConvTy;
1951 }
1952 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001953
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001954 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1955 SizeDiagnoser);
1956 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001957 if (ConvertedSize.isInvalid())
1958 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001960 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001961 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001962
Douglas Gregor0bf31402010-10-08 23:50:27 +00001963 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001964 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001966 // C++98 [expr.new]p7:
1967 // The expression in a direct-new-declarator shall have integral type
1968 // with a non-negative value.
1969 //
Richard Smith0511d232016-10-05 22:41:02 +00001970 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1971 // per CWG1464. Otherwise, if it's not a constant, we must have an
1972 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001973 if (!ArraySize->isValueDependent()) {
1974 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001975 // We've already performed any required implicit conversion to integer or
1976 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001977 // FIXME: Per CWG1464, we are required to check the value prior to
1978 // converting to size_t. This will never find a negative array size in
1979 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001980 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001981 if (Value.isSigned() && Value.isNegative()) {
1982 return ExprError(Diag(ArraySize->getLocStart(),
1983 diag::err_typecheck_negative_array_size)
1984 << ArraySize->getSourceRange());
1985 }
1986
1987 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001988 unsigned ActiveSizeBits =
1989 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001990 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1991 return ExprError(Diag(ArraySize->getLocStart(),
1992 diag::err_array_too_large)
1993 << Value.toString(10)
1994 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001995 }
Richard Smith0511d232016-10-05 22:41:02 +00001996
1997 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001998 } else if (TypeIdParens.isValid()) {
1999 // Can't have dynamic array size when the type-id is in parentheses.
2000 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
2001 << ArraySize->getSourceRange()
2002 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2003 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
Douglas Gregorf2753b32010-07-13 15:54:32 +00002005 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002006 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
John McCall036f2f62011-05-15 07:14:44 +00002009 // Note that we do *not* convert the argument in any way. It can
2010 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002011 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002012
Craig Topperc3ec1492014-05-26 06:22:03 +00002013 FunctionDecl *OperatorNew = nullptr;
2014 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002015 unsigned Alignment =
2016 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2017 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2018 bool PassAlignment = getLangOpts().AlignedAllocation &&
2019 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020
Brian Gesiakcb024022018-04-01 22:59:22 +00002021 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002022 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002023 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002024 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002025 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002026 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002027 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002028 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002029
2030 // If this is an array allocation, compute whether the usual array
2031 // deallocation function for the type has a size_t parameter.
2032 bool UsualArrayDeleteWantsSize = false;
2033 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002034 UsualArrayDeleteWantsSize =
2035 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002036
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002037 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002038 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002040 OperatorNew->getType()->getAs<FunctionProtoType>();
2041 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2042 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043
Richard Smithd6f9e732014-05-13 19:56:21 +00002044 // We've already converted the placement args, just fill in any default
2045 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002046 // argument. Skip the second parameter too if we're passing in the
2047 // alignment; we've already filled it in.
2048 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2049 PassAlignment ? 2 : 1, PlacementArgs,
2050 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002051 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002053 if (!AllPlaceArgs.empty())
2054 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002055
Richard Smithd6f9e732014-05-13 19:56:21 +00002056 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002057 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002058
2059 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060
Richard Smithb2f0f052016-10-10 18:54:32 +00002061 // Warn if the type is over-aligned and is being allocated by (unaligned)
2062 // global operator new.
2063 if (PlacementArgs.empty() && !PassAlignment &&
2064 (OperatorNew->isImplicit() ||
2065 (OperatorNew->getLocStart().isValid() &&
2066 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2067 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002068 Diag(StartLoc, diag::warn_overaligned_type)
2069 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002070 << unsigned(Alignment / Context.getCharWidth())
2071 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002072 }
2073 }
2074
Sebastian Redl6047f072012-02-16 12:22:20 +00002075 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002076 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2077 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002078 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2079 SourceRange InitRange(Inits[0]->getLocStart(),
2080 Inits[NumInits - 1]->getLocEnd());
2081 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2082 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002083 }
2084
Richard Smithdd2ca572012-11-26 08:32:48 +00002085 // If we can perform the initialization, and we've not already done so,
2086 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002087 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002088 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002089 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002090 // The type we initialize is the complete type, including the array bound.
2091 QualType InitType;
2092 if (KnownArraySize)
2093 InitType = Context.getConstantArrayType(
2094 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2095 *KnownArraySize),
2096 ArrayType::Normal, 0);
2097 else if (ArraySize)
2098 InitType =
2099 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2100 else
2101 InitType = AllocType;
2102
Douglas Gregor85dabae2009-12-16 01:38:02 +00002103 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002104 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002105 InitializationSequence InitSeq(*this, Entity, Kind,
2106 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002108 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002109 if (FullInit.isInvalid())
2110 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111
Sebastian Redl6047f072012-02-16 12:22:20 +00002112 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2113 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002114 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002115 if (CXXBindTemporaryExpr *Binder =
2116 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002117 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002119 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor6642ca22010-02-26 05:06:18 +00002122 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002123 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002124 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2125 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002126 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002127 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002128 }
2129 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002130 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2131 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002132 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002133 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002134 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002135
John McCall928a2572011-07-13 20:12:57 +00002136 // C++0x [expr.new]p17:
2137 // If the new expression creates an array of objects of class type,
2138 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002139 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2140 if (ArraySize && !BaseAllocType->isDependentType()) {
2141 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2142 if (CXXDestructorDecl *dtor = LookupDestructor(
2143 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2144 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002145 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002146 PDiag(diag::err_access_dtor)
2147 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002148 if (DiagnoseUseOfDecl(dtor, StartLoc))
2149 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002150 }
John McCall928a2572011-07-13 20:12:57 +00002151 }
2152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002154 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002155 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002156 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2157 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2158 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002159}
2160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002161/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002162/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002163bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002164 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002165 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2166 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002167 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002168 return Diag(Loc, diag::err_bad_new_type)
2169 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002170 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002171 return Diag(Loc, diag::err_bad_new_type)
2172 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002173 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002174 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002175 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002176 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002177 diag::err_allocation_of_abstract_type))
2178 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002179 else if (AllocType->isVariablyModifiedType())
2180 return Diag(Loc, diag::err_variably_modified_new_type)
2181 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002182 else if (AllocType.getAddressSpace() != LangAS::Default &&
2183 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002184 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002185 << AllocType.getUnqualifiedType()
2186 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002187 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002188 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2189 QualType BaseAllocType = Context.getBaseElementType(AT);
2190 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2191 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002192 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002193 << BaseAllocType;
2194 }
2195 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002196
Sebastian Redlbd150f42008-11-21 19:14:01 +00002197 return false;
2198}
2199
Brian Gesiak87412d92018-02-15 20:09:25 +00002200static bool resolveAllocationOverload(
2201 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2202 bool &PassAlignment, FunctionDecl *&Operator,
2203 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002204 OverloadCandidateSet Candidates(R.getNameLoc(),
2205 OverloadCandidateSet::CSK_Normal);
2206 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2207 Alloc != AllocEnd; ++Alloc) {
2208 // Even member operator new/delete are implicitly treated as
2209 // static, so don't use AddMemberCandidate.
2210 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2211
2212 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2213 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2214 /*ExplicitTemplateArgs=*/nullptr, Args,
2215 Candidates,
2216 /*SuppressUserConversions=*/false);
2217 continue;
2218 }
2219
2220 FunctionDecl *Fn = cast<FunctionDecl>(D);
2221 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2222 /*SuppressUserConversions=*/false);
2223 }
2224
2225 // Do the resolution.
2226 OverloadCandidateSet::iterator Best;
2227 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2228 case OR_Success: {
2229 // Got one!
2230 FunctionDecl *FnDecl = Best->Function;
2231 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2232 Best->FoundDecl) == Sema::AR_inaccessible)
2233 return true;
2234
2235 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002236 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002237 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002238
Richard Smithb2f0f052016-10-10 18:54:32 +00002239 case OR_No_Viable_Function:
2240 // C++17 [expr.new]p13:
2241 // If no matching function is found and the allocated object type has
2242 // new-extended alignment, the alignment argument is removed from the
2243 // argument list, and overload resolution is performed again.
2244 if (PassAlignment) {
2245 PassAlignment = false;
2246 AlignArg = Args[1];
2247 Args.erase(Args.begin() + 1);
2248 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002249 Operator, &Candidates, AlignArg,
2250 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002251 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002252
Richard Smithb2f0f052016-10-10 18:54:32 +00002253 // MSVC will fall back on trying to find a matching global operator new
2254 // if operator new[] cannot be found. Also, MSVC will leak by not
2255 // generating a call to operator delete or operator delete[], but we
2256 // will not replicate that bug.
2257 // FIXME: Find out how this interacts with the std::align_val_t fallback
2258 // once MSVC implements it.
2259 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2260 S.Context.getLangOpts().MSVCCompat) {
2261 R.clear();
2262 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2263 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2264 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2265 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002266 Operator, /*Candidates=*/nullptr,
2267 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002268 }
Richard Smith1cdec012013-09-29 04:40:38 +00002269
Brian Gesiak87412d92018-02-15 20:09:25 +00002270 if (Diagnose) {
2271 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2272 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002273
Brian Gesiak87412d92018-02-15 20:09:25 +00002274 // If we have aligned candidates, only note the align_val_t candidates
2275 // from AlignedCandidates and the non-align_val_t candidates from
2276 // Candidates.
2277 if (AlignedCandidates) {
2278 auto IsAligned = [](OverloadCandidate &C) {
2279 return C.Function->getNumParams() > 1 &&
2280 C.Function->getParamDecl(1)->getType()->isAlignValT();
2281 };
2282 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002283
Brian Gesiak87412d92018-02-15 20:09:25 +00002284 // This was an overaligned allocation, so list the aligned candidates
2285 // first.
2286 Args.insert(Args.begin() + 1, AlignArg);
2287 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2288 R.getNameLoc(), IsAligned);
2289 Args.erase(Args.begin() + 1);
2290 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2291 IsUnaligned);
2292 } else {
2293 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2294 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002295 }
Richard Smith1cdec012013-09-29 04:40:38 +00002296 return true;
2297
Richard Smithb2f0f052016-10-10 18:54:32 +00002298 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002299 if (Diagnose) {
2300 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2301 << R.getLookupName() << Range;
2302 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2303 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002304 return true;
2305
2306 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002307 if (Diagnose) {
2308 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2309 << Best->Function->isDeleted() << R.getLookupName()
2310 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2311 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2312 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002313 return true;
2314 }
2315 }
2316 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002317}
2318
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002319bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002320 AllocationFunctionScope NewScope,
2321 AllocationFunctionScope DeleteScope,
2322 QualType AllocType, bool IsArray,
2323 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002324 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002325 FunctionDecl *&OperatorDelete,
2326 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002327 // --- Choosing an allocation function ---
2328 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002329 // 1) If looking in AFS_Global scope for allocation functions, only look in
2330 // the global scope. Else, if AFS_Class, only look in the scope of the
2331 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002332 // 2) If an array size is given, look for operator new[], else look for
2333 // operator new.
2334 // 3) The first argument is always size_t. Append the arguments from the
2335 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002336
Richard Smithb2f0f052016-10-10 18:54:32 +00002337 SmallVector<Expr*, 8> AllocArgs;
2338 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2339
2340 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002341 // FIXME: Should the Sema create the expression and embed it in the syntax
2342 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002343 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002344 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002345 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002346 Context.getSizeType(),
2347 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002348 AllocArgs.push_back(&Size);
2349
2350 QualType AlignValT = Context.VoidTy;
2351 if (PassAlignment) {
2352 DeclareGlobalNewDelete();
2353 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2354 }
2355 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2356 if (PassAlignment)
2357 AllocArgs.push_back(&Align);
2358
2359 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002360
Douglas Gregor6642ca22010-02-26 05:06:18 +00002361 // C++ [expr.new]p8:
2362 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002363 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002364 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002365 // type, the allocation function's name is operator new[] and the
2366 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002367 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002368 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002369
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002370 QualType AllocElemType = Context.getBaseElementType(AllocType);
2371
Richard Smithb2f0f052016-10-10 18:54:32 +00002372 // Find the allocation function.
2373 {
2374 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2375
2376 // C++1z [expr.new]p9:
2377 // If the new-expression begins with a unary :: operator, the allocation
2378 // function's name is looked up in the global scope. Otherwise, if the
2379 // allocated type is a class type T or array thereof, the allocation
2380 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002381 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002382 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2383
2384 // We can see ambiguity here if the allocation function is found in
2385 // multiple base classes.
2386 if (R.isAmbiguous())
2387 return true;
2388
2389 // If this lookup fails to find the name, or if the allocated type is not
2390 // a class type, the allocation function's name is looked up in the
2391 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002392 if (R.empty()) {
2393 if (NewScope == AFS_Class)
2394 return true;
2395
Richard Smithb2f0f052016-10-10 18:54:32 +00002396 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002397 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002398
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002399 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2400 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2401 return true;
2402 }
2403
Richard Smithb2f0f052016-10-10 18:54:32 +00002404 assert(!R.empty() && "implicitly declared allocation functions not found");
2405 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2406
2407 // We do our own custom access checks below.
2408 R.suppressDiagnostics();
2409
2410 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002411 OperatorNew, /*Candidates=*/nullptr,
2412 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002413 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002414 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002415
Richard Smithb2f0f052016-10-10 18:54:32 +00002416 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002417 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002418 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002419 return false;
2420 }
2421
Richard Smithb2f0f052016-10-10 18:54:32 +00002422 // Note, the name of OperatorNew might have been changed from array to
2423 // non-array by resolveAllocationOverload.
2424 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2425 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2426 ? OO_Array_Delete
2427 : OO_Delete);
2428
Douglas Gregor6642ca22010-02-26 05:06:18 +00002429 // C++ [expr.new]p19:
2430 //
2431 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002432 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002433 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002434 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002435 // the scope of T. If this lookup fails to find the name, or if
2436 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002437 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002438 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002439 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002440 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002441 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002442 LookupQualifiedName(FoundDelete, RD);
2443 }
John McCallfb6f5262010-03-18 08:19:33 +00002444 if (FoundDelete.isAmbiguous())
2445 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002446
Richard Smithb2f0f052016-10-10 18:54:32 +00002447 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002448 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002449 if (DeleteScope == AFS_Class)
2450 return true;
2451
Douglas Gregor6642ca22010-02-26 05:06:18 +00002452 DeclareGlobalNewDelete();
2453 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2454 }
2455
2456 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002457
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002458 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002459
John McCalld3be2c82010-09-14 21:34:24 +00002460 // Whether we're looking for a placement operator delete is dictated
2461 // by whether we selected a placement operator new, not by whether
2462 // we had explicit placement arguments. This matters for things like
2463 // struct A { void *operator new(size_t, int = 0); ... };
2464 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002465 //
2466 // We don't have any definition for what a "placement allocation function"
2467 // is, but we assume it's any allocation function whose
2468 // parameter-declaration-clause is anything other than (size_t).
2469 //
2470 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2471 // This affects whether an exception from the constructor of an overaligned
2472 // type uses the sized or non-sized form of aligned operator delete.
2473 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2474 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002475
2476 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002477 // C++ [expr.new]p20:
2478 // A declaration of a placement deallocation function matches the
2479 // declaration of a placement allocation function if it has the
2480 // same number of parameters and, after parameter transformations
2481 // (8.3.5), all parameter types except the first are
2482 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002483 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002484 // To perform this comparison, we compute the function type that
2485 // the deallocation function should have, and use that type both
2486 // for template argument deduction and for comparison purposes.
2487 QualType ExpectedFunctionType;
2488 {
2489 const FunctionProtoType *Proto
2490 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002491
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002492 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002493 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002494 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2495 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002496
John McCalldb40c7f2010-12-14 08:05:40 +00002497 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002498 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002499 EPI.Variadic = Proto->isVariadic();
2500
Douglas Gregor6642ca22010-02-26 05:06:18 +00002501 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002502 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002503 }
2504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002506 DEnd = FoundDelete.end();
2507 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002508 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002509 if (FunctionTemplateDecl *FnTmpl =
2510 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002511 // Perform template argument deduction to try to match the
2512 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002513 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002514 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2515 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002516 continue;
2517 } else
2518 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2519
Richard Smithbaa47832016-12-01 02:11:49 +00002520 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2521 ExpectedFunctionType,
2522 /*AdjustExcpetionSpec*/true),
2523 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002524 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002525 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002526
Richard Smithb2f0f052016-10-10 18:54:32 +00002527 if (getLangOpts().CUDA)
2528 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2529 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002530 // C++1y [expr.new]p22:
2531 // For a non-placement allocation function, the normal deallocation
2532 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002533 //
2534 // Per [expr.delete]p10, this lookup prefers a member operator delete
2535 // without a size_t argument, but prefers a non-member operator delete
2536 // with a size_t where possible (which it always is in this case).
2537 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2538 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2539 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2540 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2541 &BestDeallocFns);
2542 if (Selected)
2543 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2544 else {
2545 // If we failed to select an operator, all remaining functions are viable
2546 // but ambiguous.
2547 for (auto Fn : BestDeallocFns)
2548 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002549 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002550 }
2551
2552 // C++ [expr.new]p20:
2553 // [...] If the lookup finds a single matching deallocation
2554 // function, that function will be called; otherwise, no
2555 // deallocation function will be called.
2556 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002557 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002558
Richard Smithb2f0f052016-10-10 18:54:32 +00002559 // C++1z [expr.new]p23:
2560 // If the lookup finds a usual deallocation function (3.7.4.2)
2561 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002562 // as a placement deallocation function, would have been
2563 // selected as a match for the allocation function, the program
2564 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002565 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002566 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002567 UsualDeallocFnInfo Info(*this,
2568 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002569 // Core issue, per mail to core reflector, 2016-10-09:
2570 // If this is a member operator delete, and there is a corresponding
2571 // non-sized member operator delete, this isn't /really/ a sized
2572 // deallocation function, it just happens to have a size_t parameter.
2573 bool IsSizedDelete = Info.HasSizeT;
2574 if (IsSizedDelete && !FoundGlobalDelete) {
2575 auto NonSizedDelete =
2576 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2577 /*WantAlign*/Info.HasAlignValT);
2578 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2579 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2580 IsSizedDelete = false;
2581 }
2582
2583 if (IsSizedDelete) {
2584 SourceRange R = PlaceArgs.empty()
2585 ? SourceRange()
2586 : SourceRange(PlaceArgs.front()->getLocStart(),
2587 PlaceArgs.back()->getLocEnd());
2588 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2589 if (!OperatorDelete->isImplicit())
2590 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2591 << DeleteName;
2592 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002593 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002594
2595 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2596 Matches[0].first);
2597 } else if (!Matches.empty()) {
2598 // We found multiple suitable operators. Per [expr.new]p20, that means we
2599 // call no 'operator delete' function, but we should at least warn the user.
2600 // FIXME: Suppress this warning if the construction cannot throw.
2601 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2602 << DeleteName << AllocElemType;
2603
2604 for (auto &Match : Matches)
2605 Diag(Match.second->getLocation(),
2606 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002607 }
2608
Sebastian Redlfaf68082008-12-03 20:26:15 +00002609 return false;
2610}
2611
2612/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2613/// delete. These are:
2614/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002615/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002616/// void* operator new(std::size_t) throw(std::bad_alloc);
2617/// void* operator new[](std::size_t) throw(std::bad_alloc);
2618/// void operator delete(void *) throw();
2619/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002620/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002621/// void* operator new(std::size_t);
2622/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002623/// void operator delete(void *) noexcept;
2624/// void operator delete[](void *) noexcept;
2625/// // C++1y:
2626/// void* operator new(std::size_t);
2627/// void* operator new[](std::size_t);
2628/// void operator delete(void *) noexcept;
2629/// void operator delete[](void *) noexcept;
2630/// void operator delete(void *, std::size_t) noexcept;
2631/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002632/// @endcode
2633/// Note that the placement and nothrow forms of new are *not* implicitly
2634/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002635void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002636 if (GlobalNewDeleteDeclared)
2637 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002639 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2640 // are not supported.
2641 if (getLangOpts().OpenCLCPlusPlus)
2642 return;
2643
Douglas Gregor87f54062009-09-15 22:30:29 +00002644 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002645 // [...] The following allocation and deallocation functions (18.4) are
2646 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002647 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648 //
Sebastian Redl37588092011-03-14 18:08:30 +00002649 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002650 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651 // void* operator new[](std::size_t) throw(std::bad_alloc);
2652 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002653 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002654 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002655 // void* operator new(std::size_t);
2656 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002657 // void operator delete(void*) noexcept;
2658 // void operator delete[](void*) noexcept;
2659 // C++1y:
2660 // void* operator new(std::size_t);
2661 // void* operator new[](std::size_t);
2662 // void operator delete(void*) noexcept;
2663 // void operator delete[](void*) noexcept;
2664 // void operator delete(void*, std::size_t) noexcept;
2665 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002666 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002667 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002668 // new, operator new[], operator delete, operator delete[].
2669 //
2670 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2671 // "std" or "bad_alloc" as necessary to form the exception specification.
2672 // However, we do not make these implicit declarations visible to name
2673 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002674 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002675 // The "std::bad_alloc" class has not yet been declared, so build it
2676 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2678 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002679 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002680 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002681 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002682 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002683 }
Richard Smith59139022016-09-30 22:41:36 +00002684 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002685 // The "std::align_val_t" enum class has not yet been declared, so build it
2686 // implicitly.
2687 auto *AlignValT = EnumDecl::Create(
2688 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2689 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2690 AlignValT->setIntegerType(Context.getSizeType());
2691 AlignValT->setPromotionType(Context.getSizeType());
2692 AlignValT->setImplicit(true);
2693 StdAlignValT = AlignValT;
2694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Sebastian Redlfaf68082008-12-03 20:26:15 +00002696 GlobalNewDeleteDeclared = true;
2697
2698 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2699 QualType SizeT = Context.getSizeType();
2700
Richard Smith96269c52016-09-29 22:49:46 +00002701 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2702 QualType Return, QualType Param) {
2703 llvm::SmallVector<QualType, 3> Params;
2704 Params.push_back(Param);
2705
2706 // Create up to four variants of the function (sized/aligned).
2707 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2708 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002709 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002710
2711 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2712 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2713 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002714 if (Sized)
2715 Params.push_back(SizeT);
2716
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002717 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002718 if (Aligned)
2719 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2720
2721 DeclareGlobalAllocationFunction(
2722 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2723
2724 if (Aligned)
2725 Params.pop_back();
2726 }
2727 }
2728 };
2729
2730 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2731 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2732 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2733 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002734}
2735
2736/// DeclareGlobalAllocationFunction - Declares a single implicit global
2737/// allocation function if it doesn't already exist.
2738void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002739 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002740 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002741 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2742
2743 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002744 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2745 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2746 Alloc != AllocEnd; ++Alloc) {
2747 // Only look at non-template functions, as it is the predefined,
2748 // non-templated allocation function we are trying to declare here.
2749 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002750 if (Func->getNumParams() == Params.size()) {
2751 llvm::SmallVector<QualType, 3> FuncParams;
2752 for (auto *P : Func->parameters())
2753 FuncParams.push_back(
2754 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2755 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002756 // Make the function visible to name lookup, even if we found it in
2757 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002758 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002759 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002760 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002761 }
Chandler Carruth93538422010-02-03 11:02:14 +00002762 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002763 }
2764 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002765
Richard Smithc015bc22014-02-07 22:39:53 +00002766 FunctionProtoType::ExtProtoInfo EPI;
2767
Richard Smithf8b417c2014-02-08 00:42:45 +00002768 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002769 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002770 = (Name.getCXXOverloadedOperator() == OO_New ||
2771 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002772 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002773 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002774 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002775 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002776 EPI.ExceptionSpec.Type = EST_Dynamic;
2777 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002778 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002779 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002780 EPI.ExceptionSpec =
2781 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783
Artem Belevich07db5cf2016-10-21 20:34:05 +00002784 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2785 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2786 FunctionDecl *Alloc = FunctionDecl::Create(
2787 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2788 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2789 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002790 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002791 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002792
Artem Belevich07db5cf2016-10-21 20:34:05 +00002793 // Implicit sized deallocation functions always have default visibility.
2794 Alloc->addAttr(
2795 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002796
Artem Belevich07db5cf2016-10-21 20:34:05 +00002797 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2798 for (QualType T : Params) {
2799 ParamDecls.push_back(ParmVarDecl::Create(
2800 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2801 /*TInfo=*/nullptr, SC_None, nullptr));
2802 ParamDecls.back()->setImplicit();
2803 }
2804 Alloc->setParams(ParamDecls);
2805 if (ExtraAttr)
2806 Alloc->addAttr(ExtraAttr);
2807 Context.getTranslationUnitDecl()->addDecl(Alloc);
2808 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2809 };
2810
2811 if (!LangOpts.CUDA)
2812 CreateAllocationFunctionDecl(nullptr);
2813 else {
2814 // Host and device get their own declaration so each can be
2815 // defined or re-declared independently.
2816 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2817 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002818 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002819}
2820
Richard Smith1cdec012013-09-29 04:40:38 +00002821FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2822 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002823 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002824 DeclarationName Name) {
2825 DeclareGlobalNewDelete();
2826
2827 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2828 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2829
Richard Smithb2f0f052016-10-10 18:54:32 +00002830 // FIXME: It's possible for this to result in ambiguity, through a
2831 // user-declared variadic operator delete or the enable_if attribute. We
2832 // should probably not consider those cases to be usual deallocation
2833 // functions. But for now we just make an arbitrary choice in that case.
2834 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2835 Overaligned);
2836 assert(Result.FD && "operator delete missing from global scope?");
2837 return Result.FD;
2838}
Richard Smith1cdec012013-09-29 04:40:38 +00002839
Richard Smithb2f0f052016-10-10 18:54:32 +00002840FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2841 CXXRecordDecl *RD) {
2842 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002843
Richard Smithb2f0f052016-10-10 18:54:32 +00002844 FunctionDecl *OperatorDelete = nullptr;
2845 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2846 return nullptr;
2847 if (OperatorDelete)
2848 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002849
Richard Smithb2f0f052016-10-10 18:54:32 +00002850 // If there's no class-specific operator delete, look up the global
2851 // non-array delete.
2852 return FindUsualDeallocationFunction(
2853 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2854 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002855}
2856
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002857bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2858 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002859 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002860 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002861 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002862 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863
John McCall27b18f82009-11-17 02:14:36 +00002864 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002865 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002866
Chandler Carruthb6f99172010-06-28 00:30:51 +00002867 Found.suppressDiagnostics();
2868
Richard Smithb2f0f052016-10-10 18:54:32 +00002869 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002870
Richard Smithb2f0f052016-10-10 18:54:32 +00002871 // C++17 [expr.delete]p10:
2872 // If the deallocation functions have class scope, the one without a
2873 // parameter of type std::size_t is selected.
2874 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2875 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2876 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002877
Richard Smithb2f0f052016-10-10 18:54:32 +00002878 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002879 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002880 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002881
Richard Smithb2f0f052016-10-10 18:54:32 +00002882 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002883 if (Operator->isDeleted()) {
2884 if (Diagnose) {
2885 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002886 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002887 }
2888 return true;
2889 }
2890
Richard Smith921bd202012-02-26 09:11:52 +00002891 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002892 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002893 return true;
2894
John McCall66a87592010-08-04 00:31:26 +00002895 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002896 }
John McCall66a87592010-08-04 00:31:26 +00002897
Richard Smithb2f0f052016-10-10 18:54:32 +00002898 // We found multiple suitable operators; complain about the ambiguity.
2899 // FIXME: The standard doesn't say to do this; it appears that the intent
2900 // is that this should never happen.
2901 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002902 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002903 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2904 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002905 for (auto &Match : Matches)
2906 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002907 }
John McCall66a87592010-08-04 00:31:26 +00002908 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002909 }
2910
2911 // We did find operator delete/operator delete[] declarations, but
2912 // none of them were suitable.
2913 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002914 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002915 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2916 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917
Richard Smithb2f0f052016-10-10 18:54:32 +00002918 for (NamedDecl *D : Found)
2919 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002920 diag::note_member_declared_here) << Name;
2921 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002922 return true;
2923 }
2924
Craig Topperc3ec1492014-05-26 06:22:03 +00002925 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002926 return false;
2927}
2928
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002929namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002930/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002931/// initializing deletee have the same array form.
2932class MismatchingNewDeleteDetector {
2933public:
2934 enum MismatchResult {
2935 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2936 NoMismatch,
2937 /// Indicates that variable is initialized with mismatching form of \a new.
2938 VarInitMismatches,
2939 /// Indicates that member is initialized with mismatching form of \a new.
2940 MemberInitMismatches,
2941 /// Indicates that 1 or more constructors' definitions could not been
2942 /// analyzed, and they will be checked again at the end of translation unit.
2943 AnalyzeLater
2944 };
2945
2946 /// \param EndOfTU True, if this is the final analysis at the end of
2947 /// translation unit. False, if this is the initial analysis at the point
2948 /// delete-expression was encountered.
2949 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002950 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002951 HasUndefinedConstructors(false) {}
2952
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002953 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002954 /// matching form of new-expression.
2955 ///
2956 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2957 /// point where delete-expression is encountered, then a warning will be
2958 /// issued immediately. If return value is \c AnalyzeLater at the point where
2959 /// delete-expression is seen, then member will be analyzed at the end of
2960 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2961 /// couldn't be analyzed. If at least one constructor initializes the member
2962 /// with matching type of new, the return value is \c NoMismatch.
2963 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002964 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002965 /// \param Field Class member to analyze.
2966 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2967 /// for deleting the \p Field.
2968 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002969 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002970 /// List of mismatching new-expressions used for initialization of the pointee
2971 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2972 /// Indicates whether delete-expression was in array form.
2973 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002974
2975private:
2976 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002977 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002978 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002979 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002980 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002981 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002982 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002983 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002984 /// \c new either by the member initializer or in-class initialization.
2985 ///
2986 /// If bodies of all constructors are not visible at the end of translation
2987 /// unit or at least one constructor initializes member with the matching
2988 /// form of \c new, mismatch cannot be proven, and this function will return
2989 /// \c NoMismatch.
2990 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002991 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002992 /// \c new.
2993 ///
2994 /// If variable is initialized with matching form of \c new or variable is not
2995 /// initialized with a \c new expression, this function will return true.
2996 /// If variable is initialized with mismatching form of \c new, returns false.
2997 /// \param D Variable to analyze.
2998 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002999 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003000 /// form of \c new.
3001 ///
3002 /// Returns true, if member is initialized with matching form of \c new in
3003 /// member initializer list. Returns false, if member is initialized with the
3004 /// matching form of \c new in this constructor's initializer or given
3005 /// constructor isn't defined at the point where delete-expression is seen, or
3006 /// member isn't initialized by the constructor.
3007 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003008 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003009 /// \c new in member initializer list.
3010 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3011 /// Checks whether member is initialized with mismatching form of \c new by
3012 /// in-class initializer.
3013 MismatchResult analyzeInClassInitializer();
3014};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003015}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003016
3017MismatchingNewDeleteDetector::MismatchResult
3018MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3019 NewExprs.clear();
3020 assert(DE && "Expected delete-expression");
3021 IsArrayForm = DE->isArrayForm();
3022 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3023 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3024 return analyzeMemberExpr(ME);
3025 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3026 if (!hasMatchingVarInit(D))
3027 return VarInitMismatches;
3028 }
3029 return NoMismatch;
3030}
3031
3032const CXXNewExpr *
3033MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3034 assert(E != nullptr && "Expected a valid initializer expression");
3035 E = E->IgnoreParenImpCasts();
3036 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3037 if (ILE->getNumInits() == 1)
3038 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3039 }
3040
3041 return dyn_cast_or_null<const CXXNewExpr>(E);
3042}
3043
3044bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3045 const CXXCtorInitializer *CI) {
3046 const CXXNewExpr *NE = nullptr;
3047 if (Field == CI->getMember() &&
3048 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3049 if (NE->isArray() == IsArrayForm)
3050 return true;
3051 else
3052 NewExprs.push_back(NE);
3053 }
3054 return false;
3055}
3056
3057bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3058 const CXXConstructorDecl *CD) {
3059 if (CD->isImplicit())
3060 return false;
3061 const FunctionDecl *Definition = CD;
3062 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3063 HasUndefinedConstructors = true;
3064 return EndOfTU;
3065 }
3066 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3067 if (hasMatchingNewInCtorInit(CI))
3068 return true;
3069 }
3070 return false;
3071}
3072
3073MismatchingNewDeleteDetector::MismatchResult
3074MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3075 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003076 const Expr *InitExpr = Field->getInClassInitializer();
3077 if (!InitExpr)
3078 return EndOfTU ? NoMismatch : AnalyzeLater;
3079 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003080 if (NE->isArray() != IsArrayForm) {
3081 NewExprs.push_back(NE);
3082 return MemberInitMismatches;
3083 }
3084 }
3085 return NoMismatch;
3086}
3087
3088MismatchingNewDeleteDetector::MismatchResult
3089MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3090 bool DeleteWasArrayForm) {
3091 assert(Field != nullptr && "Analysis requires a valid class member.");
3092 this->Field = Field;
3093 IsArrayForm = DeleteWasArrayForm;
3094 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3095 for (const auto *CD : RD->ctors()) {
3096 if (hasMatchingNewInCtor(CD))
3097 return NoMismatch;
3098 }
3099 if (HasUndefinedConstructors)
3100 return EndOfTU ? NoMismatch : AnalyzeLater;
3101 if (!NewExprs.empty())
3102 return MemberInitMismatches;
3103 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3104 : NoMismatch;
3105}
3106
3107MismatchingNewDeleteDetector::MismatchResult
3108MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3109 assert(ME != nullptr && "Expected a member expression");
3110 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3111 return analyzeField(F, IsArrayForm);
3112 return NoMismatch;
3113}
3114
3115bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3116 const CXXNewExpr *NE = nullptr;
3117 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3118 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3119 NE->isArray() != IsArrayForm) {
3120 NewExprs.push_back(NE);
3121 }
3122 }
3123 return NewExprs.empty();
3124}
3125
3126static void
3127DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3128 const MismatchingNewDeleteDetector &Detector) {
3129 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3130 FixItHint H;
3131 if (!Detector.IsArrayForm)
3132 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3133 else {
3134 SourceLocation RSquare = Lexer::findLocationAfterToken(
3135 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3136 SemaRef.getLangOpts(), true);
3137 if (RSquare.isValid())
3138 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3139 }
3140 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3141 << Detector.IsArrayForm << H;
3142
3143 for (const auto *NE : Detector.NewExprs)
3144 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3145 << Detector.IsArrayForm;
3146}
3147
3148void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3149 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3150 return;
3151 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3152 switch (Detector.analyzeDeleteExpr(DE)) {
3153 case MismatchingNewDeleteDetector::VarInitMismatches:
3154 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3155 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3156 break;
3157 }
3158 case MismatchingNewDeleteDetector::AnalyzeLater: {
3159 DeleteExprs[Detector.Field].push_back(
3160 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3161 break;
3162 }
3163 case MismatchingNewDeleteDetector::NoMismatch:
3164 break;
3165 }
3166}
3167
3168void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3169 bool DeleteWasArrayForm) {
3170 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3171 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3172 case MismatchingNewDeleteDetector::VarInitMismatches:
3173 llvm_unreachable("This analysis should have been done for class members.");
3174 case MismatchingNewDeleteDetector::AnalyzeLater:
3175 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3176 "translation unit.");
3177 case MismatchingNewDeleteDetector::MemberInitMismatches:
3178 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3179 break;
3180 case MismatchingNewDeleteDetector::NoMismatch:
3181 break;
3182 }
3183}
3184
Sebastian Redlbd150f42008-11-21 19:14:01 +00003185/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3186/// @code ::delete ptr; @endcode
3187/// or
3188/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003189ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003190Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003191 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003192 // C++ [expr.delete]p1:
3193 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003194 // non-explicit conversion function to a pointer type. The result has type
3195 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003196 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003197 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3198
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003199 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003201 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003202 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003203
John Wiegley01296292011-04-08 18:41:53 +00003204 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003205 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003206 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003207 if (Ex.isInvalid())
3208 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003209
John Wiegley01296292011-04-08 18:41:53 +00003210 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003211
Richard Smithccc11812013-05-21 19:05:48 +00003212 class DeleteConverter : public ContextualImplicitConverter {
3213 public:
3214 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
Craig Toppere14c0f82014-03-12 04:55:44 +00003216 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003217 // FIXME: If we have an operator T* and an operator void*, we must pick
3218 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003219 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003220 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003221 return true;
3222 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003223 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003224
Richard Smithccc11812013-05-21 19:05:48 +00003225 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003226 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003227 return S.Diag(Loc, diag::err_delete_operand) << T;
3228 }
3229
3230 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003231 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003232 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3233 }
3234
3235 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003236 QualType T,
3237 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003238 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3239 }
3240
3241 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003242 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003243 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3244 << ConvTy;
3245 }
3246
3247 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003248 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003249 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3250 }
3251
3252 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003253 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003254 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3255 << ConvTy;
3256 }
3257
3258 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003259 QualType T,
3260 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003261 llvm_unreachable("conversion functions are permitted");
3262 }
3263 } Converter;
3264
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003265 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003266 if (Ex.isInvalid())
3267 return ExprError();
3268 Type = Ex.get()->getType();
3269 if (!Converter.match(Type))
3270 // FIXME: PerformContextualImplicitConversion should return ExprError
3271 // itself in this case.
3272 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003273
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003274 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003275 QualType PointeeElem = Context.getBaseElementType(Pointee);
3276
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003277 if (Pointee.getAddressSpace() != LangAS::Default &&
3278 !getLangOpts().OpenCLCPlusPlus)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003279 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003280 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003281 << Pointee.getUnqualifiedType()
3282 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003283
Craig Topperc3ec1492014-05-26 06:22:03 +00003284 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003285 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003287 // effectively bans deletion of "void*". However, most compilers support
3288 // this, so we treat it as a warning unless we're in a SFINAE context.
3289 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003290 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003291 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003292 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003293 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003294 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003295 // FIXME: This can result in errors if the definition was imported from a
3296 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003297 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003298 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003299 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3300 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3301 }
3302 }
3303
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003304 if (Pointee->isArrayType() && !ArrayForm) {
3305 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003306 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003307 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003308 ArrayForm = true;
3309 }
3310
Anders Carlssona471db02009-08-16 20:29:29 +00003311 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3312 ArrayForm ? OO_Array_Delete : OO_Delete);
3313
Eli Friedmanae4280f2011-07-26 22:25:31 +00003314 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003316 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3317 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003318 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319
John McCall284c48f2011-01-27 09:37:56 +00003320 // If we're allocating an array of records, check whether the
3321 // usual operator delete[] has a size_t parameter.
3322 if (ArrayForm) {
3323 // If the user specifically asked to use the global allocator,
3324 // we'll need to do the lookup into the class.
3325 if (UseGlobal)
3326 UsualArrayDeleteWantsSize =
3327 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3328
3329 // Otherwise, the usual operator delete[] should be the
3330 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003331 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003332 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003333 UsualDeallocFnInfo(*this,
3334 DeclAccessPair::make(OperatorDelete, AS_public))
3335 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003336 }
3337
Richard Smitheec915d62012-02-18 04:13:32 +00003338 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003339 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003340 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003341 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003342 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3343 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003344 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003345
Nico Weber5a9259c2016-01-15 21:45:31 +00003346 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3347 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3348 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3349 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003351
Richard Smithb2f0f052016-10-10 18:54:32 +00003352 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003353 if (getLangOpts().OpenCLCPlusPlus) {
3354 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3355 return ExprError();
3356 }
3357
Richard Smithb2f0f052016-10-10 18:54:32 +00003358 bool IsComplete = isCompleteType(StartLoc, Pointee);
3359 bool CanProvideSize =
3360 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3361 Pointee.isDestructedType());
3362 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3363
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003364 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003365 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3366 Overaligned, DeleteName);
3367 }
Mike Stump11289f42009-09-09 15:08:12 +00003368
Eli Friedmanfa0df832012-02-02 03:46:19 +00003369 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003370
Richard Smith5b349582017-10-13 01:55:36 +00003371 // Check access and ambiguity of destructor if we're going to call it.
3372 // Note that this is required even for a virtual delete.
3373 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003374 if (PointeeRD) {
3375 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003376 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3377 PDiag(diag::err_access_dtor) << PointeeElem);
3378 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003379 }
3380 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003381
3382 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3383 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003384
3385 // Convert the operand to the type of the first parameter of operator
3386 // delete. This is only necessary if we selected a destroying operator
3387 // delete that we are going to call (non-virtually); converting to void*
3388 // is trivial and left to AST consumers to handle.
3389 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3390 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003391 Qualifiers Qs = Pointee.getQualifiers();
3392 if (Qs.hasCVRQualifiers()) {
3393 // Qualifiers are irrelevant to this conversion; we're only looking
3394 // for access and ambiguity.
3395 Qs.removeCVRQualifiers();
3396 QualType Unqual = Context.getPointerType(
3397 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3398 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3399 }
Richard Smith5b349582017-10-13 01:55:36 +00003400 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3401 if (Ex.isInvalid())
3402 return ExprError();
3403 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003404 }
3405
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003406 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003407 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3408 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003409 AnalyzeDeleteExprMismatch(Result);
3410 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003411}
3412
Eric Fiselierfa752f22018-03-21 19:19:48 +00003413static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3414 bool IsDelete,
3415 FunctionDecl *&Operator) {
3416
3417 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3418 IsDelete ? OO_Delete : OO_New);
3419
3420 LookupResult R(S, NewName, TheCall->getLocStart(), Sema::LookupOrdinaryName);
3421 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3422 assert(!R.empty() && "implicitly declared allocation functions not found");
3423 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3424
3425 // We do our own custom access checks below.
3426 R.suppressDiagnostics();
3427
3428 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3429 OverloadCandidateSet Candidates(R.getNameLoc(),
3430 OverloadCandidateSet::CSK_Normal);
3431 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3432 FnOvl != FnOvlEnd; ++FnOvl) {
3433 // Even member operator new/delete are implicitly treated as
3434 // static, so don't use AddMemberCandidate.
3435 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3436
3437 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3438 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3439 /*ExplicitTemplateArgs=*/nullptr, Args,
3440 Candidates,
3441 /*SuppressUserConversions=*/false);
3442 continue;
3443 }
3444
3445 FunctionDecl *Fn = cast<FunctionDecl>(D);
3446 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3447 /*SuppressUserConversions=*/false);
3448 }
3449
3450 SourceRange Range = TheCall->getSourceRange();
3451
3452 // Do the resolution.
3453 OverloadCandidateSet::iterator Best;
3454 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3455 case OR_Success: {
3456 // Got one!
3457 FunctionDecl *FnDecl = Best->Function;
3458 assert(R.getNamingClass() == nullptr &&
3459 "class members should not be considered");
3460
3461 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3462 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3463 << (IsDelete ? 1 : 0) << Range;
3464 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3465 << R.getLookupName() << FnDecl->getSourceRange();
3466 return true;
3467 }
3468
3469 Operator = FnDecl;
3470 return false;
3471 }
3472
3473 case OR_No_Viable_Function:
3474 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3475 << R.getLookupName() << Range;
3476 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3477 return true;
3478
3479 case OR_Ambiguous:
3480 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3481 << R.getLookupName() << Range;
3482 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3483 return true;
3484
3485 case OR_Deleted: {
3486 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3487 << Best->Function->isDeleted() << R.getLookupName()
3488 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3489 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3490 return true;
3491 }
3492 }
3493 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3494}
3495
3496ExprResult
3497Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3498 bool IsDelete) {
3499 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3500 if (!getLangOpts().CPlusPlus) {
3501 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3502 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3503 << "C++";
3504 return ExprError();
3505 }
3506 // CodeGen assumes it can find the global new and delete to call,
3507 // so ensure that they are declared.
3508 DeclareGlobalNewDelete();
3509
3510 FunctionDecl *OperatorNewOrDelete = nullptr;
3511 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3512 OperatorNewOrDelete))
3513 return ExprError();
3514 assert(OperatorNewOrDelete && "should be found");
3515
3516 TheCall->setType(OperatorNewOrDelete->getReturnType());
3517 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3518 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3519 InitializedEntity Entity =
3520 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3521 ExprResult Arg = PerformCopyInitialization(
3522 Entity, TheCall->getArg(i)->getLocStart(), TheCall->getArg(i));
3523 if (Arg.isInvalid())
3524 return ExprError();
3525 TheCall->setArg(i, Arg.get());
3526 }
3527 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3528 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3529 "Callee expected to be implicit cast to a builtin function pointer");
3530 Callee->setType(OperatorNewOrDelete->getType());
3531
3532 return TheCallResult;
3533}
3534
Nico Weber5a9259c2016-01-15 21:45:31 +00003535void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3536 bool IsDelete, bool CallCanBeVirtual,
3537 bool WarnOnNonAbstractTypes,
3538 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003539 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003540 return;
3541
3542 // C++ [expr.delete]p3:
3543 // In the first alternative (delete object), if the static type of the
3544 // object to be deleted is different from its dynamic type, the static
3545 // type shall be a base class of the dynamic type of the object to be
3546 // deleted and the static type shall have a virtual destructor or the
3547 // behavior is undefined.
3548 //
3549 const CXXRecordDecl *PointeeRD = dtor->getParent();
3550 // Note: a final class cannot be derived from, no issue there
3551 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3552 return;
3553
Nico Weberbf2260c2017-08-31 06:17:08 +00003554 // If the superclass is in a system header, there's nothing that can be done.
3555 // The `delete` (where we emit the warning) can be in a system header,
3556 // what matters for this warning is where the deleted type is defined.
3557 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3558 return;
3559
Nico Weber5a9259c2016-01-15 21:45:31 +00003560 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3561 if (PointeeRD->isAbstract()) {
3562 // If the class is abstract, we warn by default, because we're
3563 // sure the code has undefined behavior.
3564 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3565 << ClassType;
3566 } else if (WarnOnNonAbstractTypes) {
3567 // Otherwise, if this is not an array delete, it's a bit suspect,
3568 // but not necessarily wrong.
3569 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3570 << ClassType;
3571 }
3572 if (!IsDelete) {
3573 std::string TypeStr;
3574 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3575 Diag(DtorLoc, diag::note_delete_non_virtual)
3576 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3577 }
3578}
3579
Richard Smith03a4aa32016-06-23 19:02:52 +00003580Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3581 SourceLocation StmtLoc,
3582 ConditionKind CK) {
3583 ExprResult E =
3584 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3585 if (E.isInvalid())
3586 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003587 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3588 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003589}
3590
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003591/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003592/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003593ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003594 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003595 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003596 if (ConditionVar->isInvalidDecl())
3597 return ExprError();
3598
Douglas Gregor633caca2009-11-23 23:44:04 +00003599 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregor633caca2009-11-23 23:44:04 +00003601 // C++ [stmt.select]p2:
3602 // The declarator shall not specify a function or an array.
3603 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003605 diag::err_invalid_use_of_function_type)
3606 << ConditionVar->getSourceRange());
3607 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003609 diag::err_invalid_use_of_array_type)
3610 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003611
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003612 ExprResult Condition = DeclRefExpr::Create(
3613 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3614 /*enclosing*/ false, ConditionVar->getLocation(),
3615 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003616
Eli Friedmanfa0df832012-02-02 03:46:19 +00003617 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003618
Richard Smith03a4aa32016-06-23 19:02:52 +00003619 switch (CK) {
3620 case ConditionKind::Boolean:
3621 return CheckBooleanCondition(StmtLoc, Condition.get());
3622
Richard Smithb130fe72016-06-23 19:16:49 +00003623 case ConditionKind::ConstexprIf:
3624 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3625
Richard Smith03a4aa32016-06-23 19:02:52 +00003626 case ConditionKind::Switch:
3627 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629
Richard Smith03a4aa32016-06-23 19:02:52 +00003630 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003631}
3632
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003633/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003634ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003635 // C++ 6.4p4:
3636 // The value of a condition that is an initialized declaration in a statement
3637 // other than a switch statement is the value of the declared variable
3638 // implicitly converted to type bool. If that conversion is ill-formed, the
3639 // program is ill-formed.
3640 // The value of a condition that is an expression is the value of the
3641 // expression, implicitly converted to bool.
3642 //
Richard Smithb130fe72016-06-23 19:16:49 +00003643 // FIXME: Return this value to the caller so they don't need to recompute it.
3644 llvm::APSInt Value(/*BitWidth*/1);
3645 return (IsConstexpr && !CondExpr->isValueDependent())
3646 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3647 CCEK_ConstexprIf)
3648 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003649}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003650
3651/// Helper function to determine whether this is the (deprecated) C++
3652/// conversion from a string literal to a pointer to non-const char or
3653/// non-const wchar_t (for narrow and wide string literals,
3654/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003655bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003656Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3657 // Look inside the implicit cast, if it exists.
3658 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3659 From = Cast->getSubExpr();
3660
3661 // A string literal (2.13.4) that is not a wide string literal can
3662 // be converted to an rvalue of type "pointer to char"; a wide
3663 // string literal can be converted to an rvalue of type "pointer
3664 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003665 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003666 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003667 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003668 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003669 // This conversion is considered only when there is an
3670 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003671 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3672 switch (StrLit->getKind()) {
3673 case StringLiteral::UTF8:
3674 case StringLiteral::UTF16:
3675 case StringLiteral::UTF32:
3676 // We don't allow UTF literals to be implicitly converted
3677 break;
3678 case StringLiteral::Ascii:
3679 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3680 ToPointeeType->getKind() == BuiltinType::Char_S);
3681 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003682 return Context.typesAreCompatible(Context.getWideCharType(),
3683 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003684 }
3685 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003686 }
3687
3688 return false;
3689}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003690
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003692 SourceLocation CastLoc,
3693 QualType Ty,
3694 CastKind Kind,
3695 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003696 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003697 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003698 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003699 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003700 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003701 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003702 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003703 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704
Richard Smith72d74052013-07-20 19:41:36 +00003705 if (S.RequireNonAbstractType(CastLoc, Ty,
3706 diag::err_allocation_of_abstract_type))
3707 return ExprError();
3708
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003709 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003710 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711
Richard Smith5179eb72016-06-28 19:03:57 +00003712 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3713 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003714 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003715 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003716
Richard Smithf8adcdc2014-07-17 05:12:35 +00003717 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003718 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003719 ConstructorArgs, HadMultipleCandidates,
3720 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3721 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003722 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003723 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003725 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
John McCalle3027922010-08-25 11:45:40 +00003728 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003729 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Richard Smithd3f2d322015-02-24 21:16:19 +00003731 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003732 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003733 return ExprError();
3734
Douglas Gregora4253922010-04-16 22:17:36 +00003735 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003736 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3737 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003738 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003739 if (Result.isInvalid())
3740 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003741 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003742 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3743 CK_UserDefinedConversion, Result.get(),
3744 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregor668443e2011-01-20 00:18:04 +00003746 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003747 }
3748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749}
Douglas Gregora4253922010-04-16 22:17:36 +00003750
Douglas Gregor5fb53972009-01-14 15:45:31 +00003751/// PerformImplicitConversion - Perform an implicit conversion of the
3752/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003753/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003754/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003755/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003756ExprResult
3757Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003758 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003759 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003760 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003761 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003762 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003763 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3764 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003765 if (Res.isInvalid())
3766 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003767 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003768 break;
John Wiegley01296292011-04-08 18:41:53 +00003769 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003770
Anders Carlsson110b07b2009-09-15 06:28:28 +00003771 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003773 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003774 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003775 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003776 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003777 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003778 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Anders Carlsson110b07b2009-09-15 06:28:28 +00003780 // If the user-defined conversion is specified by a conversion function,
3781 // the initial standard conversion sequence converts the source type to
3782 // the implicit object parameter of the conversion function.
3783 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003784 } else {
3785 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003786 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003787 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003788 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003790 // initial standard conversion sequence converts the source type to
3791 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003792 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 }
Richard Smith72d74052013-07-20 19:41:36 +00003795 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003796 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003797 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003798 PerformImplicitConversion(From, BeforeToType,
3799 ICS.UserDefined.Before, AA_Converting,
3800 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003801 if (Res.isInvalid())
3802 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003803 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
3806 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003807 = BuildCXXCastArgument(*this,
3808 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003809 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003810 CastKind, cast<CXXMethodDecl>(FD),
3811 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003812 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003813 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003814
3815 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003816 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003817
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003818 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003819
Richard Smith507840d2011-11-29 22:48:16 +00003820 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3821 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003822 }
John McCall0d1da222010-01-12 00:44:57 +00003823
3824 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003825 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003826 PDiag(diag::err_typecheck_ambiguous_condition)
3827 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003828 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829
Douglas Gregor39c16d42008-10-24 04:54:22 +00003830 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003831 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003832
3833 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003834 bool Diagnosed =
3835 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3836 From->getType(), From, Action);
3837 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003838 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003839 }
3840
3841 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003842 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003843}
3844
Richard Smith507840d2011-11-29 22:48:16 +00003845/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003846/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003847/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003848/// expression. Flavor is the context in which we're performing this
3849/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003850ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003851Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003852 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003853 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003854 CheckedConversionKind CCK) {
3855 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003856
Mike Stump87c57ac2009-05-16 07:39:55 +00003857 // Overall FIXME: we are recomputing too many types here and doing far too
3858 // much extra work. What this means is that we need to keep track of more
3859 // information that is computed when we try the implicit conversion initially,
3860 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003861 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003862
Douglas Gregor2fe98832008-11-03 19:09:14 +00003863 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003864 // FIXME: When can ToType be a reference type?
3865 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003866 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003867 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003868 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003869 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003870 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003871 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003872 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003873 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3874 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003875 ConstructorArgs, /*HadMultipleCandidates*/ false,
3876 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3877 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003878 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003879 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003880 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3881 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003882 From, /*HadMultipleCandidates*/ false,
3883 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3884 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003885 }
3886
Douglas Gregor980fb162010-04-29 18:24:40 +00003887 // Resolve overloaded function references.
3888 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3889 DeclAccessPair Found;
3890 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3891 true, Found);
3892 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003893 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003894
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003895 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003896 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregor980fb162010-04-29 18:24:40 +00003898 From = FixOverloadedFunctionReference(From, Found, Fn);
3899 FromType = From->getType();
3900 }
3901
Richard Smitha23ab512013-05-23 00:30:41 +00003902 // If we're converting to an atomic type, first convert to the corresponding
3903 // non-atomic type.
3904 QualType ToAtomicType;
3905 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3906 ToAtomicType = ToType;
3907 ToType = ToAtomic->getValueType();
3908 }
3909
George Burgess IV8d141e02015-12-14 22:00:49 +00003910 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003911 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003912 switch (SCS.First) {
3913 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003914 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3915 FromType = FromAtomic->getValueType().getUnqualifiedType();
3916 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3917 From, /*BasePath=*/nullptr, VK_RValue);
3918 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003919 break;
3920
Eli Friedman946b7b52012-01-24 22:51:26 +00003921 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003922 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003923 ExprResult FromRes = DefaultLvalueConversion(From);
3924 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003925 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003926 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003927 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003928 }
John McCall34376a62010-12-04 03:47:34 +00003929
Douglas Gregor39c16d42008-10-24 04:54:22 +00003930 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003931 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003932 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003933 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003934 break;
3935
3936 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003937 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003938 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003939 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003940 break;
3941
3942 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003943 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003944 }
3945
Richard Smith507840d2011-11-29 22:48:16 +00003946 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003947 switch (SCS.Second) {
3948 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003949 // C++ [except.spec]p5:
3950 // [For] assignment to and initialization of pointers to functions,
3951 // pointers to member functions, and references to functions: the
3952 // target entity shall allow at least the exceptions allowed by the
3953 // source value in the assignment or initialization.
3954 switch (Action) {
3955 case AA_Assigning:
3956 case AA_Initializing:
3957 // Note, function argument passing and returning are initialization.
3958 case AA_Passing:
3959 case AA_Returning:
3960 case AA_Sending:
3961 case AA_Passing_CFAudited:
3962 if (CheckExceptionSpecCompatibility(From, ToType))
3963 return ExprError();
3964 break;
3965
3966 case AA_Casting:
3967 case AA_Converting:
3968 // Casts and implicit conversions are not initialization, so are not
3969 // checked for exception specification mismatches.
3970 break;
3971 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003972 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003973 break;
3974
3975 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003976 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003977 if (ToType->isBooleanType()) {
3978 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3979 SCS.Second == ICK_Integral_Promotion &&
3980 "only enums with fixed underlying type can promote to bool");
3981 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003982 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003983 } else {
3984 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003985 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003986 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003987 break;
3988
3989 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003990 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003991 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003992 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003993 break;
3994
3995 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003996 case ICK_Complex_Conversion: {
3997 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3998 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3999 CastKind CK;
4000 if (FromEl->isRealFloatingType()) {
4001 if (ToEl->isRealFloatingType())
4002 CK = CK_FloatingComplexCast;
4003 else
4004 CK = CK_FloatingComplexToIntegralComplex;
4005 } else if (ToEl->isRealFloatingType()) {
4006 CK = CK_IntegralComplexToFloatingComplex;
4007 } else {
4008 CK = CK_IntegralComplexCast;
4009 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004010 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004011 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004012 break;
John McCall8cb679e2010-11-15 09:13:47 +00004013 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004014
Douglas Gregor39c16d42008-10-24 04:54:22 +00004015 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004016 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004017 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004018 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004019 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004020 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004021 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004022 break;
4023
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004024 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004025 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004026 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004027 break;
4028
John McCall31168b02011-06-15 23:02:42 +00004029 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004030 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004031 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004032 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004033 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004034 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004035 diag::ext_typecheck_convert_incompatible_pointer)
4036 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00004037 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004038 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004039 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004040 diag::ext_typecheck_convert_incompatible_pointer)
4041 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00004042 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00004043
Douglas Gregor33823722011-06-11 01:09:30 +00004044 if (From->getType()->isObjCObjectPointerType() &&
4045 ToType->isObjCObjectPointerType())
4046 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004047 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4048 !CheckObjCARCUnavailableWeakConversion(ToType,
4049 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004050 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00004051 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00004052 diag::err_arc_weak_unavailable_assign);
4053 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004054 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00004055 diag::err_arc_convesion_of_weak_unavailable)
4056 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00004057 << From->getSourceRange();
4058 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004059
Richard Smith354abec2017-12-08 23:29:59 +00004060 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004061 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004062 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004063 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004064
4065 // Make sure we extend blocks if necessary.
4066 // FIXME: doing this here is really ugly.
4067 if (Kind == CK_BlockPointerToObjCPointerCast) {
4068 ExprResult E = From;
4069 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004070 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004071 }
Brian Kelley11352a82017-03-29 18:09:02 +00004072 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4073 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004074 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004075 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004076 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004079 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004080 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004081 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004082 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004083 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004084 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004085 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004086
4087 // We may not have been able to figure out what this member pointer resolved
4088 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004089 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004090 (void)isCompleteType(From->getExprLoc(), From->getType());
4091 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004092 }
David Majnemerd96b9972014-08-08 00:10:39 +00004093
Richard Smith507840d2011-11-29 22:48:16 +00004094 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004095 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004096 break;
4097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004099 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004100 // Perform half-to-boolean conversion via float.
4101 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004102 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004103 FromType = Context.FloatTy;
4104 }
4105
Richard Smith507840d2011-11-29 22:48:16 +00004106 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004107 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004108 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004109 break;
4110
Douglas Gregor88d292c2010-05-13 16:44:06 +00004111 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004112 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004114 ToType.getNonReferenceType(),
4115 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004117 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00004118 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004119 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004120
Richard Smith507840d2011-11-29 22:48:16 +00004121 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4122 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004123 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004124 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004125 }
4126
Douglas Gregor46188682010-05-18 22:42:18 +00004127 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004128 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004129 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004130 break;
4131
George Burgess IVdf1ed002016-01-13 01:52:39 +00004132 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004133 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004134 Expr *Elem = prepareVectorSplat(ToType, From).get();
4135 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4136 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004137 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139
Douglas Gregor46188682010-05-18 22:42:18 +00004140 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004141 // Case 1. x -> _Complex y
4142 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4143 QualType ElType = ToComplex->getElementType();
4144 bool isFloatingComplex = ElType->isRealFloatingType();
4145
4146 // x -> y
4147 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4148 // do nothing
4149 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004150 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004151 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004152 } else {
4153 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004154 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004155 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004156 }
4157 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004158 From = ImpCastExprToType(From, ToType,
4159 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004160 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004161
4162 // Case 2. _Complex x -> y
4163 } else {
4164 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4165 assert(FromComplex);
4166
4167 QualType ElType = FromComplex->getElementType();
4168 bool isFloatingComplex = ElType->isRealFloatingType();
4169
4170 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004171 From = ImpCastExprToType(From, ElType,
4172 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004173 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004174 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004175
4176 // x -> y
4177 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4178 // do nothing
4179 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004180 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004181 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004182 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004183 } else {
4184 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004185 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004186 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004187 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004188 }
4189 }
Douglas Gregor46188682010-05-18 22:42:18 +00004190 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004191
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004192 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004193 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004194 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004195 break;
4196 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004197
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004198 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004199 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004200 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004201 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4202 if (FromRes.isInvalid())
4203 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004204 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004205 assert ((ConvTy == Sema::Compatible) &&
4206 "Improper transparent union conversion");
4207 (void)ConvTy;
4208 break;
4209 }
4210
Guy Benyei259f9f42013-02-07 16:05:33 +00004211 case ICK_Zero_Event_Conversion:
4212 From = ImpCastExprToType(From, ToType,
4213 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004214 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004215 break;
4216
Egor Churaev89831422016-12-23 14:55:49 +00004217 case ICK_Zero_Queue_Conversion:
4218 From = ImpCastExprToType(From, ToType,
4219 CK_ZeroToOCLQueue,
4220 From->getValueKind()).get();
4221 break;
4222
Douglas Gregor46188682010-05-18 22:42:18 +00004223 case ICK_Lvalue_To_Rvalue:
4224 case ICK_Array_To_Pointer:
4225 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004226 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004227 case ICK_Qualification:
4228 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004229 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004230 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004231 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004232 }
4233
4234 switch (SCS.Third) {
4235 case ICK_Identity:
4236 // Nothing to do.
4237 break;
4238
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004239 case ICK_Function_Conversion:
4240 // If both sides are functions (or pointers/references to them), there could
4241 // be incompatible exception declarations.
4242 if (CheckExceptionSpecCompatibility(From, ToType))
4243 return ExprError();
4244
4245 From = ImpCastExprToType(From, ToType, CK_NoOp,
4246 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4247 break;
4248
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004249 case ICK_Qualification: {
4250 // The qualification keeps the category of the inner expression, unless the
4251 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004252 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004253 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004254 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004255 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004256
Douglas Gregore981bb02011-03-14 16:13:32 +00004257 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004258 !getLangOpts().WritableStrings) {
4259 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4260 ? diag::ext_deprecated_string_literal_conversion
4261 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004262 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004263 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004264
Douglas Gregor39c16d42008-10-24 04:54:22 +00004265 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004266 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004267
Douglas Gregor39c16d42008-10-24 04:54:22 +00004268 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004269 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004270 }
4271
Douglas Gregor298f43d2012-04-12 20:42:30 +00004272 // If this conversion sequence involved a scalar -> atomic conversion, perform
4273 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004274 if (!ToAtomicType.isNull()) {
4275 assert(Context.hasSameType(
4276 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4277 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004278 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004279 }
4280
George Burgess IV8d141e02015-12-14 22:00:49 +00004281 // If this conversion sequence succeeded and involved implicitly converting a
4282 // _Nullable type to a _Nonnull one, complain.
4283 if (CCK == CCK_ImplicitConversion)
4284 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4285 From->getLocStart());
4286
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004287 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004288}
4289
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004290/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004291///
4292/// If the particular type trait requires a complete type, tries to complete
4293/// it. If completing the type fails, a diagnostic is emitted and false
4294/// returned. If completing the type succeeds or no completion was required,
4295/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004296static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004297 SourceLocation Loc,
4298 QualType ArgTy) {
4299 // C++0x [meta.unary.prop]p3:
4300 // For all of the class templates X declared in this Clause, instantiating
4301 // that template with a template argument that is a class template
4302 // specialization may result in the implicit instantiation of the template
4303 // argument if and only if the semantics of X require that the argument
4304 // must be a complete type.
4305 // We apply this rule to all the type trait expressions used to implement
4306 // these class templates. We also try to follow any GCC documented behavior
4307 // in these expressions to ensure portability of standard libraries.
4308 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004309 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004310 // is_complete_type somewhat obviously cannot require a complete type.
4311 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004312 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004313
4314 // These traits are modeled on the type predicates in C++0x
4315 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4316 // requiring a complete type, as whether or not they return true cannot be
4317 // impacted by the completeness of the type.
4318 case UTT_IsVoid:
4319 case UTT_IsIntegral:
4320 case UTT_IsFloatingPoint:
4321 case UTT_IsArray:
4322 case UTT_IsPointer:
4323 case UTT_IsLvalueReference:
4324 case UTT_IsRvalueReference:
4325 case UTT_IsMemberFunctionPointer:
4326 case UTT_IsMemberObjectPointer:
4327 case UTT_IsEnum:
4328 case UTT_IsUnion:
4329 case UTT_IsClass:
4330 case UTT_IsFunction:
4331 case UTT_IsReference:
4332 case UTT_IsArithmetic:
4333 case UTT_IsFundamental:
4334 case UTT_IsObject:
4335 case UTT_IsScalar:
4336 case UTT_IsCompound:
4337 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004338 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004339
4340 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4341 // which requires some of its traits to have the complete type. However,
4342 // the completeness of the type cannot impact these traits' semantics, and
4343 // so they don't require it. This matches the comments on these traits in
4344 // Table 49.
4345 case UTT_IsConst:
4346 case UTT_IsVolatile:
4347 case UTT_IsSigned:
4348 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004349
4350 // This type trait always returns false, checking the type is moot.
4351 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004352 return true;
4353
David Majnemer213bea32015-11-16 06:58:51 +00004354 // C++14 [meta.unary.prop]:
4355 // If T is a non-union class type, T shall be a complete type.
4356 case UTT_IsEmpty:
4357 case UTT_IsPolymorphic:
4358 case UTT_IsAbstract:
4359 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4360 if (!RD->isUnion())
4361 return !S.RequireCompleteType(
4362 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4363 return true;
4364
4365 // C++14 [meta.unary.prop]:
4366 // If T is a class type, T shall be a complete type.
4367 case UTT_IsFinal:
4368 case UTT_IsSealed:
4369 if (ArgTy->getAsCXXRecordDecl())
4370 return !S.RequireCompleteType(
4371 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4372 return true;
4373
Richard Smithf03e9082017-06-01 00:28:16 +00004374 // C++1z [meta.unary.prop]:
4375 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004376 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004377 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004378 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004379 case UTT_IsStandardLayout:
4380 case UTT_IsPOD:
4381 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004382 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4383 // or an array of unknown bound. But GCC actually imposes the same constraints
4384 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004385 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004386 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004387 case UTT_HasNothrowConstructor:
4388 case UTT_HasNothrowCopy:
4389 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004390 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004391 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004392 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004393 case UTT_HasTrivialCopy:
4394 case UTT_HasTrivialDestructor:
4395 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004396 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4397 LLVM_FALLTHROUGH;
4398
4399 // C++1z [meta.unary.prop]:
4400 // T shall be a complete type, cv void, or an array of unknown bound.
4401 case UTT_IsDestructible:
4402 case UTT_IsNothrowDestructible:
4403 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004404 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004405 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004406 return true;
4407
4408 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004409 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004410 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004411}
4412
Joao Matosc9523d42013-03-27 01:34:16 +00004413static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4414 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004415 bool (CXXRecordDecl::*HasTrivial)() const,
4416 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004417 bool (CXXMethodDecl::*IsDesiredOp)() const)
4418{
4419 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4420 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4421 return true;
4422
4423 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4424 DeclarationNameInfo NameInfo(Name, KeyLoc);
4425 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4426 if (Self.LookupQualifiedName(Res, RD)) {
4427 bool FoundOperator = false;
4428 Res.suppressDiagnostics();
4429 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4430 Op != OpEnd; ++Op) {
4431 if (isa<FunctionTemplateDecl>(*Op))
4432 continue;
4433
4434 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4435 if((Operator->*IsDesiredOp)()) {
4436 FoundOperator = true;
4437 const FunctionProtoType *CPT =
4438 Operator->getType()->getAs<FunctionProtoType>();
4439 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004440 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004441 return false;
4442 }
4443 }
4444 return FoundOperator;
4445 }
4446 return false;
4447}
4448
Alp Toker95e7ff22014-01-01 05:57:51 +00004449static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004450 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004451 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004452
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004453 ASTContext &C = Self.Context;
4454 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004455 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004456 // Type trait expressions corresponding to the primary type category
4457 // predicates in C++0x [meta.unary.cat].
4458 case UTT_IsVoid:
4459 return T->isVoidType();
4460 case UTT_IsIntegral:
4461 return T->isIntegralType(C);
4462 case UTT_IsFloatingPoint:
4463 return T->isFloatingType();
4464 case UTT_IsArray:
4465 return T->isArrayType();
4466 case UTT_IsPointer:
4467 return T->isPointerType();
4468 case UTT_IsLvalueReference:
4469 return T->isLValueReferenceType();
4470 case UTT_IsRvalueReference:
4471 return T->isRValueReferenceType();
4472 case UTT_IsMemberFunctionPointer:
4473 return T->isMemberFunctionPointerType();
4474 case UTT_IsMemberObjectPointer:
4475 return T->isMemberDataPointerType();
4476 case UTT_IsEnum:
4477 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004478 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004479 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004480 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004481 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004482 case UTT_IsFunction:
4483 return T->isFunctionType();
4484
4485 // Type trait expressions which correspond to the convenient composition
4486 // predicates in C++0x [meta.unary.comp].
4487 case UTT_IsReference:
4488 return T->isReferenceType();
4489 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004490 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004491 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004492 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004493 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004494 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004495 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004496 // Note: semantic analysis depends on Objective-C lifetime types to be
4497 // considered scalar types. However, such types do not actually behave
4498 // like scalar types at run time (since they may require retain/release
4499 // operations), so we report them as non-scalar.
4500 if (T->isObjCLifetimeType()) {
4501 switch (T.getObjCLifetime()) {
4502 case Qualifiers::OCL_None:
4503 case Qualifiers::OCL_ExplicitNone:
4504 return true;
4505
4506 case Qualifiers::OCL_Strong:
4507 case Qualifiers::OCL_Weak:
4508 case Qualifiers::OCL_Autoreleasing:
4509 return false;
4510 }
4511 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004512
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004513 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004514 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004515 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004516 case UTT_IsMemberPointer:
4517 return T->isMemberPointerType();
4518
4519 // Type trait expressions which correspond to the type property predicates
4520 // in C++0x [meta.unary.prop].
4521 case UTT_IsConst:
4522 return T.isConstQualified();
4523 case UTT_IsVolatile:
4524 return T.isVolatileQualified();
4525 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004526 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004527 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004528 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004529 case UTT_IsStandardLayout:
4530 return T->isStandardLayoutType();
4531 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004532 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004533 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004534 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004535 case UTT_IsEmpty:
4536 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4537 return !RD->isUnion() && RD->isEmpty();
4538 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004539 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004540 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004541 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004542 return false;
4543 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004544 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004545 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004546 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004547 case UTT_IsAggregate:
4548 // Report vector extensions and complex types as aggregates because they
4549 // support aggregate initialization. GCC mirrors this behavior for vectors
4550 // but not _Complex.
4551 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4552 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004553 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4554 // even then only when it is used with the 'interface struct ...' syntax
4555 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004556 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004557 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004558 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004559 case UTT_IsSealed:
4560 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004561 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004562 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004563 case UTT_IsSigned:
4564 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004565 case UTT_IsUnsigned:
4566 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004567
4568 // Type trait expressions which query classes regarding their construction,
4569 // destruction, and copying. Rather than being based directly on the
4570 // related type predicates in the standard, they are specified by both
4571 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4572 // specifications.
4573 //
4574 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4575 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004576 //
4577 // Note that these builtins do not behave as documented in g++: if a class
4578 // has both a trivial and a non-trivial special member of a particular kind,
4579 // they return false! For now, we emulate this behavior.
4580 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4581 // does not correctly compute triviality in the presence of multiple special
4582 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004583 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004584 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4585 // If __is_pod (type) is true then the trait is true, else if type is
4586 // a cv class or union type (or array thereof) with a trivial default
4587 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004588 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004589 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004590 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4591 return RD->hasTrivialDefaultConstructor() &&
4592 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004593 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004594 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004595 // This trait is implemented by MSVC 2012 and needed to parse the
4596 // standard library headers. Specifically this is used as the logic
4597 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004598 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004599 return true;
4600 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4601 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4602 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004603 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004604 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4605 // If __is_pod (type) is true or type is a reference type then
4606 // the trait is true, else if type is a cv class or union type
4607 // with a trivial copy constructor ([class.copy]) then the trait
4608 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004609 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004610 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004611 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4612 return RD->hasTrivialCopyConstructor() &&
4613 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004614 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004615 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004616 // This trait is implemented by MSVC 2012 and needed to parse the
4617 // standard library headers. Specifically it is used as the logic
4618 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004619 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004620 return true;
4621 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4622 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4623 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004624 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004625 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4626 // If type is const qualified or is a reference type then the
4627 // trait is false. Otherwise if __is_pod (type) is true then the
4628 // trait is true, else if type is a cv class or union type with
4629 // a trivial copy assignment ([class.copy]) then the trait is
4630 // true, else it is false.
4631 // Note: the const and reference restrictions are interesting,
4632 // given that const and reference members don't prevent a class
4633 // from having a trivial copy assignment operator (but do cause
4634 // errors if the copy assignment operator is actually used, q.v.
4635 // [class.copy]p12).
4636
Richard Smith92f241f2012-12-08 02:53:02 +00004637 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004638 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004639 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004640 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004641 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4642 return RD->hasTrivialCopyAssignment() &&
4643 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004644 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004645 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004646 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004647 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004648 // C++14 [meta.unary.prop]:
4649 // For reference types, is_destructible<T>::value is true.
4650 if (T->isReferenceType())
4651 return true;
4652
4653 // Objective-C++ ARC: autorelease types don't require destruction.
4654 if (T->isObjCLifetimeType() &&
4655 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4656 return true;
4657
4658 // C++14 [meta.unary.prop]:
4659 // For incomplete types and function types, is_destructible<T>::value is
4660 // false.
4661 if (T->isIncompleteType() || T->isFunctionType())
4662 return false;
4663
Richard Smithf03e9082017-06-01 00:28:16 +00004664 // A type that requires destruction (via a non-trivial destructor or ARC
4665 // lifetime semantics) is not trivially-destructible.
4666 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4667 return false;
4668
David Majnemerac73de92015-08-11 03:03:28 +00004669 // C++14 [meta.unary.prop]:
4670 // For object types and given U equal to remove_all_extents_t<T>, if the
4671 // expression std::declval<U&>().~U() is well-formed when treated as an
4672 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4673 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4674 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4675 if (!Destructor)
4676 return false;
4677 // C++14 [dcl.fct.def.delete]p2:
4678 // A program that refers to a deleted function implicitly or
4679 // explicitly, other than to declare it, is ill-formed.
4680 if (Destructor->isDeleted())
4681 return false;
4682 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4683 return false;
4684 if (UTT == UTT_IsNothrowDestructible) {
4685 const FunctionProtoType *CPT =
4686 Destructor->getType()->getAs<FunctionProtoType>();
4687 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004688 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004689 return false;
4690 }
4691 }
4692 return true;
4693
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004694 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004695 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004696 // If __is_pod (type) is true or type is a reference type
4697 // then the trait is true, else if type is a cv class or union
4698 // type (or array thereof) with a trivial destructor
4699 // ([class.dtor]) then the trait is true, else it is
4700 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004701 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004702 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004703
John McCall31168b02011-06-15 23:02:42 +00004704 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004705 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004706 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4707 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004708
Richard Smith92f241f2012-12-08 02:53:02 +00004709 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4710 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004711 return false;
4712 // TODO: Propagate nothrowness for implicitly declared special members.
4713 case UTT_HasNothrowAssign:
4714 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4715 // If type is const qualified or is a reference type then the
4716 // trait is false. Otherwise if __has_trivial_assign (type)
4717 // is true then the trait is true, else if type is a cv class
4718 // or union type with copy assignment operators that are known
4719 // not to throw an exception then the trait is true, else it is
4720 // false.
4721 if (C.getBaseElementType(T).isConstQualified())
4722 return false;
4723 if (T->isReferenceType())
4724 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004725 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004726 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004727
Joao Matosc9523d42013-03-27 01:34:16 +00004728 if (const RecordType *RT = T->getAs<RecordType>())
4729 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4730 &CXXRecordDecl::hasTrivialCopyAssignment,
4731 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4732 &CXXMethodDecl::isCopyAssignmentOperator);
4733 return false;
4734 case UTT_HasNothrowMoveAssign:
4735 // This trait is implemented by MSVC 2012 and needed to parse the
4736 // standard library headers. Specifically this is used as the logic
4737 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004738 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004739 return true;
4740
4741 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4742 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4743 &CXXRecordDecl::hasTrivialMoveAssignment,
4744 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4745 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004746 return false;
4747 case UTT_HasNothrowCopy:
4748 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4749 // If __has_trivial_copy (type) is true then the trait is true, else
4750 // if type is a cv class or union type with copy constructors that are
4751 // known not to throw an exception then the trait is true, else it is
4752 // false.
John McCall31168b02011-06-15 23:02:42 +00004753 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004754 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004755 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4756 if (RD->hasTrivialCopyConstructor() &&
4757 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004758 return true;
4759
4760 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004761 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004762 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004763 // A template constructor is never a copy constructor.
4764 // FIXME: However, it may actually be selected at the actual overload
4765 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004766 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004767 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004768 // UsingDecl itself is not a constructor
4769 if (isa<UsingDecl>(ND))
4770 continue;
4771 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004772 if (Constructor->isCopyConstructor(FoundTQs)) {
4773 FoundConstructor = true;
4774 const FunctionProtoType *CPT
4775 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004776 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4777 if (!CPT)
4778 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004779 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004780 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004781 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004782 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004783 }
4784 }
4785
Richard Smith938f40b2011-06-11 17:19:42 +00004786 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004787 }
4788 return false;
4789 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004790 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004791 // If __has_trivial_constructor (type) is true then the trait is
4792 // true, else if type is a cv class or union type (or array
4793 // thereof) with a default constructor that is known not to
4794 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004795 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004796 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004797 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4798 if (RD->hasTrivialDefaultConstructor() &&
4799 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004800 return true;
4801
Alp Tokerb4bca412014-01-20 00:23:47 +00004802 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004803 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004804 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004805 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004806 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004807 // UsingDecl itself is not a constructor
4808 if (isa<UsingDecl>(ND))
4809 continue;
4810 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004811 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004812 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004813 const FunctionProtoType *CPT
4814 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004815 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4816 if (!CPT)
4817 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004818 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004819 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004820 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004821 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004822 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004823 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004824 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004825 }
4826 return false;
4827 case UTT_HasVirtualDestructor:
4828 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4829 // If type is a class type with a virtual destructor ([class.dtor])
4830 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004831 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004832 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004833 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004834 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004835
4836 // These type trait expressions are modeled on the specifications for the
4837 // Embarcadero C++0x type trait functions:
4838 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4839 case UTT_IsCompleteType:
4840 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4841 // Returns True if and only if T is a complete type at the point of the
4842 // function call.
4843 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004844 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004845 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004846 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004847}
Sebastian Redl5822f082009-02-07 20:10:22 +00004848
Alp Tokercbb90342013-12-13 20:49:58 +00004849static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4850 QualType RhsT, SourceLocation KeyLoc);
4851
Douglas Gregor29c42f22012-02-24 07:38:34 +00004852static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4853 ArrayRef<TypeSourceInfo *> Args,
4854 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004855 if (Kind <= UTT_Last)
4856 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4857
Eric Fiselier1af6c112018-01-12 00:09:37 +00004858 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4859 // traits to avoid duplication.
4860 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004861 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4862 Args[1]->getType(), RParenLoc);
4863
Douglas Gregor29c42f22012-02-24 07:38:34 +00004864 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004865 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004866 case clang::TT_IsConstructible:
4867 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004868 case clang::TT_IsTriviallyConstructible: {
4869 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004870 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004871 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004872 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004873 // definition for is_constructible, as defined below, is known to call
4874 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004875 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004876 // The predicate condition for a template specialization
4877 // is_constructible<T, Args...> shall be satisfied if and only if the
4878 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004879 // variable t:
4880 //
4881 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004882 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004883
4884 // Precondition: T and all types in the parameter pack Args shall be
4885 // complete types, (possibly cv-qualified) void, or arrays of
4886 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004887 for (const auto *TSI : Args) {
4888 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004889 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004890 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004891
Simon Pilgrim75c26882016-09-30 14:25:09 +00004892 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004893 diag::err_incomplete_type_used_in_type_trait_expr))
4894 return false;
4895 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004896
David Majnemer9658ecc2015-11-13 05:32:43 +00004897 // Make sure the first argument is not incomplete nor a function type.
4898 QualType T = Args[0]->getType();
4899 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004900 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004901
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004902 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004903 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004904 if (RD && RD->isAbstract())
4905 return false;
4906
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004907 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4908 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004909 ArgExprs.reserve(Args.size() - 1);
4910 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004911 QualType ArgTy = Args[I]->getType();
4912 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4913 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004914 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004915 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4916 ArgTy.getNonLValueExprType(S.Context),
4917 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004918 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004919 for (Expr &E : OpaqueArgExprs)
4920 ArgExprs.push_back(&E);
4921
Simon Pilgrim75c26882016-09-30 14:25:09 +00004922 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004923 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004924 EnterExpressionEvaluationContext Unevaluated(
4925 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004926 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4927 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4928 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4929 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4930 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004931 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004932 if (Init.Failed())
4933 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004934
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004935 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004936 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4937 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004938
Alp Toker73287bf2014-01-20 00:24:09 +00004939 if (Kind == clang::TT_IsConstructible)
4940 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004941
Eric Fiselier1af6c112018-01-12 00:09:37 +00004942 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4943 if (!T->isReferenceType())
4944 return false;
4945
4946 return !Init.isDirectReferenceBinding();
4947 }
4948
Alp Toker73287bf2014-01-20 00:24:09 +00004949 if (Kind == clang::TT_IsNothrowConstructible)
4950 return S.canThrow(Result.get()) == CT_Cannot;
4951
4952 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004953 // Under Objective-C ARC and Weak, if the destination has non-trivial
4954 // Objective-C lifetime, this is a non-trivial construction.
4955 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004956 return false;
4957
4958 // The initialization succeeded; now make sure there are no non-trivial
4959 // calls.
4960 return !Result.get()->hasNonTrivialCall(S.Context);
4961 }
4962
4963 llvm_unreachable("unhandled type trait");
4964 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004965 }
Alp Tokercbb90342013-12-13 20:49:58 +00004966 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004967 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004968
Douglas Gregor29c42f22012-02-24 07:38:34 +00004969 return false;
4970}
4971
Simon Pilgrim75c26882016-09-30 14:25:09 +00004972ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4973 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004974 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004975 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004976
Alp Toker95e7ff22014-01-01 05:57:51 +00004977 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4978 *this, Kind, KWLoc, Args[0]->getType()))
4979 return ExprError();
4980
Douglas Gregor29c42f22012-02-24 07:38:34 +00004981 bool Dependent = false;
4982 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4983 if (Args[I]->getType()->isDependentType()) {
4984 Dependent = true;
4985 break;
4986 }
4987 }
Alp Tokercbb90342013-12-13 20:49:58 +00004988
4989 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004990 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004991 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4992
4993 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4994 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004995}
4996
Alp Toker88f64e62013-12-13 21:19:30 +00004997ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4998 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004999 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005000 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005001 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005002
Douglas Gregor29c42f22012-02-24 07:38:34 +00005003 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5004 TypeSourceInfo *TInfo;
5005 QualType T = GetTypeFromParser(Args[I], &TInfo);
5006 if (!TInfo)
5007 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005008
5009 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005010 }
Alp Tokercbb90342013-12-13 20:49:58 +00005011
Douglas Gregor29c42f22012-02-24 07:38:34 +00005012 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5013}
5014
Alp Tokercbb90342013-12-13 20:49:58 +00005015static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5016 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005017 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5018 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005019
5020 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005021 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005022 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005023 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005024 // Base and Derived are not unions and name the same class type without
5025 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005026
John McCall388ef532011-01-28 22:02:36 +00005027 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005028 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005029 if (!rhsRecord || !lhsRecord) {
5030 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5031 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5032 if (!LHSObjTy || !RHSObjTy)
5033 return false;
5034
5035 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5036 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5037 if (!BaseInterface || !DerivedInterface)
5038 return false;
5039
5040 if (Self.RequireCompleteType(
5041 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5042 return false;
5043
5044 return BaseInterface->isSuperClassOf(DerivedInterface);
5045 }
John McCall388ef532011-01-28 22:02:36 +00005046
5047 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5048 == (lhsRecord == rhsRecord));
5049
5050 if (lhsRecord == rhsRecord)
5051 return !lhsRecord->getDecl()->isUnion();
5052
5053 // C++0x [meta.rel]p2:
5054 // If Base and Derived are class types and are different types
5055 // (ignoring possible cv-qualifiers) then Derived shall be a
5056 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005057 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005058 diag::err_incomplete_type_used_in_type_trait_expr))
5059 return false;
5060
5061 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5062 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5063 }
John Wiegley65497cc2011-04-27 23:09:49 +00005064 case BTT_IsSame:
5065 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005066 case BTT_TypeCompatible: {
5067 // GCC ignores cv-qualifiers on arrays for this builtin.
5068 Qualifiers LhsQuals, RhsQuals;
5069 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5070 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5071 return Self.Context.typesAreCompatible(Lhs, Rhs);
5072 }
John Wiegley65497cc2011-04-27 23:09:49 +00005073 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005074 case BTT_IsConvertibleTo: {
5075 // C++0x [meta.rel]p4:
5076 // Given the following function prototype:
5077 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005078 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005079 // typename add_rvalue_reference<T>::type create();
5080 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005081 // the predicate condition for a template specialization
5082 // is_convertible<From, To> shall be satisfied if and only if
5083 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005084 // well-formed, including any implicit conversions to the return
5085 // type of the function:
5086 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005087 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005088 // return create<From>();
5089 // }
5090 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005091 // Access checking is performed as if in a context unrelated to To and
5092 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005093 // of the return-statement (including conversions to the return type)
5094 // is considered.
5095 //
5096 // We model the initialization as a copy-initialization of a temporary
5097 // of the appropriate type, which for this expression is identical to the
5098 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005099
5100 // Functions aren't allowed to return function or array types.
5101 if (RhsT->isFunctionType() || RhsT->isArrayType())
5102 return false;
5103
5104 // A return statement in a void function must have void type.
5105 if (RhsT->isVoidType())
5106 return LhsT->isVoidType();
5107
5108 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005109 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005110 return false;
5111
5112 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005113 if (LhsT->isObjectType() || LhsT->isFunctionType())
5114 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005115
5116 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005117 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005118 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005119 Expr::getValueKindForType(LhsT));
5120 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005121 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005122 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005123
5124 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005125 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005126 EnterExpressionEvaluationContext Unevaluated(
5127 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005128 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5129 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005130 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005131 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005132 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005133
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005134 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005135 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5136 }
Alp Toker73287bf2014-01-20 00:24:09 +00005137
David Majnemerb3d96882016-05-23 17:21:55 +00005138 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005139 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005140 case BTT_IsTriviallyAssignable: {
5141 // C++11 [meta.unary.prop]p3:
5142 // is_trivially_assignable is defined as:
5143 // is_assignable<T, U>::value is true and the assignment, as defined by
5144 // is_assignable, is known to call no operation that is not trivial
5145 //
5146 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005147 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005148 // treated as an unevaluated operand (Clause 5).
5149 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005150 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005151 // void, or arrays of unknown bound.
5152 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005153 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005154 diag::err_incomplete_type_used_in_type_trait_expr))
5155 return false;
5156 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005157 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005158 diag::err_incomplete_type_used_in_type_trait_expr))
5159 return false;
5160
5161 // cv void is never assignable.
5162 if (LhsT->isVoidType() || RhsT->isVoidType())
5163 return false;
5164
Simon Pilgrim75c26882016-09-30 14:25:09 +00005165 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005166 // declval<U>().
5167 if (LhsT->isObjectType() || LhsT->isFunctionType())
5168 LhsT = Self.Context.getRValueReferenceType(LhsT);
5169 if (RhsT->isObjectType() || RhsT->isFunctionType())
5170 RhsT = Self.Context.getRValueReferenceType(RhsT);
5171 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5172 Expr::getValueKindForType(LhsT));
5173 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5174 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005175
5176 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005177 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005178 EnterExpressionEvaluationContext Unevaluated(
5179 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005180 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005181 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005182 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5183 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005184 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5185 return false;
5186
David Majnemerb3d96882016-05-23 17:21:55 +00005187 if (BTT == BTT_IsAssignable)
5188 return true;
5189
Alp Toker73287bf2014-01-20 00:24:09 +00005190 if (BTT == BTT_IsNothrowAssignable)
5191 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005192
Alp Toker73287bf2014-01-20 00:24:09 +00005193 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005194 // Under Objective-C ARC and Weak, if the destination has non-trivial
5195 // Objective-C lifetime, this is a non-trivial assignment.
5196 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005197 return false;
5198
5199 return !Result.get()->hasNonTrivialCall(Self.Context);
5200 }
5201
5202 llvm_unreachable("unhandled type trait");
5203 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005204 }
Alp Tokercbb90342013-12-13 20:49:58 +00005205 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005206 }
5207 llvm_unreachable("Unknown type trait or not implemented");
5208}
5209
John Wiegley6242b6a2011-04-28 00:16:57 +00005210ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5211 SourceLocation KWLoc,
5212 ParsedType Ty,
5213 Expr* DimExpr,
5214 SourceLocation RParen) {
5215 TypeSourceInfo *TSInfo;
5216 QualType T = GetTypeFromParser(Ty, &TSInfo);
5217 if (!TSInfo)
5218 TSInfo = Context.getTrivialTypeSourceInfo(T);
5219
5220 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5221}
5222
5223static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5224 QualType T, Expr *DimExpr,
5225 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005226 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005227
5228 switch(ATT) {
5229 case ATT_ArrayRank:
5230 if (T->isArrayType()) {
5231 unsigned Dim = 0;
5232 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5233 ++Dim;
5234 T = AT->getElementType();
5235 }
5236 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005237 }
John Wiegleyd3522222011-04-28 02:06:46 +00005238 return 0;
5239
John Wiegley6242b6a2011-04-28 00:16:57 +00005240 case ATT_ArrayExtent: {
5241 llvm::APSInt Value;
5242 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005243 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005244 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005245 false).isInvalid())
5246 return 0;
5247 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005248 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5249 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005250 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005251 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005252 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005253
5254 if (T->isArrayType()) {
5255 unsigned D = 0;
5256 bool Matched = false;
5257 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5258 if (Dim == D) {
5259 Matched = true;
5260 break;
5261 }
5262 ++D;
5263 T = AT->getElementType();
5264 }
5265
John Wiegleyd3522222011-04-28 02:06:46 +00005266 if (Matched && T->isArrayType()) {
5267 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5268 return CAT->getSize().getLimitedValue();
5269 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005270 }
John Wiegleyd3522222011-04-28 02:06:46 +00005271 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005272 }
5273 }
5274 llvm_unreachable("Unknown type trait or not implemented");
5275}
5276
5277ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5278 SourceLocation KWLoc,
5279 TypeSourceInfo *TSInfo,
5280 Expr* DimExpr,
5281 SourceLocation RParen) {
5282 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005283
Chandler Carruthc5276e52011-05-01 08:48:21 +00005284 // FIXME: This should likely be tracked as an APInt to remove any host
5285 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005286 uint64_t Value = 0;
5287 if (!T->isDependentType())
5288 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5289
Chandler Carruthc5276e52011-05-01 08:48:21 +00005290 // While the specification for these traits from the Embarcadero C++
5291 // compiler's documentation says the return type is 'unsigned int', Clang
5292 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5293 // compiler, there is no difference. On several other platforms this is an
5294 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005295 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5296 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005297}
5298
John Wiegleyf9f65842011-04-25 06:54:41 +00005299ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005300 SourceLocation KWLoc,
5301 Expr *Queried,
5302 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005303 // If error parsing the expression, ignore.
5304 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005305 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005306
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005307 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005308
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005309 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005310}
5311
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005312static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5313 switch (ET) {
5314 case ET_IsLValueExpr: return E->isLValue();
5315 case ET_IsRValueExpr: return E->isRValue();
5316 }
5317 llvm_unreachable("Expression trait not covered by switch");
5318}
5319
John Wiegleyf9f65842011-04-25 06:54:41 +00005320ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005321 SourceLocation KWLoc,
5322 Expr *Queried,
5323 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005324 if (Queried->isTypeDependent()) {
5325 // Delay type-checking for type-dependent expressions.
5326 } else if (Queried->getType()->isPlaceholderType()) {
5327 ExprResult PE = CheckPlaceholderExpr(Queried);
5328 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005329 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005330 }
5331
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005332 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005333
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005334 return new (Context)
5335 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005336}
5337
Richard Trieu82402a02011-09-15 21:56:47 +00005338QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005339 ExprValueKind &VK,
5340 SourceLocation Loc,
5341 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005342 assert(!LHS.get()->getType()->isPlaceholderType() &&
5343 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005344 "placeholders should have been weeded out by now");
5345
Richard Smith4baaa5a2016-12-03 01:14:32 +00005346 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5347 // temporary materialization conversion otherwise.
5348 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005349 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005350 else if (LHS.get()->isRValue())
5351 LHS = TemporaryMaterializationConversion(LHS.get());
5352 if (LHS.isInvalid())
5353 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005354
5355 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005356 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005357 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005358
Sebastian Redl5822f082009-02-07 20:10:22 +00005359 const char *OpSpelling = isIndirect ? "->*" : ".*";
5360 // C++ 5.5p2
5361 // The binary operator .* [p3: ->*] binds its second operand, which shall
5362 // be of type "pointer to member of T" (where T is a completely-defined
5363 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005364 QualType RHSType = RHS.get()->getType();
5365 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005366 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005367 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005368 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005369 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005370 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005371
Sebastian Redl5822f082009-02-07 20:10:22 +00005372 QualType Class(MemPtr->getClass(), 0);
5373
Douglas Gregord07ba342010-10-13 20:41:14 +00005374 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5375 // member pointer points must be completely-defined. However, there is no
5376 // reason for this semantic distinction, and the rule is not enforced by
5377 // other compilers. Therefore, we do not check this property, as it is
5378 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005379
Sebastian Redl5822f082009-02-07 20:10:22 +00005380 // C++ 5.5p2
5381 // [...] to its first operand, which shall be of class T or of a class of
5382 // which T is an unambiguous and accessible base class. [p3: a pointer to
5383 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005384 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005385 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005386 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5387 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005388 else {
5389 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005390 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005391 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005392 return QualType();
5393 }
5394 }
5395
Richard Trieu82402a02011-09-15 21:56:47 +00005396 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005397 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005398 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5399 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005400 return QualType();
5401 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005402
Richard Smith0f59cb32015-12-18 21:45:41 +00005403 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005404 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005405 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005406 return QualType();
5407 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005408
5409 CXXCastPath BasePath;
5410 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5411 SourceRange(LHS.get()->getLocStart(),
5412 RHS.get()->getLocEnd()),
5413 &BasePath))
5414 return QualType();
5415
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005416 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005417 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5418 if (isIndirect)
5419 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005420 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005421 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005422 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005423 }
5424
Richard Trieu82402a02011-09-15 21:56:47 +00005425 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005426 // Diagnose use of pointer-to-member type which when used as
5427 // the functional cast in a pointer-to-member expression.
5428 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5429 return QualType();
5430 }
John McCall7decc9e2010-11-18 06:31:45 +00005431
Sebastian Redl5822f082009-02-07 20:10:22 +00005432 // C++ 5.5p2
5433 // The result is an object or a function of the type specified by the
5434 // second operand.
5435 // The cv qualifiers are the union of those in the pointer and the left side,
5436 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005437 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005438 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005439
Douglas Gregor1d042092011-01-26 16:40:18 +00005440 // C++0x [expr.mptr.oper]p6:
5441 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005442 // ill-formed if the second operand is a pointer to member function with
5443 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5444 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005445 // is a pointer to member function with ref-qualifier &&.
5446 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5447 switch (Proto->getRefQualifier()) {
5448 case RQ_None:
5449 // Do nothing
5450 break;
5451
5452 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005453 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5454 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5455 if (Proto->isConst())
5456 Diag(Loc, getLangOpts().CPlusPlus2a
5457 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5458 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5459 else
5460 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5461 << RHSType << 1 << LHS.get()->getSourceRange();
5462 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005463 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Douglas Gregor1d042092011-01-26 16:40:18 +00005465 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005466 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005467 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005468 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005469 break;
5470 }
5471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472
John McCall7decc9e2010-11-18 06:31:45 +00005473 // C++ [expr.mptr.oper]p6:
5474 // The result of a .* expression whose second operand is a pointer
5475 // to a data member is of the same value category as its
5476 // first operand. The result of a .* expression whose second
5477 // operand is a pointer to a member function is a prvalue. The
5478 // result of an ->* expression is an lvalue if its second operand
5479 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005480 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005481 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005482 return Context.BoundMemberTy;
5483 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005484 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005485 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005486 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005487 }
John McCall7decc9e2010-11-18 06:31:45 +00005488
Sebastian Redl5822f082009-02-07 20:10:22 +00005489 return Result;
5490}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005492/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005493///
5494/// This is part of the parameter validation for the ? operator. If either
5495/// value operand is a class type, the two operands are attempted to be
5496/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005497/// It returns true if the program is ill-formed and has already been diagnosed
5498/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005499static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5500 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005501 bool &HaveConversion,
5502 QualType &ToType) {
5503 HaveConversion = false;
5504 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
5506 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005507 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005508 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005509 // The process for determining whether an operand expression E1 of type T1
5510 // can be converted to match an operand expression E2 of type T2 is defined
5511 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005512 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5513 // implicitly converted to type "lvalue reference to T2", subject to the
5514 // constraint that in the conversion the reference must bind directly to
5515 // an lvalue.
5516 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005517 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005518 // the constraint that the reference must bind directly.
5519 if (To->isLValue() || To->isXValue()) {
5520 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5521 : Self.Context.getRValueReferenceType(ToType);
5522
Douglas Gregor838fcc32010-03-26 20:14:36 +00005523 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005525 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005526 if (InitSeq.isDirectReferenceBinding()) {
5527 ToType = T;
5528 HaveConversion = true;
5529 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531
Douglas Gregor838fcc32010-03-26 20:14:36 +00005532 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005533 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005534 }
John McCall65eb8792010-02-25 01:37:24 +00005535
Sebastian Redl1a99f442009-04-16 17:51:27 +00005536 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5537 // -- if E1 and E2 have class type, and the underlying class types are
5538 // the same or one is a base class of the other:
5539 QualType FTy = From->getType();
5540 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005541 const RecordType *FRec = FTy->getAs<RecordType>();
5542 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005543 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005544 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5545 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5546 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005547 // E1 can be converted to match E2 if the class of T2 is the
5548 // same type as, or a base class of, the class of T1, and
5549 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005550 if (FRec == TRec || FDerivedFromT) {
5551 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005552 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005553 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005554 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005555 HaveConversion = true;
5556 return false;
5557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Douglas Gregor838fcc32010-03-26 20:14:36 +00005559 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005560 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005561 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Douglas Gregor838fcc32010-03-26 20:14:36 +00005564 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566
Douglas Gregor838fcc32010-03-26 20:14:36 +00005567 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5568 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005570 // an rvalue).
5571 //
5572 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5573 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005574 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575
Douglas Gregor838fcc32010-03-26 20:14:36 +00005576 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005577 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005578 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005579 ToType = TTy;
5580 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005581 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005582
Sebastian Redl1a99f442009-04-16 17:51:27 +00005583 return false;
5584}
5585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005586/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005587///
5588/// This is part of the parameter validation for the ? operator. If either
5589/// value operand is a class type, overload resolution is used to find a
5590/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005591static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005592 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005593 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005594 OverloadCandidateSet CandidateSet(QuestionLoc,
5595 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005596 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005597 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005598
5599 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005600 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005601 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005602 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005603 ExprResult LHSRes = Self.PerformImplicitConversion(
5604 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5605 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005606 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005607 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005608 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005609
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005610 ExprResult RHSRes = Self.PerformImplicitConversion(
5611 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5612 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005613 if (RHSRes.isInvalid())
5614 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005615 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005616 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005617 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005618 return false;
John Wiegley01296292011-04-08 18:41:53 +00005619 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005621 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005622
5623 // Emit a better diagnostic if one of the expressions is a null pointer
5624 // constant and the other is a pointer type. In this case, the user most
5625 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005626 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005627 return true;
5628
5629 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005630 << LHS.get()->getType() << RHS.get()->getType()
5631 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005632 return true;
5633
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005634 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005635 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005636 << LHS.get()->getType() << RHS.get()->getType()
5637 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005638 // FIXME: Print the possible common types by printing the return types of
5639 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005640 break;
5641
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005642 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005643 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005644 }
5645 return true;
5646}
5647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005648/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005649/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005650static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005651 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005652 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005653 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005654 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005655 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005656 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005657 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005658 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659
John Wiegley01296292011-04-08 18:41:53 +00005660 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005661 return false;
5662}
5663
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005664/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005665///
5666/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5667/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005668QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5669 ExprResult &RHS, ExprValueKind &VK,
5670 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005671 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005672 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5673 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005674
Richard Smith45edb702012-08-07 22:06:48 +00005675 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005676 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005677 //
5678 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5679 // a is that of a integer vector with the same number of elements and
5680 // size as the vectors of b and c. If one of either b or c is a scalar
5681 // it is implicitly converted to match the type of the vector.
5682 // Otherwise the expression is ill-formed. If both b and c are scalars,
5683 // then b and c are checked and converted to the type of a if possible.
5684 // Unlike the OpenCL ?: operator, the expression is evaluated as
5685 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005686 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005687 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005688 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005689 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005690 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005691 }
5692
John McCall7decc9e2010-11-18 06:31:45 +00005693 // Assume r-value.
5694 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005695 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005696
Sebastian Redl1a99f442009-04-16 17:51:27 +00005697 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005698 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005699 return Context.DependentTy;
5700
Richard Smith45edb702012-08-07 22:06:48 +00005701 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005702 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005703 QualType LTy = LHS.get()->getType();
5704 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005705 bool LVoid = LTy->isVoidType();
5706 bool RVoid = RTy->isVoidType();
5707 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005708 // ... one of the following shall hold:
5709 // -- The second or the third operand (but not both) is a (possibly
5710 // parenthesized) throw-expression; the result is of the type
5711 // and value category of the other.
5712 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5713 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5714 if (LThrow != RThrow) {
5715 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5716 VK = NonThrow->getValueKind();
5717 // DR (no number yet): the result is a bit-field if the
5718 // non-throw-expression operand is a bit-field.
5719 OK = NonThrow->getObjectKind();
5720 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005721 }
5722
Sebastian Redl1a99f442009-04-16 17:51:27 +00005723 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005724 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005725 if (LVoid && RVoid)
5726 return Context.VoidTy;
5727
5728 // Neither holds, error.
5729 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5730 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005731 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005732 return QualType();
5733 }
5734
5735 // Neither is void.
5736
Richard Smithf2b084f2012-08-08 06:13:49 +00005737 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005738 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005739 // either has (cv) class type [...] an attempt is made to convert each of
5740 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005742 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005743 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005744 QualType L2RType, R2LType;
5745 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005746 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005747 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005748 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005749 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750
Sebastian Redl1a99f442009-04-16 17:51:27 +00005751 // If both can be converted, [...] the program is ill-formed.
5752 if (HaveL2R && HaveR2L) {
5753 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005754 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005755 return QualType();
5756 }
5757
5758 // If exactly one conversion is possible, that conversion is applied to
5759 // the chosen operand and the converted operands are used in place of the
5760 // original operands for the remainder of this section.
5761 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005762 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005763 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005764 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005765 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005766 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005767 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005768 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005769 }
5770 }
5771
Richard Smithf2b084f2012-08-08 06:13:49 +00005772 // C++11 [expr.cond]p3
5773 // if both are glvalues of the same value category and the same type except
5774 // for cv-qualification, an attempt is made to convert each of those
5775 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005776 // FIXME:
5777 // Resolving a defect in P0012R1: we extend this to cover all cases where
5778 // one of the operands is reference-compatible with the other, in order
5779 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005780 ExprValueKind LVK = LHS.get()->getValueKind();
5781 ExprValueKind RVK = RHS.get()->getValueKind();
5782 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005783 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005784 // DerivedToBase was already handled by the class-specific case above.
5785 // FIXME: Should we allow ObjC conversions here?
5786 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5787 if (CompareReferenceRelationship(
5788 QuestionLoc, LTy, RTy, DerivedToBase,
5789 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005790 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5791 // [...] subject to the constraint that the reference must bind
5792 // directly [...]
5793 !RHS.get()->refersToBitField() &&
5794 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005795 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005796 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005797 } else if (CompareReferenceRelationship(
5798 QuestionLoc, RTy, LTy, DerivedToBase,
5799 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005800 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5801 !LHS.get()->refersToBitField() &&
5802 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005803 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5804 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005805 }
5806 }
5807
5808 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005809 // If the second and third operands are glvalues of the same value
5810 // category and have the same type, the result is of that type and
5811 // value category and it is a bit-field if the second or the third
5812 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005813 // We only extend this to bitfields, not to the crazy other kinds of
5814 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005815 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005816 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005817 LHS.get()->isOrdinaryOrBitFieldObject() &&
5818 RHS.get()->isOrdinaryOrBitFieldObject()) {
5819 VK = LHS.get()->getValueKind();
5820 if (LHS.get()->getObjectKind() == OK_BitField ||
5821 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005822 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005823
5824 // If we have function pointer types, unify them anyway to unify their
5825 // exception specifications, if any.
5826 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5827 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005828 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005829 /*ConvertArgs*/false);
5830 LTy = Context.getQualifiedType(LTy, Qs);
5831
5832 assert(!LTy.isNull() && "failed to find composite pointer type for "
5833 "canonically equivalent function ptr types");
5834 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5835 }
5836
John McCall7decc9e2010-11-18 06:31:45 +00005837 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005838 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005839
Richard Smithf2b084f2012-08-08 06:13:49 +00005840 // C++11 [expr.cond]p5
5841 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005842 // do not have the same type, and either has (cv) class type, ...
5843 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5844 // ... overload resolution is used to determine the conversions (if any)
5845 // to be applied to the operands. If the overload resolution fails, the
5846 // program is ill-formed.
5847 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5848 return QualType();
5849 }
5850
Richard Smithf2b084f2012-08-08 06:13:49 +00005851 // C++11 [expr.cond]p6
5852 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005853 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005854 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5855 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005856 if (LHS.isInvalid() || RHS.isInvalid())
5857 return QualType();
5858 LTy = LHS.get()->getType();
5859 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005860
5861 // After those conversions, one of the following shall hold:
5862 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005863 // is of that type. If the operands have class type, the result
5864 // is a prvalue temporary of the result type, which is
5865 // copy-initialized from either the second operand or the third
5866 // operand depending on the value of the first operand.
5867 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5868 if (LTy->isRecordType()) {
5869 // The operands have class type. Make a temporary copy.
5870 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005871
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005872 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5873 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005874 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005875 if (LHSCopy.isInvalid())
5876 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005877
5878 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5879 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005880 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005881 if (RHSCopy.isInvalid())
5882 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005883
John Wiegley01296292011-04-08 18:41:53 +00005884 LHS = LHSCopy;
5885 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005886 }
5887
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005888 // If we have function pointer types, unify them anyway to unify their
5889 // exception specifications, if any.
5890 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5891 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5892 assert(!LTy.isNull() && "failed to find composite pointer type for "
5893 "canonically equivalent function ptr types");
5894 }
5895
Sebastian Redl1a99f442009-04-16 17:51:27 +00005896 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005897 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005898
Douglas Gregor46188682010-05-18 22:42:18 +00005899 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005900 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005901 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5902 /*AllowBothBool*/true,
5903 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005904
Sebastian Redl1a99f442009-04-16 17:51:27 +00005905 // -- The second and third operands have arithmetic or enumeration type;
5906 // the usual arithmetic conversions are performed to bring them to a
5907 // common type, and the result is of that type.
5908 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005909 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005910 if (LHS.isInvalid() || RHS.isInvalid())
5911 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005912 if (ResTy.isNull()) {
5913 Diag(QuestionLoc,
5914 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5915 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5916 return QualType();
5917 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005918
5919 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5920 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5921
5922 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005923 }
5924
5925 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005926 // type and the other is a null pointer constant, or both are null
5927 // pointer constants, at least one of which is non-integral; pointer
5928 // conversions and qualification conversions are performed to bring them
5929 // to their composite pointer type. The result is of the composite
5930 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005931 // -- The second and third operands have pointer to member type, or one has
5932 // pointer to member type and the other is a null pointer constant;
5933 // pointer to member conversions and qualification conversions are
5934 // performed to bring them to a common type, whose cv-qualification
5935 // shall match the cv-qualification of either the second or the third
5936 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005937 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5938 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005939 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005940
Douglas Gregor697a3912010-04-01 22:47:07 +00005941 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005942 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5943 if (!Composite.isNull())
5944 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005945
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005946 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005947 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005948 return QualType();
5949
Sebastian Redl1a99f442009-04-16 17:51:27 +00005950 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005951 << LHS.get()->getType() << RHS.get()->getType()
5952 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005953 return QualType();
5954}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005955
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005956static FunctionProtoType::ExceptionSpecInfo
5957mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5958 FunctionProtoType::ExceptionSpecInfo ESI2,
5959 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5960 ExceptionSpecificationType EST1 = ESI1.Type;
5961 ExceptionSpecificationType EST2 = ESI2.Type;
5962
5963 // If either of them can throw anything, that is the result.
5964 if (EST1 == EST_None) return ESI1;
5965 if (EST2 == EST_None) return ESI2;
5966 if (EST1 == EST_MSAny) return ESI1;
5967 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005968 if (EST1 == EST_NoexceptFalse) return ESI1;
5969 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005970
5971 // If either of them is non-throwing, the result is the other.
5972 if (EST1 == EST_DynamicNone) return ESI2;
5973 if (EST2 == EST_DynamicNone) return ESI1;
5974 if (EST1 == EST_BasicNoexcept) return ESI2;
5975 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005976 if (EST1 == EST_NoexceptTrue) return ESI2;
5977 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005978
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005979 // If we're left with value-dependent computed noexcept expressions, we're
5980 // stuck. Before C++17, we can just drop the exception specification entirely,
5981 // since it's not actually part of the canonical type. And this should never
5982 // happen in C++17, because it would mean we were computing the composite
5983 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00005984 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005985 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005986 "computing composite pointer type of dependent types");
5987 return FunctionProtoType::ExceptionSpecInfo();
5988 }
5989
5990 // Switch over the possibilities so that people adding new values know to
5991 // update this function.
5992 switch (EST1) {
5993 case EST_None:
5994 case EST_DynamicNone:
5995 case EST_MSAny:
5996 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00005997 case EST_DependentNoexcept:
5998 case EST_NoexceptFalse:
5999 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006000 llvm_unreachable("handled above");
6001
6002 case EST_Dynamic: {
6003 // This is the fun case: both exception specifications are dynamic. Form
6004 // the union of the two lists.
6005 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6006 llvm::SmallPtrSet<QualType, 8> Found;
6007 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6008 for (QualType E : Exceptions)
6009 if (Found.insert(S.Context.getCanonicalType(E)).second)
6010 ExceptionTypeStorage.push_back(E);
6011
6012 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6013 Result.Exceptions = ExceptionTypeStorage;
6014 return Result;
6015 }
6016
6017 case EST_Unevaluated:
6018 case EST_Uninstantiated:
6019 case EST_Unparsed:
6020 llvm_unreachable("shouldn't see unresolved exception specifications here");
6021 }
6022
6023 llvm_unreachable("invalid ExceptionSpecificationType");
6024}
6025
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006026/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006027///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006028/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006029/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006030/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006031/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006032///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006033/// \param Loc The location of the operator requiring these two expressions to
6034/// be converted to the composite pointer type.
6035///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006036/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006037QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006038 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006039 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006040 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006041
6042 // C++1z [expr]p14:
6043 // The composite pointer type of two operands p1 and p2 having types T1
6044 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006045 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006046
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006047 // where at least one is a pointer or pointer to member type or
6048 // std::nullptr_t is:
6049 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6050 T1->isNullPtrType();
6051 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6052 T2->isNullPtrType();
6053 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006054 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006055
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006056 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6057 // This can't actually happen, following the standard, but we also use this
6058 // to implement the end of [expr.conv], which hits this case.
6059 //
6060 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6061 if (T1IsPointerLike &&
6062 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006063 if (ConvertArgs)
6064 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6065 ? CK_NullToMemberPointer
6066 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006067 return T1;
6068 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006069 if (T2IsPointerLike &&
6070 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006071 if (ConvertArgs)
6072 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6073 ? CK_NullToMemberPointer
6074 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006075 return T2;
6076 }
Mike Stump11289f42009-09-09 15:08:12 +00006077
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006078 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006079 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006080 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006081 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6082 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006083
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006084 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6085 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6086 // the union of cv1 and cv2;
6087 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6088 // "pointer to function", where the function types are otherwise the same,
6089 // "pointer to function";
6090 // FIXME: This rule is defective: it should also permit removing noexcept
6091 // from a pointer to member function. As a Clang extension, we also
6092 // permit removing 'noreturn', so we generalize this rule to;
6093 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6094 // "pointer to member function" and the pointee types can be unified
6095 // by a function pointer conversion, that conversion is applied
6096 // before checking the following rules.
6097 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6098 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6099 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6100 // respectively;
6101 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6102 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6103 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6104 // T1 or the cv-combined type of T1 and T2, respectively;
6105 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6106 // T2;
6107 //
6108 // If looked at in the right way, these bullets all do the same thing.
6109 // What we do here is, we build the two possible cv-combined types, and try
6110 // the conversions in both directions. If only one works, or if the two
6111 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006112 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006113 //
6114 // Note that this will fail to find a composite pointer type for "pointer
6115 // to void" and "pointer to function". We can't actually perform the final
6116 // conversion in this case, even though a composite pointer type formally
6117 // exists.
6118 SmallVector<unsigned, 4> QualifierUnion;
6119 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006120 QualType Composite1 = T1;
6121 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006122 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006123 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006124 const PointerType *Ptr1, *Ptr2;
6125 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6126 (Ptr2 = Composite2->getAs<PointerType>())) {
6127 Composite1 = Ptr1->getPointeeType();
6128 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006130 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006131 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006132 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006133 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006134
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006135 QualifierUnion.push_back(
6136 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006137 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006138 continue;
6139 }
Mike Stump11289f42009-09-09 15:08:12 +00006140
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006141 const MemberPointerType *MemPtr1, *MemPtr2;
6142 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6143 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6144 Composite1 = MemPtr1->getPointeeType();
6145 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006146
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006147 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006148 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006149 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006150 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006151
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006152 QualifierUnion.push_back(
6153 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6154 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6155 MemPtr2->getClass()));
6156 continue;
6157 }
Mike Stump11289f42009-09-09 15:08:12 +00006158
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006159 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006160
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006161 // Cannot unwrap any more types.
6162 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006163 }
Mike Stump11289f42009-09-09 15:08:12 +00006164
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006165 // Apply the function pointer conversion to unify the types. We've already
6166 // unwrapped down to the function types, and we want to merge rather than
6167 // just convert, so do this ourselves rather than calling
6168 // IsFunctionConversion.
6169 //
6170 // FIXME: In order to match the standard wording as closely as possible, we
6171 // currently only do this under a single level of pointers. Ideally, we would
6172 // allow this in general, and set NeedConstBefore to the relevant depth on
6173 // the side(s) where we changed anything.
6174 if (QualifierUnion.size() == 1) {
6175 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6176 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6177 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6178 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6179
6180 // The result is noreturn if both operands are.
6181 bool Noreturn =
6182 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6183 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6184 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6185
6186 // The result is nothrow if both operands are.
6187 SmallVector<QualType, 8> ExceptionTypeStorage;
6188 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6189 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6190 ExceptionTypeStorage);
6191
6192 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6193 FPT1->getParamTypes(), EPI1);
6194 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6195 FPT2->getParamTypes(), EPI2);
6196 }
6197 }
6198 }
6199
Richard Smith5e9746f2016-10-21 22:00:42 +00006200 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006201 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006202 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006203 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006204 for (unsigned I = 0; I != NeedConstBefore; ++I)
6205 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006206 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006208
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006209 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006210 auto MOC = MemberOfClass.rbegin();
6211 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6212 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6213 auto Classes = *MOC++;
6214 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006215 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006216 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006217 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006218 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006219 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006220 } else {
6221 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006222 Composite1 =
6223 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6224 Composite2 =
6225 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006226 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006227 }
6228
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006229 struct Conversion {
6230 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006231 Expr *&E1, *&E2;
6232 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006233 InitializedEntity Entity;
6234 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006235 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006236 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006237
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006238 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6239 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006240 : S(S), E1(E1), E2(E2), Composite(Composite),
6241 Entity(InitializedEntity::InitializeTemporary(Composite)),
6242 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6243 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6244 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006245
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006246 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006247 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6248 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006249 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006250 E1 = E1Result.getAs<Expr>();
6251
6252 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6253 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006254 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006255 E2 = E2Result.getAs<Expr>();
6256
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006257 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006258 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006259 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006260
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006261 // Try to convert to each composite pointer type.
6262 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006263 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6264 if (ConvertArgs && C1.perform())
6265 return QualType();
6266 return C1.Composite;
6267 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006268 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006269
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006270 if (C1.Viable == C2.Viable) {
6271 // Either Composite1 and Composite2 are viable and are different, or
6272 // neither is viable.
6273 // FIXME: How both be viable and different?
6274 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006275 }
6276
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006277 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006278 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6279 return QualType();
6280
6281 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006282}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006283
John McCalldadc5752010-08-24 06:29:42 +00006284ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006285 if (!E)
6286 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006287
John McCall31168b02011-06-15 23:02:42 +00006288 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6289
6290 // If the result is a glvalue, we shouldn't bind it.
6291 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006292 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006293
John McCall31168b02011-06-15 23:02:42 +00006294 // In ARC, calls that return a retainable type can return retained,
6295 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006296 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006297 E->getType()->isObjCRetainableType()) {
6298
6299 bool ReturnsRetained;
6300
6301 // For actual calls, we compute this by examining the type of the
6302 // called value.
6303 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6304 Expr *Callee = Call->getCallee()->IgnoreParens();
6305 QualType T = Callee->getType();
6306
6307 if (T == Context.BoundMemberTy) {
6308 // Handle pointer-to-members.
6309 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6310 T = BinOp->getRHS()->getType();
6311 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6312 T = Mem->getMemberDecl()->getType();
6313 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006314
John McCall31168b02011-06-15 23:02:42 +00006315 if (const PointerType *Ptr = T->getAs<PointerType>())
6316 T = Ptr->getPointeeType();
6317 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6318 T = Ptr->getPointeeType();
6319 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6320 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006321
John McCall31168b02011-06-15 23:02:42 +00006322 const FunctionType *FTy = T->getAs<FunctionType>();
6323 assert(FTy && "call to value not of function type?");
6324 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6325
6326 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6327 // type always produce a +1 object.
6328 } else if (isa<StmtExpr>(E)) {
6329 ReturnsRetained = true;
6330
Ted Kremeneke65b0862012-03-06 20:05:56 +00006331 // We hit this case with the lambda conversion-to-block optimization;
6332 // we don't want any extra casts here.
6333 } else if (isa<CastExpr>(E) &&
6334 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006335 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006336
John McCall31168b02011-06-15 23:02:42 +00006337 // For message sends and property references, we try to find an
6338 // actual method. FIXME: we should infer retention by selector in
6339 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006340 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006341 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006342 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6343 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006344 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6345 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006346 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006347 // Don't do reclaims if we're using the zero-element array
6348 // constant.
6349 if (ArrayLit->getNumElements() == 0 &&
6350 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6351 return E;
6352
Ted Kremeneke65b0862012-03-06 20:05:56 +00006353 D = ArrayLit->getArrayWithObjectsMethod();
6354 } else if (ObjCDictionaryLiteral *DictLit
6355 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006356 // Don't do reclaims if we're using the zero-element dictionary
6357 // constant.
6358 if (DictLit->getNumElements() == 0 &&
6359 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6360 return E;
6361
Ted Kremeneke65b0862012-03-06 20:05:56 +00006362 D = DictLit->getDictWithObjectsMethod();
6363 }
John McCall31168b02011-06-15 23:02:42 +00006364
6365 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006366
6367 // Don't do reclaims on performSelector calls; despite their
6368 // return type, the invoked method doesn't necessarily actually
6369 // return an object.
6370 if (!ReturnsRetained &&
6371 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006372 return E;
John McCall31168b02011-06-15 23:02:42 +00006373 }
6374
John McCall16de4d22011-11-14 19:53:16 +00006375 // Don't reclaim an object of Class type.
6376 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006377 return E;
John McCall16de4d22011-11-14 19:53:16 +00006378
Tim Shen4a05bb82016-06-21 20:29:17 +00006379 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006380
John McCall2d637d22011-09-10 06:18:15 +00006381 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6382 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006383 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6384 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006385 }
6386
David Blaikiebbafb8a2012-03-11 07:00:24 +00006387 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006388 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006389
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006390 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6391 // a fast path for the common case that the type is directly a RecordType.
6392 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006393 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006394 while (!RT) {
6395 switch (T->getTypeClass()) {
6396 case Type::Record:
6397 RT = cast<RecordType>(T);
6398 break;
6399 case Type::ConstantArray:
6400 case Type::IncompleteArray:
6401 case Type::VariableArray:
6402 case Type::DependentSizedArray:
6403 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6404 break;
6405 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006406 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006407 }
6408 }
Mike Stump11289f42009-09-09 15:08:12 +00006409
Richard Smithfd555f62012-02-22 02:04:18 +00006410 // That should be enough to guarantee that this type is complete, if we're
6411 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006412 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006413 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006414 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006415
6416 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006417 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006418
John McCall31168b02011-06-15 23:02:42 +00006419 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006420 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006421 CheckDestructorAccess(E->getExprLoc(), Destructor,
6422 PDiag(diag::err_access_dtor_temp)
6423 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006424 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6425 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006426
Richard Smithfd555f62012-02-22 02:04:18 +00006427 // If destructor is trivial, we can avoid the extra copy.
6428 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006429 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006430
John McCall28fc7092011-11-10 05:35:25 +00006431 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006432 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006433 }
Richard Smitheec915d62012-02-18 04:13:32 +00006434
6435 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006436 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6437
6438 if (IsDecltype)
6439 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6440
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006441 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006442}
6443
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444ExprResult
John McCall5d413782010-12-06 08:20:24 +00006445Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006446 if (SubExpr.isInvalid())
6447 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006449 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006450}
6451
John McCall28fc7092011-11-10 05:35:25 +00006452Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006453 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006454
Eli Friedman3bda6b12012-02-02 23:15:15 +00006455 CleanupVarDeclMarking();
6456
John McCall28fc7092011-11-10 05:35:25 +00006457 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6458 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006459 assert(Cleanup.exprNeedsCleanups() ||
6460 ExprCleanupObjects.size() == FirstCleanup);
6461 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006462 return SubExpr;
6463
Craig Topper5fc8fc22014-08-27 06:28:36 +00006464 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6465 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006466
Tim Shen4a05bb82016-06-21 20:29:17 +00006467 auto *E = ExprWithCleanups::Create(
6468 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006469 DiscardCleanupsInEvaluationContext();
6470
6471 return E;
6472}
6473
John McCall5d413782010-12-06 08:20:24 +00006474Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006475 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006476
Eli Friedman3bda6b12012-02-02 23:15:15 +00006477 CleanupVarDeclMarking();
6478
Tim Shen4a05bb82016-06-21 20:29:17 +00006479 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006480 return SubStmt;
6481
6482 // FIXME: In order to attach the temporaries, wrap the statement into
6483 // a StmtExpr; currently this is only used for asm statements.
6484 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6485 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006486 CompoundStmt *CompStmt = CompoundStmt::Create(
6487 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006488 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6489 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006490 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006491}
6492
Richard Smithfd555f62012-02-22 02:04:18 +00006493/// Process the expression contained within a decltype. For such expressions,
6494/// certain semantic checks on temporaries are delayed until this point, and
6495/// are omitted for the 'topmost' call in the decltype expression. If the
6496/// topmost call bound a temporary, strip that temporary off the expression.
6497ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006498 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006499
6500 // C++11 [expr.call]p11:
6501 // If a function call is a prvalue of object type,
6502 // -- if the function call is either
6503 // -- the operand of a decltype-specifier, or
6504 // -- the right operand of a comma operator that is the operand of a
6505 // decltype-specifier,
6506 // a temporary object is not introduced for the prvalue.
6507
6508 // Recursively rebuild ParenExprs and comma expressions to strip out the
6509 // outermost CXXBindTemporaryExpr, if any.
6510 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6511 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6512 if (SubExpr.isInvalid())
6513 return ExprError();
6514 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006515 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006516 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006517 }
6518 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6519 if (BO->getOpcode() == BO_Comma) {
6520 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6521 if (RHS.isInvalid())
6522 return ExprError();
6523 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006524 return E;
6525 return new (Context) BinaryOperator(
6526 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006527 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006528 }
6529 }
6530
6531 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006532 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6533 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006534 if (TopCall)
6535 E = TopCall;
6536 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006537 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006538
6539 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006540 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006541
Richard Smithf86b0ae2012-07-28 19:54:11 +00006542 // In MS mode, don't perform any extra checking of call return types within a
6543 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006544 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006545 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006546
Richard Smithfd555f62012-02-22 02:04:18 +00006547 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006548 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6549 I != N; ++I) {
6550 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006551 if (Call == TopCall)
6552 continue;
6553
David Majnemerced8bdf2015-02-25 17:36:15 +00006554 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006555 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006556 Call, Call->getDirectCallee()))
6557 return ExprError();
6558 }
6559
6560 // Now all relevant types are complete, check the destructors are accessible
6561 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006562 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6563 I != N; ++I) {
6564 CXXBindTemporaryExpr *Bind =
6565 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006566 if (Bind == TopBind)
6567 continue;
6568
6569 CXXTemporary *Temp = Bind->getTemporary();
6570
6571 CXXRecordDecl *RD =
6572 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6573 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6574 Temp->setDestructor(Destructor);
6575
Richard Smith7d847b12012-05-11 22:20:10 +00006576 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6577 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006578 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006579 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006580 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6581 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006582
6583 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006584 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006585 }
6586
6587 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006588 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006589}
6590
Richard Smith79c927b2013-11-06 19:31:51 +00006591/// Note a set of 'operator->' functions that were used for a member access.
6592static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006593 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006594 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6595 // FIXME: Make this configurable?
6596 unsigned Limit = 9;
6597 if (OperatorArrows.size() > Limit) {
6598 // Produce Limit-1 normal notes and one 'skipping' note.
6599 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6600 SkipCount = OperatorArrows.size() - (Limit - 1);
6601 }
6602
6603 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6604 if (I == SkipStart) {
6605 S.Diag(OperatorArrows[I]->getLocation(),
6606 diag::note_operator_arrows_suppressed)
6607 << SkipCount;
6608 I += SkipCount;
6609 } else {
6610 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6611 << OperatorArrows[I]->getCallResultType();
6612 ++I;
6613 }
6614 }
6615}
6616
Nico Weber964d3322015-02-16 22:35:45 +00006617ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6618 SourceLocation OpLoc,
6619 tok::TokenKind OpKind,
6620 ParsedType &ObjectType,
6621 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006622 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006623 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006624 if (Result.isInvalid()) return ExprError();
6625 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006626
John McCall526ab472011-10-25 17:37:35 +00006627 Result = CheckPlaceholderExpr(Base);
6628 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006629 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006630
John McCallb268a282010-08-23 23:25:46 +00006631 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006632 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006633 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006634 // If we have a pointer to a dependent type and are using the -> operator,
6635 // the object type is the type that the pointer points to. We might still
6636 // have enough information about that type to do something useful.
6637 if (OpKind == tok::arrow)
6638 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6639 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006640
John McCallba7bf592010-08-24 05:47:05 +00006641 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006642 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006643 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006644 }
Mike Stump11289f42009-09-09 15:08:12 +00006645
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006646 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006647 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006648 // returned, with the original second operand.
6649 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006650 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006651 bool NoArrowOperatorFound = false;
6652 bool FirstIteration = true;
6653 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006654 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006655 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006656 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006657 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006659 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006660 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6661 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006662 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006663 noteOperatorArrows(*this, OperatorArrows);
6664 Diag(OpLoc, diag::note_operator_arrow_depth)
6665 << getLangOpts().ArrowDepth;
6666 return ExprError();
6667 }
6668
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006669 Result = BuildOverloadedArrowExpr(
6670 S, Base, OpLoc,
6671 // When in a template specialization and on the first loop iteration,
6672 // potentially give the default diagnostic (with the fixit in a
6673 // separate note) instead of having the error reported back to here
6674 // and giving a diagnostic with a fixit attached to the error itself.
6675 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006676 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006677 : &NoArrowOperatorFound);
6678 if (Result.isInvalid()) {
6679 if (NoArrowOperatorFound) {
6680 if (FirstIteration) {
6681 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006682 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006683 << FixItHint::CreateReplacement(OpLoc, ".");
6684 OpKind = tok::period;
6685 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006686 }
6687 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6688 << BaseType << Base->getSourceRange();
6689 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006690 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006691 Diag(CD->getLocStart(),
6692 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006693 }
6694 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006695 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006696 }
John McCallb268a282010-08-23 23:25:46 +00006697 Base = Result.get();
6698 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006699 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006700 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006701 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006702 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006703 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6704 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006705 return ExprError();
6706 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006707 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006708 }
Mike Stump11289f42009-09-09 15:08:12 +00006709
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006710 if (OpKind == tok::arrow &&
6711 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006712 BaseType = BaseType->getPointeeType();
6713 }
Mike Stump11289f42009-09-09 15:08:12 +00006714
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006715 // Objective-C properties allow "." access on Objective-C pointer types,
6716 // so adjust the base type to the object type itself.
6717 if (BaseType->isObjCObjectPointerType())
6718 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006719
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006720 // C++ [basic.lookup.classref]p2:
6721 // [...] If the type of the object expression is of pointer to scalar
6722 // type, the unqualified-id is looked up in the context of the complete
6723 // postfix-expression.
6724 //
6725 // This also indicates that we could be parsing a pseudo-destructor-name.
6726 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006727 // expressions or normal member (ivar or property) access expressions, and
6728 // it's legal for the type to be incomplete if this is a pseudo-destructor
6729 // call. We'll do more incomplete-type checks later in the lookup process,
6730 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006731 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006732 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006733 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006734 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006735 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006736 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006737 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006738 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006739 }
Mike Stump11289f42009-09-09 15:08:12 +00006740
Douglas Gregor3024f072012-04-16 07:05:22 +00006741 // The object type must be complete (or dependent), or
6742 // C++11 [expr.prim.general]p3:
6743 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006744 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006745 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006746 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006747 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006748 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006749 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006750
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006751 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006752 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006753 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006754 // type C (or of pointer to a class type C), the unqualified-id is looked
6755 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006756 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006757 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006758}
6759
Simon Pilgrim75c26882016-09-30 14:25:09 +00006760static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006761 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006762 if (Base->hasPlaceholderType()) {
6763 ExprResult result = S.CheckPlaceholderExpr(Base);
6764 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006765 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006766 }
6767 ObjectType = Base->getType();
6768
David Blaikie1d578782011-12-16 16:03:09 +00006769 // C++ [expr.pseudo]p2:
6770 // The left-hand side of the dot operator shall be of scalar type. The
6771 // left-hand side of the arrow operator shall be of pointer to scalar type.
6772 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006773 // Note that this is rather different from the normal handling for the
6774 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006775 if (OpKind == tok::arrow) {
6776 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6777 ObjectType = Ptr->getPointeeType();
6778 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006779 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006780 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6781 << ObjectType << true
6782 << FixItHint::CreateReplacement(OpLoc, ".");
6783 if (S.isSFINAEContext())
6784 return true;
6785
6786 OpKind = tok::period;
6787 }
6788 }
6789
6790 return false;
6791}
6792
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006793/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006794/// pointer objects.
6795static bool
6796canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6797 QualType DestructedType) {
6798 // If this is a record type, check if its destructor is callable.
6799 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6800 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6801 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6802 return false;
6803 }
6804
6805 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6806 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6807 DestructedType->isVectorType();
6808}
6809
John McCalldadc5752010-08-24 06:29:42 +00006810ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006811 SourceLocation OpLoc,
6812 tok::TokenKind OpKind,
6813 const CXXScopeSpec &SS,
6814 TypeSourceInfo *ScopeTypeInfo,
6815 SourceLocation CCLoc,
6816 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006817 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006818 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819
Eli Friedman0ce4de42012-01-25 04:35:06 +00006820 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006821 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6822 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823
Douglas Gregorc5c57342012-09-10 14:57:06 +00006824 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6825 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006826 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006827 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006828 else {
Nico Weber58829272012-01-23 05:50:57 +00006829 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6830 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006831 return ExprError();
6832 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006833 }
6834
6835 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006837 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006838 if (DestructedTypeInfo) {
6839 QualType DestructedType = DestructedTypeInfo->getType();
6840 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006841 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006842 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6843 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006844 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6845 // Foo *foo;
6846 // foo.~Foo();
6847 if (OpKind == tok::period && ObjectType->isPointerType() &&
6848 Context.hasSameUnqualifiedType(DestructedType,
6849 ObjectType->getPointeeType())) {
6850 auto Diagnostic =
6851 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6852 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006853
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006854 // Issue a fixit only when the destructor is valid.
6855 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6856 *this, DestructedType))
6857 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6858
6859 // Recover by setting the object type to the destructed type and the
6860 // operator to '->'.
6861 ObjectType = DestructedType;
6862 OpKind = tok::arrow;
6863 } else {
6864 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6865 << ObjectType << DestructedType << Base->getSourceRange()
6866 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6867
6868 // Recover by setting the destructed type to the object type.
6869 DestructedType = ObjectType;
6870 DestructedTypeInfo =
6871 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6872 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6873 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006874 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006875 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006876
John McCall31168b02011-06-15 23:02:42 +00006877 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6878 // Okay: just pretend that the user provided the correctly-qualified
6879 // type.
6880 } else {
6881 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6882 << ObjectType << DestructedType << Base->getSourceRange()
6883 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6884 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006885
John McCall31168b02011-06-15 23:02:42 +00006886 // Recover by setting the destructed type to the object type.
6887 DestructedType = ObjectType;
6888 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6889 DestructedTypeStart);
6890 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6891 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006892 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006895 // C++ [expr.pseudo]p2:
6896 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6897 // form
6898 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006899 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006900 //
6901 // shall designate the same scalar type.
6902 if (ScopeTypeInfo) {
6903 QualType ScopeType = ScopeTypeInfo->getType();
6904 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006905 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006906
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006907 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006908 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006909 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006910 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006912 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006913 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006914 }
6915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916
John McCallb268a282010-08-23 23:25:46 +00006917 Expr *Result
6918 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6919 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006920 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006921 ScopeTypeInfo,
6922 CCLoc,
6923 TildeLoc,
6924 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
David Majnemerced8bdf2015-02-25 17:36:15 +00006926 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006927}
6928
John McCalldadc5752010-08-24 06:29:42 +00006929ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006930 SourceLocation OpLoc,
6931 tok::TokenKind OpKind,
6932 CXXScopeSpec &SS,
6933 UnqualifiedId &FirstTypeName,
6934 SourceLocation CCLoc,
6935 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006936 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006937 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6938 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006939 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006940 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6941 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006942 "Invalid second type name in pseudo-destructor");
6943
Eli Friedman0ce4de42012-01-25 04:35:06 +00006944 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006945 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6946 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006947
6948 // Compute the object type that we should use for name lookup purposes. Only
6949 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006950 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006951 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006952 if (ObjectType->isRecordType())
6953 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006954 else if (ObjectType->isDependentType())
6955 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
6958 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006959 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006960 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006961 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006962 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006963 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006965 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006966 S, &SS, true, false, ObjectTypePtrForLookup,
6967 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006969 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6970 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006971 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006972 // couldn't find anything useful in scope. Just store the identifier and
6973 // it's location, and we'll perform (qualified) name lookup again at
6974 // template instantiation time.
6975 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6976 SecondTypeName.StartLocation);
6977 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006978 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006979 diag::err_pseudo_dtor_destructor_non_type)
6980 << SecondTypeName.Identifier << ObjectType;
6981 if (isSFINAEContext())
6982 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006984 // Recover by assuming we had the right type all along.
6985 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006986 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006987 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006988 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006989 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006990 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006991 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006992 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006993 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006994 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006995 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006996 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006997 TemplateId->TemplateNameLoc,
6998 TemplateId->LAngleLoc,
6999 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007000 TemplateId->RAngleLoc,
7001 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007002 if (T.isInvalid() || !T.get()) {
7003 // Recover by assuming we had the right type all along.
7004 DestructedType = ObjectType;
7005 } else
7006 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007008
7009 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007010 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007011 if (!DestructedType.isNull()) {
7012 if (!DestructedTypeInfo)
7013 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007014 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007015 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007018 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007019 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007020 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007021 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007022 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007023 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007025 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007026 S, &SS, true, false, ObjectTypePtrForLookup,
7027 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007028 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007030 diag::err_pseudo_dtor_destructor_non_type)
7031 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007033 if (isSFINAEContext())
7034 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007036 // Just drop this type. It's unnecessary anyway.
7037 ScopeType = QualType();
7038 } else
7039 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007040 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007041 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007042 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007043 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007044 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007045 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007046 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007047 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007048 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007049 TemplateId->TemplateNameLoc,
7050 TemplateId->LAngleLoc,
7051 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007052 TemplateId->RAngleLoc,
7053 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007054 if (T.isInvalid() || !T.get()) {
7055 // Recover by dropping this type.
7056 ScopeType = QualType();
7057 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007058 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007059 }
7060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061
Douglas Gregor90ad9222010-02-24 23:02:30 +00007062 if (!ScopeType.isNull() && !ScopeTypeInfo)
7063 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7064 FirstTypeName.StartLocation);
7065
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007066
John McCallb268a282010-08-23 23:25:46 +00007067 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007068 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007069 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007070}
7071
David Blaikie1d578782011-12-16 16:03:09 +00007072ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7073 SourceLocation OpLoc,
7074 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007075 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007076 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007077 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007078 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7079 return ExprError();
7080
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007081 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7082 false);
David Blaikie1d578782011-12-16 16:03:09 +00007083
7084 TypeLocBuilder TLB;
7085 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7086 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7087 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7088 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7089
7090 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007091 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007092 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007093}
7094
John Wiegley01296292011-04-08 18:41:53 +00007095ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007096 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007097 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00007098 if (Method->getParent()->isLambda() &&
7099 Method->getConversionType()->isBlockPointerType()) {
7100 // This is a lambda coversion to block pointer; check if the argument
7101 // is a LambdaExpr.
7102 Expr *SubE = E;
7103 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7104 if (CE && CE->getCastKind() == CK_NoOp)
7105 SubE = CE->getSubExpr();
7106 SubE = SubE->IgnoreParens();
7107 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7108 SubE = BE->getSubExpr();
7109 if (isa<LambdaExpr>(SubE)) {
7110 // For the conversion to block pointer on a lambda expression, we
7111 // construct a special BlockLiteral instead; this doesn't really make
7112 // a difference in ARC, but outside of ARC the resulting block literal
7113 // follows the normal lifetime rules for block literals instead of being
7114 // autoreleased.
7115 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007116 PushExpressionEvaluationContext(
7117 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00007118 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
7119 E->getExprLoc(),
7120 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00007121 PopExpressionEvaluationContext();
7122
Eli Friedman98b01ed2012-03-01 04:01:32 +00007123 if (Exp.isInvalid())
7124 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
7125 return Exp;
7126 }
7127 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007128
Craig Topperc3ec1492014-05-26 06:22:03 +00007129 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00007130 FoundDecl, Method);
7131 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00007132 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00007133
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007134 MemberExpr *ME = new (Context) MemberExpr(
7135 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7136 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007137 if (HadMultipleCandidates)
7138 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007139 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007140
Alp Toker314cc812014-01-25 16:55:45 +00007141 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007142 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7143 ResultType = ResultType.getNonLValueExprType(Context);
7144
Douglas Gregor27381f32009-11-23 12:27:39 +00007145 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00007146 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00007147 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00007148
7149 if (CheckFunctionCall(Method, CE,
7150 Method->getType()->castAs<FunctionProtoType>()))
7151 return ExprError();
7152
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007153 return CE;
7154}
7155
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007156ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7157 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007158 // If the operand is an unresolved lookup expression, the expression is ill-
7159 // formed per [over.over]p1, because overloaded function names cannot be used
7160 // without arguments except in explicit contexts.
7161 ExprResult R = CheckPlaceholderExpr(Operand);
7162 if (R.isInvalid())
7163 return R;
7164
7165 // The operand may have been modified when checking the placeholder type.
7166 Operand = R.get();
7167
Richard Smith51ec0cf2017-02-21 01:17:38 +00007168 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007169 // The expression operand for noexcept is in an unevaluated expression
7170 // context, so side effects could result in unintended consequences.
7171 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7172 }
7173
Richard Smithf623c962012-04-17 00:58:00 +00007174 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007175 return new (Context)
7176 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007177}
7178
7179ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7180 Expr *Operand, SourceLocation RParen) {
7181 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007182}
7183
Eli Friedmanf798f652012-05-24 22:04:19 +00007184static bool IsSpecialDiscardedValue(Expr *E) {
7185 // In C++11, discarded-value expressions of a certain form are special,
7186 // according to [expr]p10:
7187 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7188 // expression is an lvalue of volatile-qualified type and it has
7189 // one of the following forms:
7190 E = E->IgnoreParens();
7191
Eli Friedmanc49c2262012-05-24 22:36:31 +00007192 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007193 if (isa<DeclRefExpr>(E))
7194 return true;
7195
Eli Friedmanc49c2262012-05-24 22:36:31 +00007196 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007197 if (isa<ArraySubscriptExpr>(E))
7198 return true;
7199
Eli Friedmanc49c2262012-05-24 22:36:31 +00007200 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007201 if (isa<MemberExpr>(E))
7202 return true;
7203
Eli Friedmanc49c2262012-05-24 22:36:31 +00007204 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7206 if (UO->getOpcode() == UO_Deref)
7207 return true;
7208
7209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007210 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007211 if (BO->isPtrMemOp())
7212 return true;
7213
Eli Friedmanc49c2262012-05-24 22:36:31 +00007214 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007215 if (BO->getOpcode() == BO_Comma)
7216 return IsSpecialDiscardedValue(BO->getRHS());
7217 }
7218
Eli Friedmanc49c2262012-05-24 22:36:31 +00007219 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007220 // operands are one of the above, or
7221 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7222 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7223 IsSpecialDiscardedValue(CO->getFalseExpr());
7224 // The related edge case of "*x ?: *x".
7225 if (BinaryConditionalOperator *BCO =
7226 dyn_cast<BinaryConditionalOperator>(E)) {
7227 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7228 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7229 IsSpecialDiscardedValue(BCO->getFalseExpr());
7230 }
7231
7232 // Objective-C++ extensions to the rule.
7233 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7234 return true;
7235
7236 return false;
7237}
7238
John McCall34376a62010-12-04 03:47:34 +00007239/// Perform the conversions required for an expression used in a
7240/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007241ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007242 if (E->hasPlaceholderType()) {
7243 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007244 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007245 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007246 }
7247
John McCallfee942d2010-12-02 02:07:15 +00007248 // C99 6.3.2.1:
7249 // [Except in specific positions,] an lvalue that does not have
7250 // array type is converted to the value stored in the
7251 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007252 if (E->isRValue()) {
7253 // In C, function designators (i.e. expressions of function type)
7254 // are r-values, but we still want to do function-to-pointer decay
7255 // on them. This is both technically correct and convenient for
7256 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007257 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007258 return DefaultFunctionArrayConversion(E);
7259
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007260 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007261 }
John McCallfee942d2010-12-02 02:07:15 +00007262
Eli Friedmanf798f652012-05-24 22:04:19 +00007263 if (getLangOpts().CPlusPlus) {
7264 // The C++11 standard defines the notion of a discarded-value expression;
7265 // normally, we don't need to do anything to handle it, but if it is a
7266 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7267 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007268 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007269 E->getType().isVolatileQualified() &&
7270 IsSpecialDiscardedValue(E)) {
7271 ExprResult Res = DefaultLvalueConversion(E);
7272 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007273 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007274 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007275 }
Richard Smith122f88d2016-12-06 23:52:28 +00007276
7277 // C++1z:
7278 // If the expression is a prvalue after this optional conversion, the
7279 // temporary materialization conversion is applied.
7280 //
7281 // We skip this step: IR generation is able to synthesize the storage for
7282 // itself in the aggregate case, and adding the extra node to the AST is
7283 // just clutter.
7284 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7285 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007286 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007287 }
John McCall34376a62010-12-04 03:47:34 +00007288
7289 // GCC seems to also exclude expressions of incomplete enum type.
7290 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7291 if (!T->getDecl()->isComplete()) {
7292 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007293 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007294 return E;
John McCall34376a62010-12-04 03:47:34 +00007295 }
7296 }
7297
John Wiegley01296292011-04-08 18:41:53 +00007298 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7299 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007300 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007301 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007302
John McCallca61b652010-12-04 12:29:11 +00007303 if (!E->getType()->isVoidType())
7304 RequireCompleteType(E->getExprLoc(), E->getType(),
7305 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007306 return E;
John McCall34376a62010-12-04 03:47:34 +00007307}
7308
Faisal Valia17d19f2013-11-07 05:17:06 +00007309// If we can unambiguously determine whether Var can never be used
7310// in a constant expression, return true.
7311// - if the variable and its initializer are non-dependent, then
7312// we can unambiguously check if the variable is a constant expression.
7313// - if the initializer is not value dependent - we can determine whether
7314// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007315// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007316// never be a constant expression.
7317// - FXIME: if the initializer is dependent, we can still do some analysis and
7318// identify certain cases unambiguously as non-const by using a Visitor:
7319// - such as those that involve odr-use of a ParmVarDecl, involve a new
7320// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007321static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007322 ASTContext &Context) {
7323 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007324 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007325
7326 // If there is no initializer - this can not be a constant expression.
7327 if (!Var->getAnyInitializer(DefVD)) return true;
7328 assert(DefVD);
7329 if (DefVD->isWeak()) return false;
7330 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007331
Faisal Valia17d19f2013-11-07 05:17:06 +00007332 Expr *Init = cast<Expr>(Eval->Value);
7333
7334 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007335 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7336 // of value-dependent expressions, and use it here to determine whether the
7337 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007338 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007339 }
7340
Simon Pilgrim75c26882016-09-30 14:25:09 +00007341 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007342}
7343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007344/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007345/// that must be captured by any of its enclosing lambdas that are ready to
7346/// capture. If there is a lambda that can capture a nested
7347/// potential-capture, go ahead and do so. Also, check to see if any
7348/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007349/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007350
Faisal Valiab3d6462013-12-07 20:22:44 +00007351static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7352 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7353
Simon Pilgrim75c26882016-09-30 14:25:09 +00007354 assert(!S.isUnevaluatedContext());
7355 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007356#ifndef NDEBUG
7357 DeclContext *DC = S.CurContext;
7358 while (DC && isa<CapturedDecl>(DC))
7359 DC = DC->getParent();
7360 assert(
7361 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007362 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007363#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007364
7365 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7366
Faisal Valiab3d6462013-12-07 20:22:44 +00007367 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007368 // lambda (within a generic outer lambda), must be captured by an
7369 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007370 const unsigned NumPotentialCaptures =
7371 CurrentLSI->getNumPotentialVariableCaptures();
7372 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007373 Expr *VarExpr = nullptr;
7374 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007375 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007376 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007377 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007378 // need to check enclosing lambda's for speculative captures.
7379 // For e.g.:
7380 // Even though 'x' is not odr-used, it should be captured.
7381 // int test() {
7382 // const int x = 10;
7383 // auto L = [=](auto a) {
7384 // (void) +x + a;
7385 // };
7386 // }
7387 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007388 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007389 continue;
7390
7391 // If we have a capture-capable lambda for the variable, go ahead and
7392 // capture the variable in that lambda (and all its enclosing lambdas).
7393 if (const Optional<unsigned> Index =
7394 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007395 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007396 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7397 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7398 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007399 }
7400 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007401 VariableCanNeverBeAConstantExpression(Var, S.Context);
7402 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7403 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007404 // can not be used in a constant expression - which means
7405 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007406 // capture violation early, if the variable is un-captureable.
7407 // This is purely for diagnosing errors early. Otherwise, this
7408 // error would get diagnosed when the lambda becomes capture ready.
7409 QualType CaptureType, DeclRefType;
7410 SourceLocation ExprLoc = VarExpr->getExprLoc();
7411 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007412 /*EllipsisLoc*/ SourceLocation(),
7413 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007414 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007415 // We will never be able to capture this variable, and we need
7416 // to be able to in any and all instantiations, so diagnose it.
7417 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007418 /*EllipsisLoc*/ SourceLocation(),
7419 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007420 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007421 }
7422 }
7423 }
7424
Faisal Valiab3d6462013-12-07 20:22:44 +00007425 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007426 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007427 // If we have a capture-capable lambda for 'this', go ahead and capture
7428 // 'this' in that lambda (and all its enclosing lambdas).
7429 if (const Optional<unsigned> Index =
7430 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007431 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007432 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7433 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7434 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7435 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007436 }
7437 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007438
7439 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007440 CurrentLSI->clearPotentialCaptures();
7441}
7442
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007443static ExprResult attemptRecovery(Sema &SemaRef,
7444 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007445 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007446 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7447 Consumer.getLookupResult().getLookupKind());
7448 const CXXScopeSpec *SS = Consumer.getSS();
7449 CXXScopeSpec NewSS;
7450
7451 // Use an approprate CXXScopeSpec for building the expr.
7452 if (auto *NNS = TC.getCorrectionSpecifier())
7453 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7454 else if (SS && !TC.WillReplaceSpecifier())
7455 NewSS = *SS;
7456
Richard Smithde6d6c42015-12-29 19:43:10 +00007457 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007458 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007459 R.addDecl(ND);
7460 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007461 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007462 CXXRecordDecl *Record = nullptr;
7463 if (auto *NNS = TC.getCorrectionSpecifier())
7464 Record = NNS->getAsType()->getAsCXXRecordDecl();
7465 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007466 Record =
7467 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7468 if (Record)
7469 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007470
7471 // Detect and handle the case where the decl might be an implicit
7472 // member.
7473 bool MightBeImplicitMember;
7474 if (!Consumer.isAddressOfOperand())
7475 MightBeImplicitMember = true;
7476 else if (!NewSS.isEmpty())
7477 MightBeImplicitMember = false;
7478 else if (R.isOverloadedResult())
7479 MightBeImplicitMember = false;
7480 else if (R.isUnresolvableResult())
7481 MightBeImplicitMember = true;
7482 else
7483 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7484 isa<IndirectFieldDecl>(ND) ||
7485 isa<MSPropertyDecl>(ND);
7486
7487 if (MightBeImplicitMember)
7488 return SemaRef.BuildPossibleImplicitMemberExpr(
7489 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007490 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007491 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7492 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7493 Ivar->getIdentifier());
7494 }
7495 }
7496
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007497 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7498 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007499}
7500
Kaelyn Takata6c759512014-10-27 18:07:37 +00007501namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007502class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7503 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7504
7505public:
7506 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7507 : TypoExprs(TypoExprs) {}
7508 bool VisitTypoExpr(TypoExpr *TE) {
7509 TypoExprs.insert(TE);
7510 return true;
7511 }
7512};
7513
Kaelyn Takata6c759512014-10-27 18:07:37 +00007514class TransformTypos : public TreeTransform<TransformTypos> {
7515 typedef TreeTransform<TransformTypos> BaseTransform;
7516
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007517 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7518 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007519 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007520 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007521 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007522 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007524 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007525 /// If the TypoExprs were successfully corrected, then the diagnostics should
7526 /// suggest the corrections. Otherwise the diagnostics will not suggest
7527 /// anything (having been passed an empty TypoCorrection).
7528 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007529 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007530 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007531 if (State.DiagHandler) {
7532 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7533 ExprResult Replacement = TransformCache[TE];
7534
7535 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7536 // TypoCorrection, replacing the existing decls. This ensures the right
7537 // NamedDecl is used in diagnostics e.g. in the case where overload
7538 // resolution was used to select one from several possible decls that
7539 // had been stored in the TypoCorrection.
7540 if (auto *ND = getDeclFromExpr(
7541 Replacement.isInvalid() ? nullptr : Replacement.get()))
7542 TC.setCorrectionDecl(ND);
7543
7544 State.DiagHandler(TC);
7545 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007546 SemaRef.clearDelayedTypo(TE);
7547 }
7548 }
7549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007550 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007551 /// given combination of the other TypoExprs, retry those corrections against
7552 /// the next combination of substitutions for the other TypoExprs by advancing
7553 /// to the next potential correction of the second TypoExpr. For the second
7554 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7555 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7556 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7557 /// TransformCache). Returns true if there is still any untried combinations
7558 /// of corrections.
7559 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7560 for (auto TE : TypoExprs) {
7561 auto &State = SemaRef.getTypoExprState(TE);
7562 TransformCache.erase(TE);
7563 if (!State.Consumer->finished())
7564 return true;
7565 State.Consumer->resetCorrectionStream();
7566 }
7567 return false;
7568 }
7569
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007570 NamedDecl *getDeclFromExpr(Expr *E) {
7571 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7572 E = OverloadResolution[OE];
7573
7574 if (!E)
7575 return nullptr;
7576 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007577 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007578 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007579 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007580 // FIXME: Add any other expr types that could be be seen by the delayed typo
7581 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007582 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007583 return nullptr;
7584 }
7585
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007586 ExprResult TryTransform(Expr *E) {
7587 Sema::SFINAETrap Trap(SemaRef);
7588 ExprResult Res = TransformExpr(E);
7589 if (Trap.hasErrorOccurred() || Res.isInvalid())
7590 return ExprError();
7591
7592 return ExprFilter(Res.get());
7593 }
7594
Kaelyn Takata6c759512014-10-27 18:07:37 +00007595public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007596 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7597 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007598
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007599 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7600 MultiExprArg Args,
7601 SourceLocation RParenLoc,
7602 Expr *ExecConfig = nullptr) {
7603 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7604 RParenLoc, ExecConfig);
7605 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007606 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007607 Expr *ResultCall = Result.get();
7608 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7609 ResultCall = BE->getSubExpr();
7610 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7611 OverloadResolution[OE] = CE->getCallee();
7612 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007613 }
7614 return Result;
7615 }
7616
Kaelyn Takata6c759512014-10-27 18:07:37 +00007617 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7618
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007619 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7620
Kaelyn Takata6c759512014-10-27 18:07:37 +00007621 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007622 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007623 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007624 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007625
Kaelyn Takata6c759512014-10-27 18:07:37 +00007626 // Exit if either the transform was valid or if there were no TypoExprs
7627 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007628 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007629 !CheckAndAdvanceTypoExprCorrectionStreams())
7630 break;
7631 }
7632
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007633 // Ensure none of the TypoExprs have multiple typo correction candidates
7634 // with the same edit length that pass all the checks and filters.
7635 // TODO: Properly handle various permutations of possible corrections when
7636 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007637 // Also, disable typo correction while attempting the transform when
7638 // handling potentially ambiguous typo corrections as any new TypoExprs will
7639 // have been introduced by the application of one of the correction
7640 // candidates and add little to no value if corrected.
7641 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007642 while (!AmbiguousTypoExprs.empty()) {
7643 auto TE = AmbiguousTypoExprs.back();
7644 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007645 auto &State = SemaRef.getTypoExprState(TE);
7646 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007647 TransformCache.erase(TE);
7648 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007649 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007650 TransformCache.erase(TE);
7651 Res = ExprError();
7652 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007653 }
7654 AmbiguousTypoExprs.remove(TE);
7655 State.Consumer->restoreSavedPosition();
7656 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007657 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007658 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007659
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007660 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007661 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007662 FindTypoExprs(TypoExprs).TraverseStmt(E);
7663
Kaelyn Takata6c759512014-10-27 18:07:37 +00007664 EmitAllDiagnostics();
7665
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007666 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007667 }
7668
7669 ExprResult TransformTypoExpr(TypoExpr *E) {
7670 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7671 // cached transformation result if there is one and the TypoExpr isn't the
7672 // first one that was encountered.
7673 auto &CacheEntry = TransformCache[E];
7674 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7675 return CacheEntry;
7676 }
7677
7678 auto &State = SemaRef.getTypoExprState(E);
7679 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7680
7681 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7682 // typo correction and return it.
7683 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007684 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007685 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007686 // FIXME: If we would typo-correct to an invalid declaration, it's
7687 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007688 ExprResult NE = State.RecoveryHandler ?
7689 State.RecoveryHandler(SemaRef, E, TC) :
7690 attemptRecovery(SemaRef, *State.Consumer, TC);
7691 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007692 // Check whether there may be a second viable correction with the same
7693 // edit distance; if so, remember this TypoExpr may have an ambiguous
7694 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007695 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007696 if ((Next = State.Consumer->peekNextCorrection()) &&
7697 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7698 AmbiguousTypoExprs.insert(E);
7699 } else {
7700 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007701 }
7702 assert(!NE.isUnset() &&
7703 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007704 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007705 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007706 }
7707 return CacheEntry = ExprError();
7708 }
7709};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007710}
Faisal Valia17d19f2013-11-07 05:17:06 +00007711
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007712ExprResult
7713Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7714 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007715 // If the current evaluation context indicates there are uncorrected typos
7716 // and the current expression isn't guaranteed to not have typos, try to
7717 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007718 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007719 (E->isTypeDependent() || E->isValueDependent() ||
7720 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007721 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7722 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7723 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007724 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007725 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007726 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007727 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007728 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007729 ExprEvalContexts.back().NumTypos -= TyposResolved;
7730 return Result;
7731 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007732 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007733 }
7734 return E;
7735}
7736
Richard Smith945f8d32013-01-14 22:39:08 +00007737ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007738 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007739 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007740 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007741 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007742
7743 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007744 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007745
7746 // If we are an init-expression in a lambdas init-capture, we should not
7747 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007748 // containing full-expression is done).
7749 // template<class ... Ts> void test(Ts ... t) {
7750 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7751 // return a;
7752 // }() ...);
7753 // }
7754 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7755 // when we parse the lambda introducer, and teach capturing (but not
7756 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7757 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7758 // lambda where we've entered the introducer but not the body, or represent a
7759 // lambda where we've entered the body, depending on where the
7760 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007761 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007762 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007763 return ExprError();
7764
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007765 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007766 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007767 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007768 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007769 if (FullExpr.isInvalid())
7770 return ExprError();
7771 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007772
Richard Smith945f8d32013-01-14 22:39:08 +00007773 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007774 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007775 if (FullExpr.isInvalid())
7776 return ExprError();
7777
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007778 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007779 if (FullExpr.isInvalid())
7780 return ExprError();
7781 }
John Wiegley01296292011-04-08 18:41:53 +00007782
Kaelyn Takata49d84322014-11-11 23:26:56 +00007783 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7784 if (FullExpr.isInvalid())
7785 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007786
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007787 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007788
Simon Pilgrim75c26882016-09-30 14:25:09 +00007789 // At the end of this full expression (which could be a deeply nested
7790 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007791 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007792 // Consider the following code:
7793 // void f(int, int);
7794 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007795 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007796 // const int x = 10, y = 20;
7797 // auto L = [=](auto a) {
7798 // auto M = [=](auto b) {
7799 // f(x, b); <-- requires x to be captured by L and M
7800 // f(y, a); <-- requires y to be captured by L, but not all Ms
7801 // };
7802 // };
7803 // }
7804
Simon Pilgrim75c26882016-09-30 14:25:09 +00007805 // FIXME: Also consider what happens for something like this that involves
7806 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007807 // void f() {
7808 // const int n = 0;
7809 // auto L = [&](auto a) {
7810 // +n + ({ 0; a; });
7811 // };
7812 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007813 //
7814 // Here, we see +n, and then the full-expression 0; ends, so we don't
7815 // capture n (and instead remove it from our list of potential captures),
7816 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007817 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007818
Alexey Bataev31939e32016-11-11 12:36:20 +00007819 LambdaScopeInfo *const CurrentLSI =
7820 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007821 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007822 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007823 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007824 // By ensuring we are in the context of a lambda's call operator
7825 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007826 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007827 // PR, a proper fix would entail :
7828 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007829 // - Add to Sema an integer holding the smallest (outermost) scope
7830 // index that we are *lexically* within, and save/restore/set to
7831 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007832 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007833 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007834 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007835 DeclContext *DC = CurContext;
7836 while (DC && isa<CapturedDecl>(DC))
7837 DC = DC->getParent();
7838 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007839 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007840 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007841 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7842 *this);
John McCall5d413782010-12-06 08:20:24 +00007843 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007844}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007845
7846StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7847 if (!FullStmt) return StmtError();
7848
John McCall5d413782010-12-06 08:20:24 +00007849 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007850}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007851
Simon Pilgrim75c26882016-09-30 14:25:09 +00007852Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007853Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7854 CXXScopeSpec &SS,
7855 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007856 DeclarationName TargetName = TargetNameInfo.getName();
7857 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007858 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007859
Douglas Gregor43edb322011-10-24 22:31:10 +00007860 // If the name itself is dependent, then the result is dependent.
7861 if (TargetName.isDependentName())
7862 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007863
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007864 // Do the redeclaration lookup in the current scope.
7865 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7866 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007867 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007868 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007869
Douglas Gregor43edb322011-10-24 22:31:10 +00007870 switch (R.getResultKind()) {
7871 case LookupResult::Found:
7872 case LookupResult::FoundOverloaded:
7873 case LookupResult::FoundUnresolvedValue:
7874 case LookupResult::Ambiguous:
7875 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007876
Douglas Gregor43edb322011-10-24 22:31:10 +00007877 case LookupResult::NotFound:
7878 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007879
Douglas Gregor43edb322011-10-24 22:31:10 +00007880 case LookupResult::NotFoundInCurrentInstantiation:
7881 return IER_Dependent;
7882 }
David Blaikie8a40f702012-01-17 06:56:22 +00007883
7884 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007885}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007886
Simon Pilgrim75c26882016-09-30 14:25:09 +00007887Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007888Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7889 bool IsIfExists, CXXScopeSpec &SS,
7890 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007891 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007892
Richard Smith151c4562016-12-20 21:35:28 +00007893 // Check for an unexpanded parameter pack.
7894 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7895 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7896 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007897 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007898
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007899 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7900}