blob: 2bf1c7393954d2e5ca53f6e2f34160b84c594c7d [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
11/// \brief Implements semantic analysis for C++ expressions.
12///
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"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000295
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
David Blaikieecd8a942011-12-08 16:13:53 +0000326ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieefdccaa2016-01-15 23:43:34 +0000328 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
David Blaikieecd8a942011-12-08 16:13:53 +0000330 && "only get destructor types from declspecs");
331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332 QualType SearchType = GetTypeFromParser(ObjectType);
333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334 return ParsedType::make(T);
335 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000336
David Blaikieecd8a942011-12-08 16:13:53 +0000337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000339 return nullptr;
David Blaikieecd8a942011-12-08 16:13:53 +0000340}
341
Richard Smithd091dc12013-12-05 00:58:33 +0000342bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343 const UnqualifiedId &Name) {
344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345
346 if (!SS.isValid())
347 return false;
348
349 switch (SS.getScopeRep()->getKind()) {
350 case NestedNameSpecifier::Identifier:
351 case NestedNameSpecifier::TypeSpec:
352 case NestedNameSpecifier::TypeSpecWithTemplate:
353 // Per C++11 [over.literal]p2, literal operators can only be declared at
354 // namespace scope. Therefore, this unqualified-id cannot name anything.
355 // Reject it early, because we have no AST representation for this in the
356 // case where the scope is dependent.
357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358 << SS.getScopeRep();
359 return true;
360
361 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000362 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000363 case NestedNameSpecifier::Namespace:
364 case NestedNameSpecifier::NamespaceAlias:
365 return false;
366 }
367
368 llvm_unreachable("unknown nested name specifier kind");
369}
370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000372ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000373 SourceLocation TypeidLoc,
374 TypeSourceInfo *Operand,
375 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000378 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000381 Qualifiers Quals;
382 QualType T
383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000385 if (T->getAs<RecordType>() &&
386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
David Majnemer6f3150a2014-11-21 21:09:12 +0000389 if (T->isVariablyModifiedType())
390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000394}
395
396/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000397ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000398 SourceLocation TypeidLoc,
399 Expr *E,
400 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000401 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000402 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000406 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000407 }
408
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 QualType T = E->getType();
410 if (const RecordType *RecordT = T->getAs<RecordType>()) {
411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412 // C++ [expr.typeid]p3:
413 // [...] If the type of the expression is a class type, the class
414 // shall be completely-defined.
415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor9da64192010-04-26 22:37:10 +0000418 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000419 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 // polymorphic class type [...] [the] expression is an unevaluated
421 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000422 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000423 // The subexpression is potentially evaluated; switch the context
424 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000425 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000426 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000427 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000428
429 // We require a vtable to query the type at run time.
430 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000431 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000432 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // C++ [expr.typeid]p4:
436 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437 // cv-qualified type, the result of the typeid expression refers to a
438 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000439 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000440 Qualifiers Quals;
441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442 if (!Context.hasSameType(T, UnqualT)) {
443 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 }
446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
David Majnemer6f3150a2014-11-21 21:09:12 +0000448 if (E->getType()->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450 << E->getType());
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000451 else if (ActiveTemplateInstantiations.empty() &&
452 E->HasSideEffects(Context, WasEvaluated)) {
453 // The expression operand for typeid is in an unevaluated expression
454 // context, so side effects could result in unintended consequences.
455 Diag(E->getExprLoc(), WasEvaluated
456 ? diag::warn_side_effects_typeid
457 : diag::warn_side_effects_unevaluated_context);
458 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000459
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000462}
463
464/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000465ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000466Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000469 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000471
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000472 if (!CXXTypeInfoDecl) {
473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475 LookupQualifiedName(R, getStdNamespace());
476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000477 // Microsoft's typeinfo doesn't have type_info in std but in the global
478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000480 LookupQualifiedName(R, Context.getTranslationUnitDecl());
481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl)
484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Nico Weber1b7f39d2012-05-20 01:27:21 +0000487 if (!getLangOpts().RTTI) {
488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489 }
490
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregor9da64192010-04-26 22:37:10 +0000493 if (isType) {
494 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 if (T.isNull())
499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9da64192010-04-26 22:37:10 +0000501 if (!TInfo)
502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000509}
510
David Majnemer1dbc7a72016-03-27 04:46:07 +0000511/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
512/// a single GUID.
513static void
514getUuidAttrOfType(Sema &SemaRef, QualType QT,
515 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
516 // Optionally remove one level of pointer, reference or array indirection.
517 const Type *Ty = QT.getTypePtr();
518 if (QT->isPointerType() || QT->isReferenceType())
519 Ty = QT->getPointeeType().getTypePtr();
520 else if (QT->isArrayType())
521 Ty = Ty->getBaseElementTypeUnsafe();
522
Reid Klecknere516eab2016-12-13 18:58:09 +0000523 const auto *TD = Ty->getAsTagDecl();
524 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000525 return;
526
Reid Klecknere516eab2016-12-13 18:58:09 +0000527 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000528 UuidAttrs.insert(Uuid);
529 return;
530 }
531
532 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000533 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000534 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
535 for (const TemplateArgument &TA : TAL.asArray()) {
536 const UuidAttr *UuidForTA = nullptr;
537 if (TA.getKind() == TemplateArgument::Type)
538 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
539 else if (TA.getKind() == TemplateArgument::Declaration)
540 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
541
542 if (UuidForTA)
543 UuidAttrs.insert(UuidForTA);
544 }
545 }
546}
547
Francois Pichet9f4f2072010-09-08 12:20:18 +0000548/// \brief Build a Microsoft __uuidof expression with a type operand.
549ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
550 SourceLocation TypeidLoc,
551 TypeSourceInfo *Operand,
552 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000553 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000554 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000555 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
556 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
557 if (UuidAttrs.empty())
558 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
559 if (UuidAttrs.size() > 1)
560 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000561 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
David Majnemer2041b462016-03-28 03:19:50 +0000564 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000565 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000566}
567
568/// \brief Build a Microsoft __uuidof expression with an expression operand.
569ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
570 SourceLocation TypeidLoc,
571 Expr *E,
572 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000573 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000574 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000575 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
576 UuidStr = "00000000-0000-0000-0000-000000000000";
577 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000578 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
579 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
580 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582 if (UuidAttrs.size() > 1)
583 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000584 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000585 }
Francois Pichetb7577652010-12-27 01:32:00 +0000586 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000587
David Majnemer2041b462016-03-28 03:19:50 +0000588 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000590}
591
592/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
593ExprResult
594Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
595 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000597 if (!MSVCGuidDecl) {
598 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
599 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
600 LookupQualifiedName(R, Context.getTranslationUnitDecl());
601 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
602 if (!MSVCGuidDecl)
603 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 }
605
Francois Pichet9f4f2072010-09-08 12:20:18 +0000606 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Francois Pichet9f4f2072010-09-08 12:20:18 +0000608 if (isType) {
609 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000610 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000611 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
612 &TInfo);
613 if (T.isNull())
614 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Francois Pichet9f4f2072010-09-08 12:20:18 +0000616 if (!TInfo)
617 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
618
619 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
620 }
621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624}
625
Steve Naroff66356bd2007-09-16 14:56:35 +0000626/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000627ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000628Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000629 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000630 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000631 return new (Context)
632 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000633}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000634
Sebastian Redl576fd422009-05-10 18:38:11 +0000635/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000636ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000637Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000638 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000639}
640
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000641/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000642ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000643Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
644 bool IsThrownVarInScope = false;
645 if (Ex) {
646 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000647 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000648 // copy/move construction of a class object [...]
649 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000650 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000651 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000652 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000653 // innermost enclosing try-block (if there is one), the copy/move
654 // operation from the operand to the exception object (15.1) can be
655 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000656 // exception object
657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
659 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
660 for( ; S; S = S->getParent()) {
661 if (S->isDeclScope(Var)) {
662 IsThrownVarInScope = true;
663 break;
664 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000665
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 if (S->getFlags() &
667 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
668 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
669 Scope::TryScope))
670 break;
671 }
672 }
673 }
674 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000675
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000676 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
677}
678
Simon Pilgrim75c26882016-09-30 14:25:09 +0000679ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000680 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000681 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000682 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000683 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000684 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000685
Justin Lebar2a8db342016-09-28 22:45:54 +0000686 // Exceptions aren't allowed in CUDA device code.
687 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000688 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
689 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000690
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000691 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
692 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
693
John Wiegley01296292011-04-08 18:41:53 +0000694 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000695 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
696 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000697 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000698
699 // Initialize the exception result. This implicitly weeds out
700 // abstract types or types with inaccessible copy constructors.
701
702 // C++0x [class.copymove]p31:
703 // When certain criteria are met, an implementation is allowed to omit the
704 // copy/move construction of a class object [...]
705 //
706 // - in a throw-expression, when the operand is the name of a
707 // non-volatile automatic object (other than a function or
708 // catch-clause
709 // parameter) whose scope does not extend beyond the end of the
710 // innermost enclosing try-block (if there is one), the copy/move
711 // operation from the operand to the exception object (15.1) can be
712 // omitted by constructing the automatic object directly into the
713 // exception object
714 const VarDecl *NRVOVariable = nullptr;
715 if (IsThrownVarInScope)
716 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
717
718 InitializedEntity Entity = InitializedEntity::InitializeException(
719 OpLoc, ExceptionObjectTy,
720 /*NRVO=*/NRVOVariable != nullptr);
721 ExprResult Res = PerformMoveOrCopyInitialization(
722 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
723 if (Res.isInvalid())
724 return ExprError();
725 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000726 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000727
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000728 return new (Context)
729 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000730}
731
David Majnemere7a818f2015-03-06 18:53:55 +0000732static void
733collectPublicBases(CXXRecordDecl *RD,
734 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
735 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
736 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
737 bool ParentIsPublic) {
738 for (const CXXBaseSpecifier &BS : RD->bases()) {
739 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
740 bool NewSubobject;
741 // Virtual bases constitute the same subobject. Non-virtual bases are
742 // always distinct subobjects.
743 if (BS.isVirtual())
744 NewSubobject = VBases.insert(BaseDecl).second;
745 else
746 NewSubobject = true;
747
748 if (NewSubobject)
749 ++SubobjectsSeen[BaseDecl];
750
751 // Only add subobjects which have public access throughout the entire chain.
752 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
753 if (PublicPath)
754 PublicSubobjectsSeen.insert(BaseDecl);
755
756 // Recurse on to each base subobject.
757 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
758 PublicPath);
759 }
760}
761
762static void getUnambiguousPublicSubobjects(
763 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
764 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
765 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
766 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
767 SubobjectsSeen[RD] = 1;
768 PublicSubobjectsSeen.insert(RD);
769 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
770 /*ParentIsPublic=*/true);
771
772 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
773 // Skip ambiguous objects.
774 if (SubobjectsSeen[PublicSubobject] > 1)
775 continue;
776
777 Objects.push_back(PublicSubobject);
778 }
779}
780
Sebastian Redl4de47b42009-04-27 20:27:31 +0000781/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000782bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
783 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000784 // If the type of the exception would be an incomplete type or a pointer
785 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000786 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000787 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000788 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000789 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000790 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000791 }
792 if (!isPointer || !Ty->isVoidType()) {
793 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000794 isPointer ? diag::err_throw_incomplete_ptr
795 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000796 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000798
David Majnemerd09a51c2015-03-03 01:50:05 +0000799 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000800 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000801 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802 }
803
Eli Friedman91a3d272010-06-03 20:39:03 +0000804 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000805 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
806 if (!RD)
807 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000808
Douglas Gregor88d292c2010-05-13 16:44:06 +0000809 // If we are throwing a polymorphic class type or pointer thereof,
810 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000811 MarkVTableUsed(ThrowLoc, RD);
812
Eli Friedman36ebbec2010-10-12 20:32:36 +0000813 // If a pointer is thrown, the referenced object will not be destroyed.
814 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000815 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000816
Richard Smitheec915d62012-02-18 04:13:32 +0000817 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000818 if (!RD->hasIrrelevantDestructor()) {
819 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
820 MarkFunctionReferenced(E->getExprLoc(), Destructor);
821 CheckDestructorAccess(E->getExprLoc(), Destructor,
822 PDiag(diag::err_access_dtor_exception) << Ty);
823 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000824 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000825 }
826 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000827
David Majnemerdfa6d202015-03-11 18:36:39 +0000828 // The MSVC ABI creates a list of all types which can catch the exception
829 // object. This list also references the appropriate copy constructor to call
830 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000831 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000832 // We are only interested in the public, unambiguous bases contained within
833 // the exception object. Bases which are ambiguous or otherwise
834 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000835 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
836 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000837
David Majnemere7a818f2015-03-06 18:53:55 +0000838 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000839 // Attempt to lookup the copy constructor. Various pieces of machinery
840 // will spring into action, like template instantiation, which means this
841 // cannot be a simple walk of the class's decls. Instead, we must perform
842 // lookup and overload resolution.
843 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
844 if (!CD)
845 continue;
846
847 // Mark the constructor referenced as it is used by this throw expression.
848 MarkFunctionReferenced(E->getExprLoc(), CD);
849
850 // Skip this copy constructor if it is trivial, we don't need to record it
851 // in the catchable type data.
852 if (CD->isTrivial())
853 continue;
854
855 // The copy constructor is non-trivial, create a mapping from this class
856 // type to this constructor.
857 // N.B. The selection of copy constructor is not sensitive to this
858 // particular throw-site. Lookup will be performed at the catch-site to
859 // ensure that the copy constructor is, in fact, accessible (via
860 // friendship or any other means).
861 Context.addCopyConstructorForExceptionObject(Subobject, CD);
862
863 // We don't keep the instantiated default argument expressions around so
864 // we must rebuild them here.
865 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000866 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
867 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000868 }
869 }
870 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000871
David Majnemerba3e5ec2015-03-13 18:26:17 +0000872 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000873}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000874
Faisal Vali67b04462016-06-11 16:41:54 +0000875static QualType adjustCVQualifiersForCXXThisWithinLambda(
876 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
877 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
878
879 QualType ClassType = ThisTy->getPointeeType();
880 LambdaScopeInfo *CurLSI = nullptr;
881 DeclContext *CurDC = CurSemaContext;
882
883 // Iterate through the stack of lambdas starting from the innermost lambda to
884 // the outermost lambda, checking if '*this' is ever captured by copy - since
885 // that could change the cv-qualifiers of the '*this' object.
886 // The object referred to by '*this' starts out with the cv-qualifiers of its
887 // member function. We then start with the innermost lambda and iterate
888 // outward checking to see if any lambda performs a by-copy capture of '*this'
889 // - and if so, any nested lambda must respect the 'constness' of that
890 // capturing lamdbda's call operator.
891 //
892
893 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
894 // since ScopeInfos are pushed on during parsing and treetransforming. But
895 // since a generic lambda's call operator can be instantiated anywhere (even
896 // end of the TU) we need to be able to examine its enclosing lambdas and so
897 // we use the DeclContext to get a hold of the closure-class and query it for
898 // capture information. The reason we don't just resort to always using the
899 // DeclContext chain is that it is only mature for lambda expressions
900 // enclosing generic lambda's call operators that are being instantiated.
901
902 for (int I = FunctionScopes.size();
903 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
904 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
905 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000906
907 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000908 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000909
Faisal Vali67b04462016-06-11 16:41:54 +0000910 auto C = CurLSI->getCXXThisCapture();
911
912 if (C.isCopyCapture()) {
913 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
914 if (CurLSI->CallOperator->isConst())
915 ClassType.addConst();
916 return ASTCtx.getPointerType(ClassType);
917 }
918 }
919 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
920 // happen during instantiation of generic lambdas)
921 if (isLambdaCallOperator(CurDC)) {
922 assert(CurLSI);
923 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
924 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000925
Faisal Vali67b04462016-06-11 16:41:54 +0000926 auto IsThisCaptured =
927 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
928 IsConst = false;
929 IsByCopy = false;
930 for (auto &&C : Closure->captures()) {
931 if (C.capturesThis()) {
932 if (C.getCaptureKind() == LCK_StarThis)
933 IsByCopy = true;
934 if (Closure->getLambdaCallOperator()->isConst())
935 IsConst = true;
936 return true;
937 }
938 }
939 return false;
940 };
941
942 bool IsByCopyCapture = false;
943 bool IsConstCapture = false;
944 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
945 while (Closure &&
946 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
947 if (IsByCopyCapture) {
948 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
949 if (IsConstCapture)
950 ClassType.addConst();
951 return ASTCtx.getPointerType(ClassType);
952 }
953 Closure = isLambdaCallOperator(Closure->getParent())
954 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
955 : nullptr;
956 }
957 }
958 return ASTCtx.getPointerType(ClassType);
959}
960
Eli Friedman73a04092012-01-07 04:59:52 +0000961QualType Sema::getCurrentThisType() {
962 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000963 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000964
Richard Smith938f40b2011-06-11 17:19:42 +0000965 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
966 if (method && method->isInstance())
967 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000968 }
Faisal Validc6b5962016-03-21 09:25:37 +0000969
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000970 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
971 !ActiveTemplateInstantiations.empty()) {
Faisal Validc6b5962016-03-21 09:25:37 +0000972
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000973 assert(isa<CXXRecordDecl>(DC) &&
974 "Trying to get 'this' type from static method?");
975
976 // This is a lambda call operator that is being instantiated as a default
977 // initializer. DC must point to the enclosing class type, so we can recover
978 // the 'this' type from it.
979
980 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
981 // There are no cv-qualifiers for 'this' within default initializers,
982 // per [expr.prim.general]p4.
983 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +0000984 }
Faisal Vali67b04462016-06-11 16:41:54 +0000985
986 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
987 // might need to be adjusted if the lambda or any of its enclosing lambda's
988 // captures '*this' by copy.
989 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
990 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
991 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000992 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000993}
994
Simon Pilgrim75c26882016-09-30 14:25:09 +0000995Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +0000996 Decl *ContextDecl,
997 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +0000998 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +0000999 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1000{
1001 if (!Enabled || !ContextDecl)
1002 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001003
1004 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001005 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1006 Record = Template->getTemplatedDecl();
1007 else
1008 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001009
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001010 // We care only for CVR qualifiers here, so cut everything else.
1011 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001012 S.CXXThisTypeOverride
1013 = S.Context.getPointerType(
1014 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001015
Douglas Gregor3024f072012-04-16 07:05:22 +00001016 this->Enabled = true;
1017}
1018
1019
1020Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1021 if (Enabled) {
1022 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1023 }
1024}
1025
Faisal Validc6b5962016-03-21 09:25:37 +00001026static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1027 QualType ThisTy, SourceLocation Loc,
1028 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001029
Faisal Vali67b04462016-06-11 16:41:54 +00001030 QualType AdjustedThisTy = ThisTy;
1031 // The type of the corresponding data member (not a 'this' pointer if 'by
1032 // copy').
1033 QualType CaptureThisFieldTy = ThisTy;
1034 if (ByCopy) {
1035 // If we are capturing the object referred to by '*this' by copy, ignore any
1036 // cv qualifiers inherited from the type of the member function for the type
1037 // of the closure-type's corresponding data member and any use of 'this'.
1038 CaptureThisFieldTy = ThisTy->getPointeeType();
1039 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1040 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1041 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001042
Faisal Vali67b04462016-06-11 16:41:54 +00001043 FieldDecl *Field = FieldDecl::Create(
1044 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1045 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1046 ICIS_NoInit);
1047
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001048 Field->setImplicit(true);
1049 Field->setAccess(AS_private);
1050 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001051 Expr *This =
1052 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001053 if (ByCopy) {
1054 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1055 UO_Deref,
1056 This).get();
1057 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001058 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001059 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1060 InitializationSequence Init(S, Entity, InitKind, StarThis);
1061 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1062 if (ER.isInvalid()) return nullptr;
1063 return ER.get();
1064 }
1065 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001066}
1067
Simon Pilgrim75c26882016-09-30 14:25:09 +00001068bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001069 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1070 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001071 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001072 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001073 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001074
Faisal Validc6b5962016-03-21 09:25:37 +00001075 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001076
Faisal Valia17d19f2013-11-07 05:17:06 +00001077 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001078 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001079
Simon Pilgrim75c26882016-09-30 14:25:09 +00001080 // Check that we can capture the *enclosing object* (referred to by '*this')
1081 // by the capturing-entity/closure (lambda/block/etc) at
1082 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1083
1084 // Note: The *enclosing object* can only be captured by-value by a
1085 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001086 // [*this] { ... }.
1087 // Every other capture of the *enclosing object* results in its by-reference
1088 // capture.
1089
1090 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1091 // stack), we can capture the *enclosing object* only if:
1092 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1093 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001094 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001095 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001096 // -- or, there is some enclosing closure 'E' that has already captured the
1097 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001098 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001099 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001100 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001101
1102
Faisal Validc6b5962016-03-21 09:25:37 +00001103 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001104 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001105 if (CapturingScopeInfo *CSI =
1106 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1107 if (CSI->CXXThisCaptureIndex != 0) {
1108 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001109 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001110 break;
1111 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001112 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1113 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1114 // This context can't implicitly capture 'this'; fail out.
1115 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001116 Diag(Loc, diag::err_this_capture)
1117 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001118 return true;
1119 }
Eli Friedman20139d32012-01-11 02:36:31 +00001120 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001121 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001122 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001123 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001124 (Explicit && idx == MaxFunctionScopesIndex)) {
1125 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1126 // iteration through can be an explicit capture, all enclosing closures,
1127 // if any, must perform implicit captures.
1128
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001129 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001130 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001131 continue;
1132 }
Eli Friedman20139d32012-01-11 02:36:31 +00001133 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001134 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001135 Diag(Loc, diag::err_this_capture)
1136 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001137 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001138 }
Eli Friedman73a04092012-01-07 04:59:52 +00001139 break;
1140 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001141 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001142
1143 // If we got here, then the closure at MaxFunctionScopesIndex on the
1144 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1145 // (including implicit by-reference captures in any enclosing closures).
1146
1147 // In the loop below, respect the ByCopy flag only for the closure requesting
1148 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001149 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001150 // implicitly capturing the *enclosing object* by reference (see loop
1151 // above)).
1152 assert((!ByCopy ||
1153 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1154 "Only a lambda can capture the enclosing object (referred to by "
1155 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001156 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1157 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001158 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001159 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001160 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001161 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001162 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001163
Faisal Validc6b5962016-03-21 09:25:37 +00001164 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1165 // For lambda expressions, build a field and an initializing expression,
1166 // and capture the *enclosing object* by copy only if this is the first
1167 // iteration.
1168 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1169 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001170
Faisal Validc6b5962016-03-21 09:25:37 +00001171 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001172 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001173 ThisExpr =
1174 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1175 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001176
Faisal Validc6b5962016-03-21 09:25:37 +00001177 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001178 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001179 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001180 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001181}
1182
Richard Smith938f40b2011-06-11 17:19:42 +00001183ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001184 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1185 /// is a non-lvalue expression whose value is the address of the object for
1186 /// which the function is called.
1187
Douglas Gregor09deffa2011-10-18 16:47:30 +00001188 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001189 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001190
Eli Friedman73a04092012-01-07 04:59:52 +00001191 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001192 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001193}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001194
Douglas Gregor3024f072012-04-16 07:05:22 +00001195bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1196 // If we're outside the body of a member function, then we'll have a specified
1197 // type for 'this'.
1198 if (CXXThisTypeOverride.isNull())
1199 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001200
Douglas Gregor3024f072012-04-16 07:05:22 +00001201 // Determine whether we're looking into a class that's currently being
1202 // defined.
1203 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1204 return Class && Class->isBeingDefined();
1205}
1206
John McCalldadc5752010-08-24 06:29:42 +00001207ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001208Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001209 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001210 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001211 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001212 if (!TypeRep)
1213 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214
John McCall97513962010-01-15 18:39:57 +00001215 TypeSourceInfo *TInfo;
1216 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1217 if (!TInfo)
1218 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001219
Serge Pavlov38526372016-11-12 15:38:55 +00001220 // Handle errors like: int({0})
1221 if (exprs.size() == 1 && !canInitializeWithParenthesizedList(Ty) &&
1222 LParenLoc.isValid() && RParenLoc.isValid())
1223 if (auto IList = dyn_cast<InitListExpr>(exprs[0])) {
1224 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1225 << Ty << IList->getSourceRange()
1226 << FixItHint::CreateRemoval(LParenLoc)
1227 << FixItHint::CreateRemoval(RParenLoc);
1228 LParenLoc = RParenLoc = SourceLocation();
1229 }
1230
Richard Smithb8c414c2016-06-30 20:24:30 +00001231 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1232 // Avoid creating a non-type-dependent expression that contains typos.
1233 // Non-type-dependent expressions are liable to be discarded without
1234 // checking for embedded typos.
1235 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1236 !Result.get()->isTypeDependent())
1237 Result = CorrectDelayedTyposInExpr(Result.get());
1238 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001239}
1240
1241/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1242/// Can be interpreted either as function-style casting ("int(x)")
1243/// or class type construction ("ClassType(x,y,z)")
1244/// or creation of a value-initialized type ("int()").
1245ExprResult
1246Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1247 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001248 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001249 SourceLocation RParenLoc) {
1250 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001251 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001252
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001253 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001254 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1255 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001256 }
1257
Sebastian Redld74dd492012-02-12 18:41:05 +00001258 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001259 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001260 && "List initialization must have initializer list as expression.");
1261 SourceRange FullRange = SourceRange(TyBeginLoc,
1262 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1263
Douglas Gregordd04d332009-01-16 18:33:17 +00001264 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001265 // If the expression list is a single expression, the type conversion
1266 // expression is equivalent (in definedness, and if defined in meaning) to the
1267 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001268 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001269 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001270 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001271 }
1272
David Majnemer7eddcff2015-09-14 07:05:00 +00001273 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1274 // simple-type-specifier or typename-specifier for a non-array complete
1275 // object type or the (possibly cv-qualified) void type, creates a prvalue
1276 // of the specified type, whose value is that produced by value-initializing
1277 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001278 QualType ElemTy = Ty;
1279 if (Ty->isArrayType()) {
1280 if (!ListInitialization)
1281 return ExprError(Diag(TyBeginLoc,
1282 diag::err_value_init_for_array_type) << FullRange);
1283 ElemTy = Context.getBaseElementType(Ty);
1284 }
1285
David Majnemer7eddcff2015-09-14 07:05:00 +00001286 if (!ListInitialization && Ty->isFunctionType())
1287 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1288 << FullRange);
1289
Eli Friedman576cbd02012-02-29 00:00:28 +00001290 if (!Ty->isVoidType() &&
1291 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001292 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001293 return ExprError();
1294
Douglas Gregor8ec51732010-09-08 21:40:08 +00001295 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001296 InitializationKind Kind =
1297 Exprs.size() ? ListInitialization
1298 ? InitializationKind::CreateDirectList(TyBeginLoc)
1299 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1300 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1301 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1302 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001303
Richard Smith90061902013-09-23 02:20:00 +00001304 if (Result.isInvalid() || !ListInitialization)
1305 return Result;
1306
1307 Expr *Inner = Result.get();
1308 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1309 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001310 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1311 // If we created a CXXTemporaryObjectExpr, that node also represents the
1312 // functional cast. Otherwise, create an explicit cast to represent
1313 // the syntactic form of a functional-style cast that was used here.
1314 //
1315 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1316 // would give a more consistent AST representation than using a
1317 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1318 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001319 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001320 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001321 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001322 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001323 }
1324
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001325 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001326}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001327
Richard Smithb2f0f052016-10-10 18:54:32 +00001328/// \brief Determine whether the given function is a non-placement
1329/// deallocation function.
1330static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1331 if (FD->isInvalidDecl())
1332 return false;
1333
1334 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1335 return Method->isUsualDeallocationFunction();
1336
1337 if (FD->getOverloadedOperator() != OO_Delete &&
1338 FD->getOverloadedOperator() != OO_Array_Delete)
1339 return false;
1340
1341 unsigned UsualParams = 1;
1342
1343 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1344 S.Context.hasSameUnqualifiedType(
1345 FD->getParamDecl(UsualParams)->getType(),
1346 S.Context.getSizeType()))
1347 ++UsualParams;
1348
1349 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1350 S.Context.hasSameUnqualifiedType(
1351 FD->getParamDecl(UsualParams)->getType(),
1352 S.Context.getTypeDeclType(S.getStdAlignValT())))
1353 ++UsualParams;
1354
1355 return UsualParams == FD->getNumParams();
1356}
1357
1358namespace {
1359 struct UsualDeallocFnInfo {
1360 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001361 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001362 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001363 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001364 // A function template declaration is never a usual deallocation function.
1365 if (!FD)
1366 return;
1367 if (FD->getNumParams() == 3)
1368 HasAlignValT = HasSizeT = true;
1369 else if (FD->getNumParams() == 2) {
1370 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1371 HasAlignValT = !HasSizeT;
1372 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001373
1374 // In CUDA, determine how much we'd like / dislike to call this.
1375 if (S.getLangOpts().CUDA)
1376 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1377 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001378 }
1379
1380 operator bool() const { return FD; }
1381
Richard Smithf75dcbe2016-10-11 00:21:10 +00001382 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1383 bool WantAlign) const {
1384 // C++17 [expr.delete]p10:
1385 // If the type has new-extended alignment, a function with a parameter
1386 // of type std::align_val_t is preferred; otherwise a function without
1387 // such a parameter is preferred
1388 if (HasAlignValT != Other.HasAlignValT)
1389 return HasAlignValT == WantAlign;
1390
1391 if (HasSizeT != Other.HasSizeT)
1392 return HasSizeT == WantSize;
1393
1394 // Use CUDA call preference as a tiebreaker.
1395 return CUDAPref > Other.CUDAPref;
1396 }
1397
Richard Smithb2f0f052016-10-10 18:54:32 +00001398 DeclAccessPair Found;
1399 FunctionDecl *FD;
1400 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001401 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001402 };
1403}
1404
1405/// Determine whether a type has new-extended alignment. This may be called when
1406/// the type is incomplete (for a delete-expression with an incomplete pointee
1407/// type), in which case it will conservatively return false if the alignment is
1408/// not known.
1409static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1410 return S.getLangOpts().AlignedAllocation &&
1411 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1412 S.getASTContext().getTargetInfo().getNewAlign();
1413}
1414
1415/// Select the correct "usual" deallocation function to use from a selection of
1416/// deallocation functions (either global or class-scope).
1417static UsualDeallocFnInfo resolveDeallocationOverload(
1418 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1419 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1420 UsualDeallocFnInfo Best;
1421
Richard Smithb2f0f052016-10-10 18:54:32 +00001422 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001423 UsualDeallocFnInfo Info(S, I.getPair());
1424 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1425 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001426 continue;
1427
1428 if (!Best) {
1429 Best = Info;
1430 if (BestFns)
1431 BestFns->push_back(Info);
1432 continue;
1433 }
1434
Richard Smithf75dcbe2016-10-11 00:21:10 +00001435 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001436 continue;
1437
1438 // If more than one preferred function is found, all non-preferred
1439 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001440 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001441 BestFns->clear();
1442
1443 Best = Info;
1444 if (BestFns)
1445 BestFns->push_back(Info);
1446 }
1447
1448 return Best;
1449}
1450
1451/// Determine whether a given type is a class for which 'delete[]' would call
1452/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1453/// we need to store the array size (even if the type is
1454/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001455static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1456 QualType allocType) {
1457 const RecordType *record =
1458 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1459 if (!record) return false;
1460
1461 // Try to find an operator delete[] in class scope.
1462
1463 DeclarationName deleteName =
1464 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1465 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1466 S.LookupQualifiedName(ops, record->getDecl());
1467
1468 // We're just doing this for information.
1469 ops.suppressDiagnostics();
1470
1471 // Very likely: there's no operator delete[].
1472 if (ops.empty()) return false;
1473
1474 // If it's ambiguous, it should be illegal to call operator delete[]
1475 // on this thing, so it doesn't matter if we allocate extra space or not.
1476 if (ops.isAmbiguous()) return false;
1477
Richard Smithb2f0f052016-10-10 18:54:32 +00001478 // C++17 [expr.delete]p10:
1479 // If the deallocation functions have class scope, the one without a
1480 // parameter of type std::size_t is selected.
1481 auto Best = resolveDeallocationOverload(
1482 S, ops, /*WantSize*/false,
1483 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1484 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001485}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001486
Sebastian Redld74dd492012-02-12 18:41:05 +00001487/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001488///
Sebastian Redld74dd492012-02-12 18:41:05 +00001489/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001490/// @code new (memory) int[size][4] @endcode
1491/// or
1492/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001493///
1494/// \param StartLoc The first location of the expression.
1495/// \param UseGlobal True if 'new' was prefixed with '::'.
1496/// \param PlacementLParen Opening paren of the placement arguments.
1497/// \param PlacementArgs Placement new arguments.
1498/// \param PlacementRParen Closing paren of the placement arguments.
1499/// \param TypeIdParens If the type is in parens, the source range.
1500/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001501/// \param Initializer The initializing expression or initializer-list, or null
1502/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001503ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001504Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001505 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001507 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001508 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001509 // If the specified type is an array, unwrap it and save the expression.
1510 if (D.getNumTypeObjects() > 0 &&
1511 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001512 DeclaratorChunk &Chunk = D.getTypeObject(0);
1513 if (D.getDeclSpec().containsPlaceholderType())
Richard Smith30482bc2011-02-20 03:19:35 +00001514 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1515 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001516 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001517 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1518 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001519 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001520 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1521 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001522
Sebastian Redl351bb782008-12-02 14:43:59 +00001523 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001524 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001525 }
1526
Douglas Gregor73341c42009-09-11 00:18:58 +00001527 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001528 if (ArraySize) {
1529 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001530 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1531 break;
1532
1533 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1534 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001535 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001536 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001537 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1538 // shall be a converted constant expression (5.19) of type std::size_t
1539 // and shall evaluate to a strictly positive value.
1540 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1541 assert(IntWidth && "Builtin type of size 0?");
1542 llvm::APSInt Value(IntWidth);
1543 Array.NumElts
1544 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1545 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001546 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001547 } else {
1548 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001549 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001550 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001551 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001552 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001553 if (!Array.NumElts)
1554 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001555 }
1556 }
1557 }
1558 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001559
Craig Topperc3ec1492014-05-26 06:22:03 +00001560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001561 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001562 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001563 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Sebastian Redl6047f072012-02-16 12:22:20 +00001565 SourceRange DirectInitRange;
Serge Pavlov38526372016-11-12 15:38:55 +00001566 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001567 DirectInitRange = List->getSourceRange();
Serge Pavlov38526372016-11-12 15:38:55 +00001568 // Handle errors like: new int a({0})
1569 if (List->getNumExprs() == 1 &&
1570 !canInitializeWithParenthesizedList(AllocType))
1571 if (auto IList = dyn_cast<InitListExpr>(List->getExpr(0))) {
1572 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1573 << AllocType << List->getSourceRange()
1574 << FixItHint::CreateRemoval(List->getLocStart())
1575 << FixItHint::CreateRemoval(List->getLocEnd());
1576 DirectInitRange = SourceRange();
1577 Initializer = IList;
1578 }
1579 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001580
David Blaikie7b97aef2012-11-07 00:12:38 +00001581 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001582 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001583 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001584 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001585 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001586 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001587 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001588 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001589 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001590 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001591}
1592
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001593static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1594 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001595 if (!Init)
1596 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001597 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1598 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001599 if (isa<ImplicitValueInitExpr>(Init))
1600 return true;
1601 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1602 return !CCE->isListInitialization() &&
1603 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001604 else if (Style == CXXNewExpr::ListInit) {
1605 assert(isa<InitListExpr>(Init) &&
1606 "Shouldn't create list CXXConstructExprs for arrays.");
1607 return true;
1608 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001609 return false;
1610}
1611
John McCalldadc5752010-08-24 06:29:42 +00001612ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001613Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001614 SourceLocation PlacementLParen,
1615 MultiExprArg PlacementArgs,
1616 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001617 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001618 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001619 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001620 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001621 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001622 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001623 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001624 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001625
Sebastian Redl6047f072012-02-16 12:22:20 +00001626 CXXNewExpr::InitializationStyle initStyle;
1627 if (DirectInitRange.isValid()) {
1628 assert(Initializer && "Have parens but no initializer.");
1629 initStyle = CXXNewExpr::CallInit;
1630 } else if (Initializer && isa<InitListExpr>(Initializer))
1631 initStyle = CXXNewExpr::ListInit;
1632 else {
1633 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1634 isa<CXXConstructExpr>(Initializer)) &&
1635 "Initializer expression that cannot have been implicitly created.");
1636 initStyle = CXXNewExpr::NoInit;
1637 }
1638
1639 Expr **Inits = &Initializer;
1640 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001641 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1642 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1643 Inits = List->getExprs();
1644 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001645 }
1646
Richard Smith66204ec2014-03-12 17:42:45 +00001647 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith3beb7c62017-01-12 02:27:38 +00001648 if (AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001649 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001650 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1651 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001652 if (initStyle == CXXNewExpr::ListInit ||
1653 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001654 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001655 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001656 << AllocType << TypeRange);
1657 if (NumInits > 1) {
1658 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001659 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001660 diag::err_auto_new_ctor_multiple_expressions)
1661 << AllocType << TypeRange);
1662 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001663 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001664 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001665 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001666 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001667 << AllocType << Deduce->getType()
1668 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001669 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001670 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001671 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001672 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001673
Douglas Gregorcda95f42010-05-16 16:01:03 +00001674 // Per C++0x [expr.new]p5, the type being constructed may be a
1675 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001676 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001677 if (const ConstantArrayType *Array
1678 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001679 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1680 Context.getSizeType(),
1681 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001682 AllocType = Array->getElementType();
1683 }
1684 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001685
Douglas Gregor3999e152010-10-06 16:00:31 +00001686 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1687 return ExprError();
1688
Craig Topperc3ec1492014-05-26 06:22:03 +00001689 if (initStyle == CXXNewExpr::ListInit &&
1690 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001691 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1692 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001693 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001694 }
1695
Simon Pilgrim75c26882016-09-30 14:25:09 +00001696 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001697 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001698 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1699 AllocType->isObjCLifetimeType()) {
1700 AllocType = Context.getLifetimeQualifiedType(AllocType,
1701 AllocType->getObjCARCImplicitLifetime());
1702 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001703
John McCall31168b02011-06-15 23:02:42 +00001704 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001705
John McCall5e77d762013-04-16 07:28:30 +00001706 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1707 ExprResult result = CheckPlaceholderExpr(ArraySize);
1708 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001709 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001710 }
Richard Smith8dd34252012-02-04 07:07:42 +00001711 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1712 // integral or enumeration type with a non-negative value."
1713 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1714 // enumeration type, or a class type for which a single non-explicit
1715 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001716 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001717 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001718 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001719 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001720 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001721 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001722 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1723
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001724 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1725 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001726
Simon Pilgrim75c26882016-09-30 14:25:09 +00001727 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001728 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001729 // Diagnose the compatibility of this conversion.
1730 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1731 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001732 } else {
1733 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1734 protected:
1735 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001736
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001737 public:
1738 SizeConvertDiagnoser(Expr *ArraySize)
1739 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1740 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001741
1742 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1743 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001744 return S.Diag(Loc, diag::err_array_size_not_integral)
1745 << S.getLangOpts().CPlusPlus11 << T;
1746 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001747
1748 SemaDiagnosticBuilder diagnoseIncomplete(
1749 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001750 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1751 << T << ArraySize->getSourceRange();
1752 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001753
1754 SemaDiagnosticBuilder diagnoseExplicitConv(
1755 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001756 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1757 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001758
1759 SemaDiagnosticBuilder noteExplicitConv(
1760 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001761 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1762 << ConvTy->isEnumeralType() << ConvTy;
1763 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001764
1765 SemaDiagnosticBuilder diagnoseAmbiguous(
1766 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001767 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1768 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001769
1770 SemaDiagnosticBuilder noteAmbiguous(
1771 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001772 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1773 << ConvTy->isEnumeralType() << ConvTy;
1774 }
Richard Smithccc11812013-05-21 19:05:48 +00001775
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001776 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1777 QualType T,
1778 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001779 return S.Diag(Loc,
1780 S.getLangOpts().CPlusPlus11
1781 ? diag::warn_cxx98_compat_array_size_conversion
1782 : diag::ext_array_size_conversion)
1783 << T << ConvTy->isEnumeralType() << ConvTy;
1784 }
1785 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001786
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001787 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1788 SizeDiagnoser);
1789 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001790 if (ConvertedSize.isInvalid())
1791 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001793 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001794 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001795
Douglas Gregor0bf31402010-10-08 23:50:27 +00001796 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001797 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001798
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001799 // C++98 [expr.new]p7:
1800 // The expression in a direct-new-declarator shall have integral type
1801 // with a non-negative value.
1802 //
Richard Smith0511d232016-10-05 22:41:02 +00001803 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1804 // per CWG1464. Otherwise, if it's not a constant, we must have an
1805 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001806 if (!ArraySize->isValueDependent()) {
1807 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001808 // We've already performed any required implicit conversion to integer or
1809 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001810 // FIXME: Per CWG1464, we are required to check the value prior to
1811 // converting to size_t. This will never find a negative array size in
1812 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001813 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001814 if (Value.isSigned() && Value.isNegative()) {
1815 return ExprError(Diag(ArraySize->getLocStart(),
1816 diag::err_typecheck_negative_array_size)
1817 << ArraySize->getSourceRange());
1818 }
1819
1820 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001821 unsigned ActiveSizeBits =
1822 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001823 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1824 return ExprError(Diag(ArraySize->getLocStart(),
1825 diag::err_array_too_large)
1826 << Value.toString(10)
1827 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001828 }
Richard Smith0511d232016-10-05 22:41:02 +00001829
1830 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001831 } else if (TypeIdParens.isValid()) {
1832 // Can't have dynamic array size when the type-id is in parentheses.
1833 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1834 << ArraySize->getSourceRange()
1835 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1836 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
Douglas Gregorf2753b32010-07-13 15:54:32 +00001838 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001839 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
John McCall036f2f62011-05-15 07:14:44 +00001842 // Note that we do *not* convert the argument in any way. It can
1843 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001844 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001845
Craig Topperc3ec1492014-05-26 06:22:03 +00001846 FunctionDecl *OperatorNew = nullptr;
1847 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001848 unsigned Alignment =
1849 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1850 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1851 bool PassAlignment = getLangOpts().AlignedAllocation &&
1852 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001854 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001855 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001856 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001857 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001858 UseGlobal, AllocType, ArraySize, PassAlignment,
1859 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001860 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001861
1862 // If this is an array allocation, compute whether the usual array
1863 // deallocation function for the type has a size_t parameter.
1864 bool UsualArrayDeleteWantsSize = false;
1865 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001866 UsualArrayDeleteWantsSize =
1867 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001868
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001869 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001870 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001871 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001872 OperatorNew->getType()->getAs<FunctionProtoType>();
1873 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1874 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001875
Richard Smithd6f9e732014-05-13 19:56:21 +00001876 // We've already converted the placement args, just fill in any default
1877 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001878 // argument. Skip the second parameter too if we're passing in the
1879 // alignment; we've already filled it in.
1880 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1881 PassAlignment ? 2 : 1, PlacementArgs,
1882 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001883 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001884
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001885 if (!AllPlaceArgs.empty())
1886 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001887
Richard Smithd6f9e732014-05-13 19:56:21 +00001888 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001889 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001890
1891 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Richard Smithb2f0f052016-10-10 18:54:32 +00001893 // Warn if the type is over-aligned and is being allocated by (unaligned)
1894 // global operator new.
1895 if (PlacementArgs.empty() && !PassAlignment &&
1896 (OperatorNew->isImplicit() ||
1897 (OperatorNew->getLocStart().isValid() &&
1898 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1899 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001900 Diag(StartLoc, diag::warn_overaligned_type)
1901 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001902 << unsigned(Alignment / Context.getCharWidth())
1903 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001904 }
1905 }
1906
Sebastian Redl6047f072012-02-16 12:22:20 +00001907 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001908 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1909 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001910 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1911 SourceRange InitRange(Inits[0]->getLocStart(),
1912 Inits[NumInits - 1]->getLocEnd());
1913 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1914 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001915 }
1916
Richard Smithdd2ca572012-11-26 08:32:48 +00001917 // If we can perform the initialization, and we've not already done so,
1918 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001919 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001920 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001921 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001922 // The type we initialize is the complete type, including the array bound.
1923 QualType InitType;
1924 if (KnownArraySize)
1925 InitType = Context.getConstantArrayType(
1926 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1927 *KnownArraySize),
1928 ArrayType::Normal, 0);
1929 else if (ArraySize)
1930 InitType =
1931 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1932 else
1933 InitType = AllocType;
1934
Sebastian Redld74dd492012-02-12 18:41:05 +00001935 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001936 // A new-expression that creates an object of type T initializes that
1937 // object as follows:
1938 InitializationKind Kind
1939 // - If the new-initializer is omitted, the object is default-
1940 // initialized (8.5); if no initialization is performed,
1941 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001942 = initStyle == CXXNewExpr::NoInit
1943 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001945 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001946 : initStyle == CXXNewExpr::ListInit
1947 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1948 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1949 DirectInitRange.getBegin(),
1950 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951
Douglas Gregor85dabae2009-12-16 01:38:02 +00001952 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001953 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001954 InitializationSequence InitSeq(*this, Entity, Kind,
1955 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001957 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001958 if (FullInit.isInvalid())
1959 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960
Sebastian Redl6047f072012-02-16 12:22:20 +00001961 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1962 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001963 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001964 if (CXXBindTemporaryExpr *Binder =
1965 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001966 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001968 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Douglas Gregor6642ca22010-02-26 05:06:18 +00001971 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001972 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001973 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1974 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001975 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001976 }
1977 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001978 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1979 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001980 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001981 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001982
John McCall928a2572011-07-13 20:12:57 +00001983 // C++0x [expr.new]p17:
1984 // If the new expression creates an array of objects of class type,
1985 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001986 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1987 if (ArraySize && !BaseAllocType->isDependentType()) {
1988 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1989 if (CXXDestructorDecl *dtor = LookupDestructor(
1990 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1991 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001992 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00001993 PDiag(diag::err_access_dtor)
1994 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001995 if (DiagnoseUseOfDecl(dtor, StartLoc))
1996 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001997 }
John McCall928a2572011-07-13 20:12:57 +00001998 }
1999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002001 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002002 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002003 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2004 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2005 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002006}
2007
Sebastian Redl6047f072012-02-16 12:22:20 +00002008/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002009/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002010bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002011 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002012 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2013 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002014 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002015 return Diag(Loc, diag::err_bad_new_type)
2016 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002017 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002018 return Diag(Loc, diag::err_bad_new_type)
2019 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002020 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002021 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002022 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002023 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002024 diag::err_allocation_of_abstract_type))
2025 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002026 else if (AllocType->isVariablyModifiedType())
2027 return Diag(Loc, diag::err_variably_modified_new_type)
2028 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002029 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2030 return Diag(Loc, diag::err_address_space_qualified_new)
2031 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002032 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002033 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2034 QualType BaseAllocType = Context.getBaseElementType(AT);
2035 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2036 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002037 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002038 << BaseAllocType;
2039 }
2040 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002041
Sebastian Redlbd150f42008-11-21 19:14:01 +00002042 return false;
2043}
2044
Richard Smithb2f0f052016-10-10 18:54:32 +00002045static bool
2046resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2047 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2048 FunctionDecl *&Operator,
2049 OverloadCandidateSet *AlignedCandidates = nullptr,
2050 Expr *AlignArg = nullptr) {
2051 OverloadCandidateSet Candidates(R.getNameLoc(),
2052 OverloadCandidateSet::CSK_Normal);
2053 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2054 Alloc != AllocEnd; ++Alloc) {
2055 // Even member operator new/delete are implicitly treated as
2056 // static, so don't use AddMemberCandidate.
2057 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2058
2059 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2060 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2061 /*ExplicitTemplateArgs=*/nullptr, Args,
2062 Candidates,
2063 /*SuppressUserConversions=*/false);
2064 continue;
2065 }
2066
2067 FunctionDecl *Fn = cast<FunctionDecl>(D);
2068 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2069 /*SuppressUserConversions=*/false);
2070 }
2071
2072 // Do the resolution.
2073 OverloadCandidateSet::iterator Best;
2074 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2075 case OR_Success: {
2076 // Got one!
2077 FunctionDecl *FnDecl = Best->Function;
2078 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2079 Best->FoundDecl) == Sema::AR_inaccessible)
2080 return true;
2081
2082 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002083 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002084 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002085
Richard Smithb2f0f052016-10-10 18:54:32 +00002086 case OR_No_Viable_Function:
2087 // C++17 [expr.new]p13:
2088 // If no matching function is found and the allocated object type has
2089 // new-extended alignment, the alignment argument is removed from the
2090 // argument list, and overload resolution is performed again.
2091 if (PassAlignment) {
2092 PassAlignment = false;
2093 AlignArg = Args[1];
2094 Args.erase(Args.begin() + 1);
2095 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2096 Operator, &Candidates, AlignArg);
2097 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002098
Richard Smithb2f0f052016-10-10 18:54:32 +00002099 // MSVC will fall back on trying to find a matching global operator new
2100 // if operator new[] cannot be found. Also, MSVC will leak by not
2101 // generating a call to operator delete or operator delete[], but we
2102 // will not replicate that bug.
2103 // FIXME: Find out how this interacts with the std::align_val_t fallback
2104 // once MSVC implements it.
2105 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2106 S.Context.getLangOpts().MSVCCompat) {
2107 R.clear();
2108 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2109 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2110 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2111 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2112 Operator, nullptr);
2113 }
Richard Smith1cdec012013-09-29 04:40:38 +00002114
Richard Smithb2f0f052016-10-10 18:54:32 +00002115 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2116 << R.getLookupName() << Range;
2117
2118 // If we have aligned candidates, only note the align_val_t candidates
2119 // from AlignedCandidates and the non-align_val_t candidates from
2120 // Candidates.
2121 if (AlignedCandidates) {
2122 auto IsAligned = [](OverloadCandidate &C) {
2123 return C.Function->getNumParams() > 1 &&
2124 C.Function->getParamDecl(1)->getType()->isAlignValT();
2125 };
2126 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2127
2128 // This was an overaligned allocation, so list the aligned candidates
2129 // first.
2130 Args.insert(Args.begin() + 1, AlignArg);
2131 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2132 R.getNameLoc(), IsAligned);
2133 Args.erase(Args.begin() + 1);
2134 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2135 IsUnaligned);
2136 } else {
2137 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2138 }
Richard Smith1cdec012013-09-29 04:40:38 +00002139 return true;
2140
Richard Smithb2f0f052016-10-10 18:54:32 +00002141 case OR_Ambiguous:
2142 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2143 << R.getLookupName() << Range;
2144 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2145 return true;
2146
2147 case OR_Deleted: {
2148 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2149 << Best->Function->isDeleted()
2150 << R.getLookupName()
2151 << S.getDeletedOrUnavailableSuffix(Best->Function)
2152 << Range;
2153 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2154 return true;
2155 }
2156 }
2157 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002158}
2159
Richard Smithb2f0f052016-10-10 18:54:32 +00002160
Sebastian Redlfaf68082008-12-03 20:26:15 +00002161/// FindAllocationFunctions - Finds the overloads of operator new and delete
2162/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002163bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2164 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002165 bool IsArray, bool &PassAlignment,
2166 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002167 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002168 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002169 // --- Choosing an allocation function ---
2170 // C++ 5.3.4p8 - 14 & 18
2171 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2172 // in the scope of the allocated class.
2173 // 2) If an array size is given, look for operator new[], else look for
2174 // operator new.
2175 // 3) The first argument is always size_t. Append the arguments from the
2176 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002177
Richard Smithb2f0f052016-10-10 18:54:32 +00002178 SmallVector<Expr*, 8> AllocArgs;
2179 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2180
2181 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002182 // FIXME: Should the Sema create the expression and embed it in the syntax
2183 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002184 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002185 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002186 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002187 Context.getSizeType(),
2188 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002189 AllocArgs.push_back(&Size);
2190
2191 QualType AlignValT = Context.VoidTy;
2192 if (PassAlignment) {
2193 DeclareGlobalNewDelete();
2194 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2195 }
2196 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2197 if (PassAlignment)
2198 AllocArgs.push_back(&Align);
2199
2200 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002201
Douglas Gregor6642ca22010-02-26 05:06:18 +00002202 // C++ [expr.new]p8:
2203 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002204 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002205 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002206 // type, the allocation function's name is operator new[] and the
2207 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002208 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002209 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002210
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002211 QualType AllocElemType = Context.getBaseElementType(AllocType);
2212
Richard Smithb2f0f052016-10-10 18:54:32 +00002213 // Find the allocation function.
2214 {
2215 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2216
2217 // C++1z [expr.new]p9:
2218 // If the new-expression begins with a unary :: operator, the allocation
2219 // function's name is looked up in the global scope. Otherwise, if the
2220 // allocated type is a class type T or array thereof, the allocation
2221 // function's name is looked up in the scope of T.
2222 if (AllocElemType->isRecordType() && !UseGlobal)
2223 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2224
2225 // We can see ambiguity here if the allocation function is found in
2226 // multiple base classes.
2227 if (R.isAmbiguous())
2228 return true;
2229
2230 // If this lookup fails to find the name, or if the allocated type is not
2231 // a class type, the allocation function's name is looked up in the
2232 // global scope.
2233 if (R.empty())
2234 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2235
2236 assert(!R.empty() && "implicitly declared allocation functions not found");
2237 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2238
2239 // We do our own custom access checks below.
2240 R.suppressDiagnostics();
2241
2242 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2243 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002244 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002245 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002246
Richard Smithb2f0f052016-10-10 18:54:32 +00002247 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002248 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002249 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002250 return false;
2251 }
2252
Richard Smithb2f0f052016-10-10 18:54:32 +00002253 // Note, the name of OperatorNew might have been changed from array to
2254 // non-array by resolveAllocationOverload.
2255 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2256 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2257 ? OO_Array_Delete
2258 : OO_Delete);
2259
Douglas Gregor6642ca22010-02-26 05:06:18 +00002260 // C++ [expr.new]p19:
2261 //
2262 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002263 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002264 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002265 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002266 // the scope of T. If this lookup fails to find the name, or if
2267 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002268 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002269 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002270 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002271 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002272 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002273 LookupQualifiedName(FoundDelete, RD);
2274 }
John McCallfb6f5262010-03-18 08:19:33 +00002275 if (FoundDelete.isAmbiguous())
2276 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002277
Richard Smithb2f0f052016-10-10 18:54:32 +00002278 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002279 if (FoundDelete.empty()) {
2280 DeclareGlobalNewDelete();
2281 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2282 }
2283
2284 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002285
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002286 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002287
John McCalld3be2c82010-09-14 21:34:24 +00002288 // Whether we're looking for a placement operator delete is dictated
2289 // by whether we selected a placement operator new, not by whether
2290 // we had explicit placement arguments. This matters for things like
2291 // struct A { void *operator new(size_t, int = 0); ... };
2292 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002293 //
2294 // We don't have any definition for what a "placement allocation function"
2295 // is, but we assume it's any allocation function whose
2296 // parameter-declaration-clause is anything other than (size_t).
2297 //
2298 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2299 // This affects whether an exception from the constructor of an overaligned
2300 // type uses the sized or non-sized form of aligned operator delete.
2301 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2302 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002303
2304 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002305 // C++ [expr.new]p20:
2306 // A declaration of a placement deallocation function matches the
2307 // declaration of a placement allocation function if it has the
2308 // same number of parameters and, after parameter transformations
2309 // (8.3.5), all parameter types except the first are
2310 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002312 // To perform this comparison, we compute the function type that
2313 // the deallocation function should have, and use that type both
2314 // for template argument deduction and for comparison purposes.
2315 QualType ExpectedFunctionType;
2316 {
2317 const FunctionProtoType *Proto
2318 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002320 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002322 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2323 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002324
John McCalldb40c7f2010-12-14 08:05:40 +00002325 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002326 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002327 EPI.Variadic = Proto->isVariadic();
2328
Douglas Gregor6642ca22010-02-26 05:06:18 +00002329 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002330 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002331 }
2332
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002333 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002334 DEnd = FoundDelete.end();
2335 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002336 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002337 if (FunctionTemplateDecl *FnTmpl =
2338 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002339 // Perform template argument deduction to try to match the
2340 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002341 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002342 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2343 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002344 continue;
2345 } else
2346 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2347
Richard Smithbaa47832016-12-01 02:11:49 +00002348 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2349 ExpectedFunctionType,
2350 /*AdjustExcpetionSpec*/true),
2351 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002352 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002353 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002354
Richard Smithb2f0f052016-10-10 18:54:32 +00002355 if (getLangOpts().CUDA)
2356 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2357 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002358 // C++1y [expr.new]p22:
2359 // For a non-placement allocation function, the normal deallocation
2360 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002361 //
2362 // Per [expr.delete]p10, this lookup prefers a member operator delete
2363 // without a size_t argument, but prefers a non-member operator delete
2364 // with a size_t where possible (which it always is in this case).
2365 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2366 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2367 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2368 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2369 &BestDeallocFns);
2370 if (Selected)
2371 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2372 else {
2373 // If we failed to select an operator, all remaining functions are viable
2374 // but ambiguous.
2375 for (auto Fn : BestDeallocFns)
2376 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002377 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002378 }
2379
2380 // C++ [expr.new]p20:
2381 // [...] If the lookup finds a single matching deallocation
2382 // function, that function will be called; otherwise, no
2383 // deallocation function will be called.
2384 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002385 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002386
Richard Smithb2f0f052016-10-10 18:54:32 +00002387 // C++1z [expr.new]p23:
2388 // If the lookup finds a usual deallocation function (3.7.4.2)
2389 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002390 // as a placement deallocation function, would have been
2391 // selected as a match for the allocation function, the program
2392 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002393 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002394 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002395 UsualDeallocFnInfo Info(*this,
2396 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002397 // Core issue, per mail to core reflector, 2016-10-09:
2398 // If this is a member operator delete, and there is a corresponding
2399 // non-sized member operator delete, this isn't /really/ a sized
2400 // deallocation function, it just happens to have a size_t parameter.
2401 bool IsSizedDelete = Info.HasSizeT;
2402 if (IsSizedDelete && !FoundGlobalDelete) {
2403 auto NonSizedDelete =
2404 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2405 /*WantAlign*/Info.HasAlignValT);
2406 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2407 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2408 IsSizedDelete = false;
2409 }
2410
2411 if (IsSizedDelete) {
2412 SourceRange R = PlaceArgs.empty()
2413 ? SourceRange()
2414 : SourceRange(PlaceArgs.front()->getLocStart(),
2415 PlaceArgs.back()->getLocEnd());
2416 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2417 if (!OperatorDelete->isImplicit())
2418 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2419 << DeleteName;
2420 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002421 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002422
2423 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2424 Matches[0].first);
2425 } else if (!Matches.empty()) {
2426 // We found multiple suitable operators. Per [expr.new]p20, that means we
2427 // call no 'operator delete' function, but we should at least warn the user.
2428 // FIXME: Suppress this warning if the construction cannot throw.
2429 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2430 << DeleteName << AllocElemType;
2431
2432 for (auto &Match : Matches)
2433 Diag(Match.second->getLocation(),
2434 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002435 }
2436
Sebastian Redlfaf68082008-12-03 20:26:15 +00002437 return false;
2438}
2439
2440/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2441/// delete. These are:
2442/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002443/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002444/// void* operator new(std::size_t) throw(std::bad_alloc);
2445/// void* operator new[](std::size_t) throw(std::bad_alloc);
2446/// void operator delete(void *) throw();
2447/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002448/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002449/// void* operator new(std::size_t);
2450/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002451/// void operator delete(void *) noexcept;
2452/// void operator delete[](void *) noexcept;
2453/// // C++1y:
2454/// void* operator new(std::size_t);
2455/// void* operator new[](std::size_t);
2456/// void operator delete(void *) noexcept;
2457/// void operator delete[](void *) noexcept;
2458/// void operator delete(void *, std::size_t) noexcept;
2459/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002460/// @endcode
2461/// Note that the placement and nothrow forms of new are *not* implicitly
2462/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002463void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002464 if (GlobalNewDeleteDeclared)
2465 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002466
Douglas Gregor87f54062009-09-15 22:30:29 +00002467 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468 // [...] The following allocation and deallocation functions (18.4) are
2469 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002470 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471 //
Sebastian Redl37588092011-03-14 18:08:30 +00002472 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002473 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002474 // void* operator new[](std::size_t) throw(std::bad_alloc);
2475 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002476 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002477 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002478 // void* operator new(std::size_t);
2479 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002480 // void operator delete(void*) noexcept;
2481 // void operator delete[](void*) noexcept;
2482 // C++1y:
2483 // void* operator new(std::size_t);
2484 // void* operator new[](std::size_t);
2485 // void operator delete(void*) noexcept;
2486 // void operator delete[](void*) noexcept;
2487 // void operator delete(void*, std::size_t) noexcept;
2488 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002489 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002490 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002491 // new, operator new[], operator delete, operator delete[].
2492 //
2493 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2494 // "std" or "bad_alloc" as necessary to form the exception specification.
2495 // However, we do not make these implicit declarations visible to name
2496 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002497 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002498 // The "std::bad_alloc" class has not yet been declared, so build it
2499 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002500 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2501 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002502 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002503 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002504 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002505 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002506 }
Richard Smith59139022016-09-30 22:41:36 +00002507 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002508 // The "std::align_val_t" enum class has not yet been declared, so build it
2509 // implicitly.
2510 auto *AlignValT = EnumDecl::Create(
2511 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2512 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2513 AlignValT->setIntegerType(Context.getSizeType());
2514 AlignValT->setPromotionType(Context.getSizeType());
2515 AlignValT->setImplicit(true);
2516 StdAlignValT = AlignValT;
2517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518
Sebastian Redlfaf68082008-12-03 20:26:15 +00002519 GlobalNewDeleteDeclared = true;
2520
2521 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2522 QualType SizeT = Context.getSizeType();
2523
Richard Smith96269c52016-09-29 22:49:46 +00002524 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2525 QualType Return, QualType Param) {
2526 llvm::SmallVector<QualType, 3> Params;
2527 Params.push_back(Param);
2528
2529 // Create up to four variants of the function (sized/aligned).
2530 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2531 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002532 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002533
2534 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2535 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2536 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002537 if (Sized)
2538 Params.push_back(SizeT);
2539
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002540 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002541 if (Aligned)
2542 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2543
2544 DeclareGlobalAllocationFunction(
2545 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2546
2547 if (Aligned)
2548 Params.pop_back();
2549 }
2550 }
2551 };
2552
2553 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2554 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2555 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2556 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002557}
2558
2559/// DeclareGlobalAllocationFunction - Declares a single implicit global
2560/// allocation function if it doesn't already exist.
2561void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002562 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002563 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002564 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2565
2566 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002567 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2568 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2569 Alloc != AllocEnd; ++Alloc) {
2570 // Only look at non-template functions, as it is the predefined,
2571 // non-templated allocation function we are trying to declare here.
2572 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002573 if (Func->getNumParams() == Params.size()) {
2574 llvm::SmallVector<QualType, 3> FuncParams;
2575 for (auto *P : Func->parameters())
2576 FuncParams.push_back(
2577 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2578 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002579 // Make the function visible to name lookup, even if we found it in
2580 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002581 // allocation function, or is suppressing that function.
2582 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002583 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002584 }
Chandler Carruth93538422010-02-03 11:02:14 +00002585 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002586 }
2587 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002588
Richard Smithc015bc22014-02-07 22:39:53 +00002589 FunctionProtoType::ExtProtoInfo EPI;
2590
Richard Smithf8b417c2014-02-08 00:42:45 +00002591 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002592 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002593 = (Name.getCXXOverloadedOperator() == OO_New ||
2594 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002595 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002596 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002597 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002598 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002599 EPI.ExceptionSpec.Type = EST_Dynamic;
2600 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002601 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002602 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002603 EPI.ExceptionSpec =
2604 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606
Artem Belevich07db5cf2016-10-21 20:34:05 +00002607 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2608 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2609 FunctionDecl *Alloc = FunctionDecl::Create(
2610 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2611 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2612 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002613
Artem Belevich07db5cf2016-10-21 20:34:05 +00002614 // Implicit sized deallocation functions always have default visibility.
2615 Alloc->addAttr(
2616 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617
Artem Belevich07db5cf2016-10-21 20:34:05 +00002618 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2619 for (QualType T : Params) {
2620 ParamDecls.push_back(ParmVarDecl::Create(
2621 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2622 /*TInfo=*/nullptr, SC_None, nullptr));
2623 ParamDecls.back()->setImplicit();
2624 }
2625 Alloc->setParams(ParamDecls);
2626 if (ExtraAttr)
2627 Alloc->addAttr(ExtraAttr);
2628 Context.getTranslationUnitDecl()->addDecl(Alloc);
2629 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2630 };
2631
2632 if (!LangOpts.CUDA)
2633 CreateAllocationFunctionDecl(nullptr);
2634 else {
2635 // Host and device get their own declaration so each can be
2636 // defined or re-declared independently.
2637 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2638 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002639 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002640}
2641
Richard Smith1cdec012013-09-29 04:40:38 +00002642FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2643 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002644 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002645 DeclarationName Name) {
2646 DeclareGlobalNewDelete();
2647
2648 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2649 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2650
Richard Smithb2f0f052016-10-10 18:54:32 +00002651 // FIXME: It's possible for this to result in ambiguity, through a
2652 // user-declared variadic operator delete or the enable_if attribute. We
2653 // should probably not consider those cases to be usual deallocation
2654 // functions. But for now we just make an arbitrary choice in that case.
2655 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2656 Overaligned);
2657 assert(Result.FD && "operator delete missing from global scope?");
2658 return Result.FD;
2659}
Richard Smith1cdec012013-09-29 04:40:38 +00002660
Richard Smithb2f0f052016-10-10 18:54:32 +00002661FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2662 CXXRecordDecl *RD) {
2663 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002664
Richard Smithb2f0f052016-10-10 18:54:32 +00002665 FunctionDecl *OperatorDelete = nullptr;
2666 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2667 return nullptr;
2668 if (OperatorDelete)
2669 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002670
Richard Smithb2f0f052016-10-10 18:54:32 +00002671 // If there's no class-specific operator delete, look up the global
2672 // non-array delete.
2673 return FindUsualDeallocationFunction(
2674 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2675 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002676}
2677
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002678bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2679 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002680 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002681 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002682 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002683 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002684
John McCall27b18f82009-11-17 02:14:36 +00002685 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002686 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002687
Chandler Carruthb6f99172010-06-28 00:30:51 +00002688 Found.suppressDiagnostics();
2689
Richard Smithb2f0f052016-10-10 18:54:32 +00002690 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002691
Richard Smithb2f0f052016-10-10 18:54:32 +00002692 // C++17 [expr.delete]p10:
2693 // If the deallocation functions have class scope, the one without a
2694 // parameter of type std::size_t is selected.
2695 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2696 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2697 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002698
Richard Smithb2f0f052016-10-10 18:54:32 +00002699 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002700 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002701 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002702
Richard Smithb2f0f052016-10-10 18:54:32 +00002703 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002704 if (Operator->isDeleted()) {
2705 if (Diagnose) {
2706 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002707 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002708 }
2709 return true;
2710 }
2711
Richard Smith921bd202012-02-26 09:11:52 +00002712 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002713 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002714 return true;
2715
John McCall66a87592010-08-04 00:31:26 +00002716 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002717 }
John McCall66a87592010-08-04 00:31:26 +00002718
Richard Smithb2f0f052016-10-10 18:54:32 +00002719 // We found multiple suitable operators; complain about the ambiguity.
2720 // FIXME: The standard doesn't say to do this; it appears that the intent
2721 // is that this should never happen.
2722 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002723 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002724 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2725 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002726 for (auto &Match : Matches)
2727 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002728 }
John McCall66a87592010-08-04 00:31:26 +00002729 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002730 }
2731
2732 // We did find operator delete/operator delete[] declarations, but
2733 // none of them were suitable.
2734 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002735 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002736 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2737 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738
Richard Smithb2f0f052016-10-10 18:54:32 +00002739 for (NamedDecl *D : Found)
2740 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002741 diag::note_member_declared_here) << Name;
2742 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002743 return true;
2744 }
2745
Craig Topperc3ec1492014-05-26 06:22:03 +00002746 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002747 return false;
2748}
2749
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002750namespace {
2751/// \brief Checks whether delete-expression, and new-expression used for
2752/// initializing deletee have the same array form.
2753class MismatchingNewDeleteDetector {
2754public:
2755 enum MismatchResult {
2756 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2757 NoMismatch,
2758 /// Indicates that variable is initialized with mismatching form of \a new.
2759 VarInitMismatches,
2760 /// Indicates that member is initialized with mismatching form of \a new.
2761 MemberInitMismatches,
2762 /// Indicates that 1 or more constructors' definitions could not been
2763 /// analyzed, and they will be checked again at the end of translation unit.
2764 AnalyzeLater
2765 };
2766
2767 /// \param EndOfTU True, if this is the final analysis at the end of
2768 /// translation unit. False, if this is the initial analysis at the point
2769 /// delete-expression was encountered.
2770 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002771 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002772 HasUndefinedConstructors(false) {}
2773
2774 /// \brief Checks whether pointee of a delete-expression is initialized with
2775 /// matching form of new-expression.
2776 ///
2777 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2778 /// point where delete-expression is encountered, then a warning will be
2779 /// issued immediately. If return value is \c AnalyzeLater at the point where
2780 /// delete-expression is seen, then member will be analyzed at the end of
2781 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2782 /// couldn't be analyzed. If at least one constructor initializes the member
2783 /// with matching type of new, the return value is \c NoMismatch.
2784 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2785 /// \brief Analyzes a class member.
2786 /// \param Field Class member to analyze.
2787 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2788 /// for deleting the \p Field.
2789 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002790 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002791 /// List of mismatching new-expressions used for initialization of the pointee
2792 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2793 /// Indicates whether delete-expression was in array form.
2794 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002795
2796private:
2797 const bool EndOfTU;
2798 /// \brief Indicates that there is at least one constructor without body.
2799 bool HasUndefinedConstructors;
2800 /// \brief Returns \c CXXNewExpr from given initialization expression.
2801 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002802 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002803 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2804 /// \brief Returns whether member is initialized with mismatching form of
2805 /// \c new either by the member initializer or in-class initialization.
2806 ///
2807 /// If bodies of all constructors are not visible at the end of translation
2808 /// unit or at least one constructor initializes member with the matching
2809 /// form of \c new, mismatch cannot be proven, and this function will return
2810 /// \c NoMismatch.
2811 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2812 /// \brief Returns whether variable is initialized with mismatching form of
2813 /// \c new.
2814 ///
2815 /// If variable is initialized with matching form of \c new or variable is not
2816 /// initialized with a \c new expression, this function will return true.
2817 /// If variable is initialized with mismatching form of \c new, returns false.
2818 /// \param D Variable to analyze.
2819 bool hasMatchingVarInit(const DeclRefExpr *D);
2820 /// \brief Checks whether the constructor initializes pointee with mismatching
2821 /// form of \c new.
2822 ///
2823 /// Returns true, if member is initialized with matching form of \c new in
2824 /// member initializer list. Returns false, if member is initialized with the
2825 /// matching form of \c new in this constructor's initializer or given
2826 /// constructor isn't defined at the point where delete-expression is seen, or
2827 /// member isn't initialized by the constructor.
2828 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2829 /// \brief Checks whether member is initialized with matching form of
2830 /// \c new in member initializer list.
2831 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2832 /// Checks whether member is initialized with mismatching form of \c new by
2833 /// in-class initializer.
2834 MismatchResult analyzeInClassInitializer();
2835};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002836}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002837
2838MismatchingNewDeleteDetector::MismatchResult
2839MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2840 NewExprs.clear();
2841 assert(DE && "Expected delete-expression");
2842 IsArrayForm = DE->isArrayForm();
2843 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2844 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2845 return analyzeMemberExpr(ME);
2846 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2847 if (!hasMatchingVarInit(D))
2848 return VarInitMismatches;
2849 }
2850 return NoMismatch;
2851}
2852
2853const CXXNewExpr *
2854MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2855 assert(E != nullptr && "Expected a valid initializer expression");
2856 E = E->IgnoreParenImpCasts();
2857 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2858 if (ILE->getNumInits() == 1)
2859 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2860 }
2861
2862 return dyn_cast_or_null<const CXXNewExpr>(E);
2863}
2864
2865bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2866 const CXXCtorInitializer *CI) {
2867 const CXXNewExpr *NE = nullptr;
2868 if (Field == CI->getMember() &&
2869 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2870 if (NE->isArray() == IsArrayForm)
2871 return true;
2872 else
2873 NewExprs.push_back(NE);
2874 }
2875 return false;
2876}
2877
2878bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2879 const CXXConstructorDecl *CD) {
2880 if (CD->isImplicit())
2881 return false;
2882 const FunctionDecl *Definition = CD;
2883 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2884 HasUndefinedConstructors = true;
2885 return EndOfTU;
2886 }
2887 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2888 if (hasMatchingNewInCtorInit(CI))
2889 return true;
2890 }
2891 return false;
2892}
2893
2894MismatchingNewDeleteDetector::MismatchResult
2895MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2896 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002897 const Expr *InitExpr = Field->getInClassInitializer();
2898 if (!InitExpr)
2899 return EndOfTU ? NoMismatch : AnalyzeLater;
2900 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002901 if (NE->isArray() != IsArrayForm) {
2902 NewExprs.push_back(NE);
2903 return MemberInitMismatches;
2904 }
2905 }
2906 return NoMismatch;
2907}
2908
2909MismatchingNewDeleteDetector::MismatchResult
2910MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2911 bool DeleteWasArrayForm) {
2912 assert(Field != nullptr && "Analysis requires a valid class member.");
2913 this->Field = Field;
2914 IsArrayForm = DeleteWasArrayForm;
2915 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2916 for (const auto *CD : RD->ctors()) {
2917 if (hasMatchingNewInCtor(CD))
2918 return NoMismatch;
2919 }
2920 if (HasUndefinedConstructors)
2921 return EndOfTU ? NoMismatch : AnalyzeLater;
2922 if (!NewExprs.empty())
2923 return MemberInitMismatches;
2924 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2925 : NoMismatch;
2926}
2927
2928MismatchingNewDeleteDetector::MismatchResult
2929MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2930 assert(ME != nullptr && "Expected a member expression");
2931 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2932 return analyzeField(F, IsArrayForm);
2933 return NoMismatch;
2934}
2935
2936bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2937 const CXXNewExpr *NE = nullptr;
2938 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2939 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2940 NE->isArray() != IsArrayForm) {
2941 NewExprs.push_back(NE);
2942 }
2943 }
2944 return NewExprs.empty();
2945}
2946
2947static void
2948DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2949 const MismatchingNewDeleteDetector &Detector) {
2950 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2951 FixItHint H;
2952 if (!Detector.IsArrayForm)
2953 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2954 else {
2955 SourceLocation RSquare = Lexer::findLocationAfterToken(
2956 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2957 SemaRef.getLangOpts(), true);
2958 if (RSquare.isValid())
2959 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2960 }
2961 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2962 << Detector.IsArrayForm << H;
2963
2964 for (const auto *NE : Detector.NewExprs)
2965 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2966 << Detector.IsArrayForm;
2967}
2968
2969void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2970 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2971 return;
2972 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2973 switch (Detector.analyzeDeleteExpr(DE)) {
2974 case MismatchingNewDeleteDetector::VarInitMismatches:
2975 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2976 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2977 break;
2978 }
2979 case MismatchingNewDeleteDetector::AnalyzeLater: {
2980 DeleteExprs[Detector.Field].push_back(
2981 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2982 break;
2983 }
2984 case MismatchingNewDeleteDetector::NoMismatch:
2985 break;
2986 }
2987}
2988
2989void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2990 bool DeleteWasArrayForm) {
2991 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2992 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2993 case MismatchingNewDeleteDetector::VarInitMismatches:
2994 llvm_unreachable("This analysis should have been done for class members.");
2995 case MismatchingNewDeleteDetector::AnalyzeLater:
2996 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2997 "translation unit.");
2998 case MismatchingNewDeleteDetector::MemberInitMismatches:
2999 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3000 break;
3001 case MismatchingNewDeleteDetector::NoMismatch:
3002 break;
3003 }
3004}
3005
Sebastian Redlbd150f42008-11-21 19:14:01 +00003006/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3007/// @code ::delete ptr; @endcode
3008/// or
3009/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003010ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003011Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003012 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003013 // C++ [expr.delete]p1:
3014 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003015 // non-explicit conversion function to a pointer type. The result has type
3016 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003017 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003018 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3019
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003020 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003021 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003022 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003023 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003024
John Wiegley01296292011-04-08 18:41:53 +00003025 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003026 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003027 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003028 if (Ex.isInvalid())
3029 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003030
John Wiegley01296292011-04-08 18:41:53 +00003031 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003032
Richard Smithccc11812013-05-21 19:05:48 +00003033 class DeleteConverter : public ContextualImplicitConverter {
3034 public:
3035 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
Craig Toppere14c0f82014-03-12 04:55:44 +00003037 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003038 // FIXME: If we have an operator T* and an operator void*, we must pick
3039 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003040 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003041 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003042 return true;
3043 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003044 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003045
Richard Smithccc11812013-05-21 19:05:48 +00003046 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003047 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003048 return S.Diag(Loc, diag::err_delete_operand) << T;
3049 }
3050
3051 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003052 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003053 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3054 }
3055
3056 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003057 QualType T,
3058 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003059 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3060 }
3061
3062 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003063 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003064 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3065 << ConvTy;
3066 }
3067
3068 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003069 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003070 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3071 }
3072
3073 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003074 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003075 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3076 << ConvTy;
3077 }
3078
3079 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003080 QualType T,
3081 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003082 llvm_unreachable("conversion functions are permitted");
3083 }
3084 } Converter;
3085
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003086 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003087 if (Ex.isInvalid())
3088 return ExprError();
3089 Type = Ex.get()->getType();
3090 if (!Converter.match(Type))
3091 // FIXME: PerformContextualImplicitConversion should return ExprError
3092 // itself in this case.
3093 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003094
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003095 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003096 QualType PointeeElem = Context.getBaseElementType(Pointee);
3097
3098 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003099 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003100 diag::err_address_space_qualified_delete)
3101 << Pointee.getUnqualifiedType() << AddressSpace;
3102
Craig Topperc3ec1492014-05-26 06:22:03 +00003103 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003104 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003106 // effectively bans deletion of "void*". However, most compilers support
3107 // this, so we treat it as a warning unless we're in a SFINAE context.
3108 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003109 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003110 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003111 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003112 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003113 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003114 // FIXME: This can result in errors if the definition was imported from a
3115 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003116 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003117 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003118 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3119 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3120 }
3121 }
3122
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003123 if (Pointee->isArrayType() && !ArrayForm) {
3124 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003125 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003126 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003127 ArrayForm = true;
3128 }
3129
Anders Carlssona471db02009-08-16 20:29:29 +00003130 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3131 ArrayForm ? OO_Array_Delete : OO_Delete);
3132
Eli Friedmanae4280f2011-07-26 22:25:31 +00003133 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003135 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3136 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003137 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003138
John McCall284c48f2011-01-27 09:37:56 +00003139 // If we're allocating an array of records, check whether the
3140 // usual operator delete[] has a size_t parameter.
3141 if (ArrayForm) {
3142 // If the user specifically asked to use the global allocator,
3143 // we'll need to do the lookup into the class.
3144 if (UseGlobal)
3145 UsualArrayDeleteWantsSize =
3146 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3147
3148 // Otherwise, the usual operator delete[] should be the
3149 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003150 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003151 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003152 UsualDeallocFnInfo(*this,
3153 DeclAccessPair::make(OperatorDelete, AS_public))
3154 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003155 }
3156
Richard Smitheec915d62012-02-18 04:13:32 +00003157 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003158 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003159 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003160 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003161 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3162 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003163 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003164
Nico Weber5a9259c2016-01-15 21:45:31 +00003165 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3166 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3167 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3168 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170
Richard Smithb2f0f052016-10-10 18:54:32 +00003171 if (!OperatorDelete) {
3172 bool IsComplete = isCompleteType(StartLoc, Pointee);
3173 bool CanProvideSize =
3174 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3175 Pointee.isDestructedType());
3176 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3177
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003178 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003179 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3180 Overaligned, DeleteName);
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
Eli Friedmanfa0df832012-02-02 03:46:19 +00003183 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003184
Douglas Gregorfa778132011-02-01 15:50:11 +00003185 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003186 if (PointeeRD) {
3187 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003188 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003189 PDiag(diag::err_access_dtor) << PointeeElem);
3190 }
3191 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003192 }
3193
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003194 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003195 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3196 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003197 AnalyzeDeleteExprMismatch(Result);
3198 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003199}
3200
Nico Weber5a9259c2016-01-15 21:45:31 +00003201void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3202 bool IsDelete, bool CallCanBeVirtual,
3203 bool WarnOnNonAbstractTypes,
3204 SourceLocation DtorLoc) {
3205 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3206 return;
3207
3208 // C++ [expr.delete]p3:
3209 // In the first alternative (delete object), if the static type of the
3210 // object to be deleted is different from its dynamic type, the static
3211 // type shall be a base class of the dynamic type of the object to be
3212 // deleted and the static type shall have a virtual destructor or the
3213 // behavior is undefined.
3214 //
3215 const CXXRecordDecl *PointeeRD = dtor->getParent();
3216 // Note: a final class cannot be derived from, no issue there
3217 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3218 return;
3219
3220 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3221 if (PointeeRD->isAbstract()) {
3222 // If the class is abstract, we warn by default, because we're
3223 // sure the code has undefined behavior.
3224 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3225 << ClassType;
3226 } else if (WarnOnNonAbstractTypes) {
3227 // Otherwise, if this is not an array delete, it's a bit suspect,
3228 // but not necessarily wrong.
3229 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3230 << ClassType;
3231 }
3232 if (!IsDelete) {
3233 std::string TypeStr;
3234 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3235 Diag(DtorLoc, diag::note_delete_non_virtual)
3236 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3237 }
3238}
3239
Richard Smith03a4aa32016-06-23 19:02:52 +00003240Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3241 SourceLocation StmtLoc,
3242 ConditionKind CK) {
3243 ExprResult E =
3244 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3245 if (E.isInvalid())
3246 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003247 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3248 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003249}
3250
Douglas Gregor633caca2009-11-23 23:44:04 +00003251/// \brief Check the use of the given variable as a C++ condition in an if,
3252/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003253ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003254 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003255 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003256 if (ConditionVar->isInvalidDecl())
3257 return ExprError();
3258
Douglas Gregor633caca2009-11-23 23:44:04 +00003259 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260
Douglas Gregor633caca2009-11-23 23:44:04 +00003261 // C++ [stmt.select]p2:
3262 // The declarator shall not specify a function or an array.
3263 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003265 diag::err_invalid_use_of_function_type)
3266 << ConditionVar->getSourceRange());
3267 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003269 diag::err_invalid_use_of_array_type)
3270 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003271
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003272 ExprResult Condition = DeclRefExpr::Create(
3273 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3274 /*enclosing*/ false, ConditionVar->getLocation(),
3275 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003276
Eli Friedmanfa0df832012-02-02 03:46:19 +00003277 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003278
Richard Smith03a4aa32016-06-23 19:02:52 +00003279 switch (CK) {
3280 case ConditionKind::Boolean:
3281 return CheckBooleanCondition(StmtLoc, Condition.get());
3282
Richard Smithb130fe72016-06-23 19:16:49 +00003283 case ConditionKind::ConstexprIf:
3284 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3285
Richard Smith03a4aa32016-06-23 19:02:52 +00003286 case ConditionKind::Switch:
3287 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289
Richard Smith03a4aa32016-06-23 19:02:52 +00003290 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003291}
3292
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003293/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003294ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003295 // C++ 6.4p4:
3296 // The value of a condition that is an initialized declaration in a statement
3297 // other than a switch statement is the value of the declared variable
3298 // implicitly converted to type bool. If that conversion is ill-formed, the
3299 // program is ill-formed.
3300 // The value of a condition that is an expression is the value of the
3301 // expression, implicitly converted to bool.
3302 //
Richard Smithb130fe72016-06-23 19:16:49 +00003303 // FIXME: Return this value to the caller so they don't need to recompute it.
3304 llvm::APSInt Value(/*BitWidth*/1);
3305 return (IsConstexpr && !CondExpr->isValueDependent())
3306 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3307 CCEK_ConstexprIf)
3308 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003309}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003310
3311/// Helper function to determine whether this is the (deprecated) C++
3312/// conversion from a string literal to a pointer to non-const char or
3313/// non-const wchar_t (for narrow and wide string literals,
3314/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003315bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003316Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3317 // Look inside the implicit cast, if it exists.
3318 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3319 From = Cast->getSubExpr();
3320
3321 // A string literal (2.13.4) that is not a wide string literal can
3322 // be converted to an rvalue of type "pointer to char"; a wide
3323 // string literal can be converted to an rvalue of type "pointer
3324 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003325 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003326 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003327 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003328 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003329 // This conversion is considered only when there is an
3330 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003331 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3332 switch (StrLit->getKind()) {
3333 case StringLiteral::UTF8:
3334 case StringLiteral::UTF16:
3335 case StringLiteral::UTF32:
3336 // We don't allow UTF literals to be implicitly converted
3337 break;
3338 case StringLiteral::Ascii:
3339 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3340 ToPointeeType->getKind() == BuiltinType::Char_S);
3341 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003342 return Context.typesAreCompatible(Context.getWideCharType(),
3343 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003344 }
3345 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003346 }
3347
3348 return false;
3349}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003350
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003351static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003352 SourceLocation CastLoc,
3353 QualType Ty,
3354 CastKind Kind,
3355 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003356 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003357 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003358 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003359 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003360 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003361 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003362 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003363 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Richard Smith72d74052013-07-20 19:41:36 +00003365 if (S.RequireNonAbstractType(CastLoc, Ty,
3366 diag::err_allocation_of_abstract_type))
3367 return ExprError();
3368
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003369 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003370 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371
Richard Smith5179eb72016-06-28 19:03:57 +00003372 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3373 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003374 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003375 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003376
Richard Smithf8adcdc2014-07-17 05:12:35 +00003377 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003378 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003379 ConstructorArgs, HadMultipleCandidates,
3380 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3381 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003382 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003383 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003385 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387
John McCalle3027922010-08-25 11:45:40 +00003388 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003389 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Richard Smithd3f2d322015-02-24 21:16:19 +00003391 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003392 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003393 return ExprError();
3394
Douglas Gregora4253922010-04-16 22:17:36 +00003395 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003396 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3397 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003398 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003399 if (Result.isInvalid())
3400 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003401 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003402 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3403 CK_UserDefinedConversion, Result.get(),
3404 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405
Douglas Gregor668443e2011-01-20 00:18:04 +00003406 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003407 }
3408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409}
Douglas Gregora4253922010-04-16 22:17:36 +00003410
Douglas Gregor5fb53972009-01-14 15:45:31 +00003411/// PerformImplicitConversion - Perform an implicit conversion of the
3412/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003413/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003414/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003415/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003416ExprResult
3417Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003418 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003419 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003420 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003421 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003422 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003423 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3424 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003425 if (Res.isInvalid())
3426 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003427 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003428 break;
John Wiegley01296292011-04-08 18:41:53 +00003429 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003430
Anders Carlsson110b07b2009-09-15 06:28:28 +00003431 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003433 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003434 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003435 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003436 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003437 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003438 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Anders Carlsson110b07b2009-09-15 06:28:28 +00003440 // If the user-defined conversion is specified by a conversion function,
3441 // the initial standard conversion sequence converts the source type to
3442 // the implicit object parameter of the conversion function.
3443 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003444 } else {
3445 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003446 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003447 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003448 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003450 // initial standard conversion sequence converts the source type to
3451 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003452 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454 }
Richard Smith72d74052013-07-20 19:41:36 +00003455 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003456 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003457 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003458 PerformImplicitConversion(From, BeforeToType,
3459 ICS.UserDefined.Before, AA_Converting,
3460 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003461 if (Res.isInvalid())
3462 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003463 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
3466 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003467 = BuildCXXCastArgument(*this,
3468 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003469 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003470 CastKind, cast<CXXMethodDecl>(FD),
3471 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003472 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003473 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003474
3475 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003476 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003477
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003478 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003479
Richard Smith507840d2011-11-29 22:48:16 +00003480 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3481 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003482 }
John McCall0d1da222010-01-12 00:44:57 +00003483
3484 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003485 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003486 PDiag(diag::err_typecheck_ambiguous_condition)
3487 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003488 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregor39c16d42008-10-24 04:54:22 +00003490 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003491 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003492
3493 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003494 bool Diagnosed =
3495 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3496 From->getType(), From, Action);
3497 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003498 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003499 }
3500
3501 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003502 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003503}
3504
Richard Smith507840d2011-11-29 22:48:16 +00003505/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003506/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003507/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003508/// expression. Flavor is the context in which we're performing this
3509/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003510ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003511Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003512 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003513 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003514 CheckedConversionKind CCK) {
3515 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003516
Mike Stump87c57ac2009-05-16 07:39:55 +00003517 // Overall FIXME: we are recomputing too many types here and doing far too
3518 // much extra work. What this means is that we need to keep track of more
3519 // information that is computed when we try the implicit conversion initially,
3520 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003521 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003522
Douglas Gregor2fe98832008-11-03 19:09:14 +00003523 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003524 // FIXME: When can ToType be a reference type?
3525 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003526 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003527 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003528 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003529 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003530 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003531 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003532 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003533 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3534 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003535 ConstructorArgs, /*HadMultipleCandidates*/ false,
3536 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3537 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003538 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003539 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003540 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3541 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003542 From, /*HadMultipleCandidates*/ false,
3543 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3544 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003545 }
3546
Douglas Gregor980fb162010-04-29 18:24:40 +00003547 // Resolve overloaded function references.
3548 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3549 DeclAccessPair Found;
3550 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3551 true, Found);
3552 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003553 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003554
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003555 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003556 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557
Douglas Gregor980fb162010-04-29 18:24:40 +00003558 From = FixOverloadedFunctionReference(From, Found, Fn);
3559 FromType = From->getType();
3560 }
3561
Richard Smitha23ab512013-05-23 00:30:41 +00003562 // If we're converting to an atomic type, first convert to the corresponding
3563 // non-atomic type.
3564 QualType ToAtomicType;
3565 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3566 ToAtomicType = ToType;
3567 ToType = ToAtomic->getValueType();
3568 }
3569
George Burgess IV8d141e02015-12-14 22:00:49 +00003570 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003571 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003572 switch (SCS.First) {
3573 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003574 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3575 FromType = FromAtomic->getValueType().getUnqualifiedType();
3576 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3577 From, /*BasePath=*/nullptr, VK_RValue);
3578 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003579 break;
3580
Eli Friedman946b7b52012-01-24 22:51:26 +00003581 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003582 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003583 ExprResult FromRes = DefaultLvalueConversion(From);
3584 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003585 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003586 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003587 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003588 }
John McCall34376a62010-12-04 03:47:34 +00003589
Douglas Gregor39c16d42008-10-24 04:54:22 +00003590 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003591 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003592 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003593 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003594 break;
3595
3596 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003597 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003598 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003599 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003600 break;
3601
3602 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003603 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003604 }
3605
Richard Smith507840d2011-11-29 22:48:16 +00003606 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003607 switch (SCS.Second) {
3608 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003609 // C++ [except.spec]p5:
3610 // [For] assignment to and initialization of pointers to functions,
3611 // pointers to member functions, and references to functions: the
3612 // target entity shall allow at least the exceptions allowed by the
3613 // source value in the assignment or initialization.
3614 switch (Action) {
3615 case AA_Assigning:
3616 case AA_Initializing:
3617 // Note, function argument passing and returning are initialization.
3618 case AA_Passing:
3619 case AA_Returning:
3620 case AA_Sending:
3621 case AA_Passing_CFAudited:
3622 if (CheckExceptionSpecCompatibility(From, ToType))
3623 return ExprError();
3624 break;
3625
3626 case AA_Casting:
3627 case AA_Converting:
3628 // Casts and implicit conversions are not initialization, so are not
3629 // checked for exception specification mismatches.
3630 break;
3631 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003632 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003633 break;
3634
3635 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003636 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003637 if (ToType->isBooleanType()) {
3638 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3639 SCS.Second == ICK_Integral_Promotion &&
3640 "only enums with fixed underlying type can promote to bool");
3641 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003642 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003643 } else {
3644 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003645 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003646 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003647 break;
3648
3649 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003650 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003651 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003652 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003653 break;
3654
3655 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003656 case ICK_Complex_Conversion: {
3657 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3658 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3659 CastKind CK;
3660 if (FromEl->isRealFloatingType()) {
3661 if (ToEl->isRealFloatingType())
3662 CK = CK_FloatingComplexCast;
3663 else
3664 CK = CK_FloatingComplexToIntegralComplex;
3665 } else if (ToEl->isRealFloatingType()) {
3666 CK = CK_IntegralComplexToFloatingComplex;
3667 } else {
3668 CK = CK_IntegralComplexCast;
3669 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003670 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003671 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003672 break;
John McCall8cb679e2010-11-15 09:13:47 +00003673 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003674
Douglas Gregor39c16d42008-10-24 04:54:22 +00003675 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003676 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003677 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003678 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003679 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003680 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003681 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003682 break;
3683
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003684 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003685 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003686 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003687 break;
3688
John McCall31168b02011-06-15 23:02:42 +00003689 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003690 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003691 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003692 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003693 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003694 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003695 diag::ext_typecheck_convert_incompatible_pointer)
3696 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003697 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003698 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003699 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003700 diag::ext_typecheck_convert_incompatible_pointer)
3701 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003702 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003703
Douglas Gregor33823722011-06-11 01:09:30 +00003704 if (From->getType()->isObjCObjectPointerType() &&
3705 ToType->isObjCObjectPointerType())
3706 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003707 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003708 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003709 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003710 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003711 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003712 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003713 diag::err_arc_weak_unavailable_assign);
3714 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003715 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003716 diag::err_arc_convesion_of_weak_unavailable)
3717 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003718 << From->getSourceRange();
3719 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003720
John McCall8cb679e2010-11-15 09:13:47 +00003721 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003722 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003723 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003724 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003725
3726 // Make sure we extend blocks if necessary.
3727 // FIXME: doing this here is really ugly.
3728 if (Kind == CK_BlockPointerToObjCPointerCast) {
3729 ExprResult E = From;
3730 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003731 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003732 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003733 if (getLangOpts().ObjCAutoRefCount)
3734 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003735 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003736 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003737 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003740 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003741 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003742 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003743 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003744 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003745 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003746 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003747
3748 // We may not have been able to figure out what this member pointer resolved
3749 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003750 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003751 (void)isCompleteType(From->getExprLoc(), From->getType());
3752 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003753 }
David Majnemerd96b9972014-08-08 00:10:39 +00003754
Richard Smith507840d2011-11-29 22:48:16 +00003755 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003756 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003757 break;
3758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003760 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003761 // Perform half-to-boolean conversion via float.
3762 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003763 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003764 FromType = Context.FloatTy;
3765 }
3766
Richard Smith507840d2011-11-29 22:48:16 +00003767 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003768 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003769 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003770 break;
3771
Douglas Gregor88d292c2010-05-13 16:44:06 +00003772 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003773 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003775 ToType.getNonReferenceType(),
3776 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003778 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003779 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003780 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003781
Richard Smith507840d2011-11-29 22:48:16 +00003782 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3783 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003784 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003785 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003786 }
3787
Douglas Gregor46188682010-05-18 22:42:18 +00003788 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003789 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003790 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003791 break;
3792
George Burgess IVdf1ed002016-01-13 01:52:39 +00003793 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003794 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003795 Expr *Elem = prepareVectorSplat(ToType, From).get();
3796 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3797 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003798 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
Douglas Gregor46188682010-05-18 22:42:18 +00003801 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003802 // Case 1. x -> _Complex y
3803 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3804 QualType ElType = ToComplex->getElementType();
3805 bool isFloatingComplex = ElType->isRealFloatingType();
3806
3807 // x -> y
3808 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3809 // do nothing
3810 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003811 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003812 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003813 } else {
3814 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003815 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003816 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003817 }
3818 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003819 From = ImpCastExprToType(From, ToType,
3820 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003821 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003822
3823 // Case 2. _Complex x -> y
3824 } else {
3825 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3826 assert(FromComplex);
3827
3828 QualType ElType = FromComplex->getElementType();
3829 bool isFloatingComplex = ElType->isRealFloatingType();
3830
3831 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003832 From = ImpCastExprToType(From, ElType,
3833 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003834 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003835 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003836
3837 // x -> y
3838 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3839 // do nothing
3840 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003841 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003842 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003843 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003844 } else {
3845 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003846 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003847 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003848 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003849 }
3850 }
Douglas Gregor46188682010-05-18 22:42:18 +00003851 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003852
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003853 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003854 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003855 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003856 break;
3857 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003858
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003859 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003860 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003861 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003862 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3863 if (FromRes.isInvalid())
3864 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003865 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003866 assert ((ConvTy == Sema::Compatible) &&
3867 "Improper transparent union conversion");
3868 (void)ConvTy;
3869 break;
3870 }
3871
Guy Benyei259f9f42013-02-07 16:05:33 +00003872 case ICK_Zero_Event_Conversion:
3873 From = ImpCastExprToType(From, ToType,
3874 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003875 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003876 break;
3877
Egor Churaev89831422016-12-23 14:55:49 +00003878 case ICK_Zero_Queue_Conversion:
3879 From = ImpCastExprToType(From, ToType,
3880 CK_ZeroToOCLQueue,
3881 From->getValueKind()).get();
3882 break;
3883
Douglas Gregor46188682010-05-18 22:42:18 +00003884 case ICK_Lvalue_To_Rvalue:
3885 case ICK_Array_To_Pointer:
3886 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003887 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003888 case ICK_Qualification:
3889 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003890 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003891 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003892 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003893 }
3894
3895 switch (SCS.Third) {
3896 case ICK_Identity:
3897 // Nothing to do.
3898 break;
3899
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003900 case ICK_Function_Conversion:
3901 // If both sides are functions (or pointers/references to them), there could
3902 // be incompatible exception declarations.
3903 if (CheckExceptionSpecCompatibility(From, ToType))
3904 return ExprError();
3905
3906 From = ImpCastExprToType(From, ToType, CK_NoOp,
3907 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3908 break;
3909
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003910 case ICK_Qualification: {
3911 // The qualification keeps the category of the inner expression, unless the
3912 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003913 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003914 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003915 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003916 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003917
Douglas Gregore981bb02011-03-14 16:13:32 +00003918 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003919 !getLangOpts().WritableStrings) {
3920 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3921 ? diag::ext_deprecated_string_literal_conversion
3922 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003923 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003924 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003925
Douglas Gregor39c16d42008-10-24 04:54:22 +00003926 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003927 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003928
Douglas Gregor39c16d42008-10-24 04:54:22 +00003929 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003930 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003931 }
3932
Douglas Gregor298f43d2012-04-12 20:42:30 +00003933 // If this conversion sequence involved a scalar -> atomic conversion, perform
3934 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003935 if (!ToAtomicType.isNull()) {
3936 assert(Context.hasSameType(
3937 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3938 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003939 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003940 }
3941
George Burgess IV8d141e02015-12-14 22:00:49 +00003942 // If this conversion sequence succeeded and involved implicitly converting a
3943 // _Nullable type to a _Nonnull one, complain.
3944 if (CCK == CCK_ImplicitConversion)
3945 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3946 From->getLocStart());
3947
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003948 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003949}
3950
Chandler Carruth8e172c62011-05-01 06:51:22 +00003951/// \brief Check the completeness of a type in a unary type trait.
3952///
3953/// If the particular type trait requires a complete type, tries to complete
3954/// it. If completing the type fails, a diagnostic is emitted and false
3955/// returned. If completing the type succeeds or no completion was required,
3956/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003957static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003958 SourceLocation Loc,
3959 QualType ArgTy) {
3960 // C++0x [meta.unary.prop]p3:
3961 // For all of the class templates X declared in this Clause, instantiating
3962 // that template with a template argument that is a class template
3963 // specialization may result in the implicit instantiation of the template
3964 // argument if and only if the semantics of X require that the argument
3965 // must be a complete type.
3966 // We apply this rule to all the type trait expressions used to implement
3967 // these class templates. We also try to follow any GCC documented behavior
3968 // in these expressions to ensure portability of standard libraries.
3969 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003970 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003971 // is_complete_type somewhat obviously cannot require a complete type.
3972 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003973 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003974
3975 // These traits are modeled on the type predicates in C++0x
3976 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3977 // requiring a complete type, as whether or not they return true cannot be
3978 // impacted by the completeness of the type.
3979 case UTT_IsVoid:
3980 case UTT_IsIntegral:
3981 case UTT_IsFloatingPoint:
3982 case UTT_IsArray:
3983 case UTT_IsPointer:
3984 case UTT_IsLvalueReference:
3985 case UTT_IsRvalueReference:
3986 case UTT_IsMemberFunctionPointer:
3987 case UTT_IsMemberObjectPointer:
3988 case UTT_IsEnum:
3989 case UTT_IsUnion:
3990 case UTT_IsClass:
3991 case UTT_IsFunction:
3992 case UTT_IsReference:
3993 case UTT_IsArithmetic:
3994 case UTT_IsFundamental:
3995 case UTT_IsObject:
3996 case UTT_IsScalar:
3997 case UTT_IsCompound:
3998 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003999 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004000
4001 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4002 // which requires some of its traits to have the complete type. However,
4003 // the completeness of the type cannot impact these traits' semantics, and
4004 // so they don't require it. This matches the comments on these traits in
4005 // Table 49.
4006 case UTT_IsConst:
4007 case UTT_IsVolatile:
4008 case UTT_IsSigned:
4009 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004010
4011 // This type trait always returns false, checking the type is moot.
4012 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004013 return true;
4014
David Majnemer213bea32015-11-16 06:58:51 +00004015 // C++14 [meta.unary.prop]:
4016 // If T is a non-union class type, T shall be a complete type.
4017 case UTT_IsEmpty:
4018 case UTT_IsPolymorphic:
4019 case UTT_IsAbstract:
4020 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4021 if (!RD->isUnion())
4022 return !S.RequireCompleteType(
4023 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4024 return true;
4025
4026 // C++14 [meta.unary.prop]:
4027 // If T is a class type, T shall be a complete type.
4028 case UTT_IsFinal:
4029 case UTT_IsSealed:
4030 if (ArgTy->getAsCXXRecordDecl())
4031 return !S.RequireCompleteType(
4032 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4033 return true;
4034
4035 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4036 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004037 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004038 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004039 case UTT_IsStandardLayout:
4040 case UTT_IsPOD:
4041 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004042
Alp Toker73287bf2014-01-20 00:24:09 +00004043 case UTT_IsDestructible:
4044 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004045 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004046
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004047 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004048 // [meta.unary.prop] despite not being named the same. They are specified
4049 // by both GCC and the Embarcadero C++ compiler, and require the complete
4050 // type due to the overarching C++0x type predicates being implemented
4051 // requiring the complete type.
4052 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004053 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004054 case UTT_HasNothrowConstructor:
4055 case UTT_HasNothrowCopy:
4056 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004057 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004058 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004059 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004060 case UTT_HasTrivialCopy:
4061 case UTT_HasTrivialDestructor:
4062 case UTT_HasVirtualDestructor:
4063 // Arrays of unknown bound are expressly allowed.
4064 QualType ElTy = ArgTy;
4065 if (ArgTy->isIncompleteArrayType())
4066 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4067
4068 // The void type is expressly allowed.
4069 if (ElTy->isVoidType())
4070 return true;
4071
4072 return !S.RequireCompleteType(
4073 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004074 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004075}
4076
Joao Matosc9523d42013-03-27 01:34:16 +00004077static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4078 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004079 bool (CXXRecordDecl::*HasTrivial)() const,
4080 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004081 bool (CXXMethodDecl::*IsDesiredOp)() const)
4082{
4083 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4084 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4085 return true;
4086
4087 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4088 DeclarationNameInfo NameInfo(Name, KeyLoc);
4089 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4090 if (Self.LookupQualifiedName(Res, RD)) {
4091 bool FoundOperator = false;
4092 Res.suppressDiagnostics();
4093 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4094 Op != OpEnd; ++Op) {
4095 if (isa<FunctionTemplateDecl>(*Op))
4096 continue;
4097
4098 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4099 if((Operator->*IsDesiredOp)()) {
4100 FoundOperator = true;
4101 const FunctionProtoType *CPT =
4102 Operator->getType()->getAs<FunctionProtoType>();
4103 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004104 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004105 return false;
4106 }
4107 }
4108 return FoundOperator;
4109 }
4110 return false;
4111}
4112
Alp Toker95e7ff22014-01-01 05:57:51 +00004113static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004114 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004115 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004116
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004117 ASTContext &C = Self.Context;
4118 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004119 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004120 // Type trait expressions corresponding to the primary type category
4121 // predicates in C++0x [meta.unary.cat].
4122 case UTT_IsVoid:
4123 return T->isVoidType();
4124 case UTT_IsIntegral:
4125 return T->isIntegralType(C);
4126 case UTT_IsFloatingPoint:
4127 return T->isFloatingType();
4128 case UTT_IsArray:
4129 return T->isArrayType();
4130 case UTT_IsPointer:
4131 return T->isPointerType();
4132 case UTT_IsLvalueReference:
4133 return T->isLValueReferenceType();
4134 case UTT_IsRvalueReference:
4135 return T->isRValueReferenceType();
4136 case UTT_IsMemberFunctionPointer:
4137 return T->isMemberFunctionPointerType();
4138 case UTT_IsMemberObjectPointer:
4139 return T->isMemberDataPointerType();
4140 case UTT_IsEnum:
4141 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004142 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004143 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004144 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004145 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004146 case UTT_IsFunction:
4147 return T->isFunctionType();
4148
4149 // Type trait expressions which correspond to the convenient composition
4150 // predicates in C++0x [meta.unary.comp].
4151 case UTT_IsReference:
4152 return T->isReferenceType();
4153 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004154 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004155 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004156 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004157 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004158 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004159 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004160 // Note: semantic analysis depends on Objective-C lifetime types to be
4161 // considered scalar types. However, such types do not actually behave
4162 // like scalar types at run time (since they may require retain/release
4163 // operations), so we report them as non-scalar.
4164 if (T->isObjCLifetimeType()) {
4165 switch (T.getObjCLifetime()) {
4166 case Qualifiers::OCL_None:
4167 case Qualifiers::OCL_ExplicitNone:
4168 return true;
4169
4170 case Qualifiers::OCL_Strong:
4171 case Qualifiers::OCL_Weak:
4172 case Qualifiers::OCL_Autoreleasing:
4173 return false;
4174 }
4175 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004176
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004177 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004178 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004179 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004180 case UTT_IsMemberPointer:
4181 return T->isMemberPointerType();
4182
4183 // Type trait expressions which correspond to the type property predicates
4184 // in C++0x [meta.unary.prop].
4185 case UTT_IsConst:
4186 return T.isConstQualified();
4187 case UTT_IsVolatile:
4188 return T.isVolatileQualified();
4189 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004190 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004191 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004192 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004193 case UTT_IsStandardLayout:
4194 return T->isStandardLayoutType();
4195 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004196 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004197 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004198 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004199 case UTT_IsEmpty:
4200 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4201 return !RD->isUnion() && RD->isEmpty();
4202 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004203 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004204 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004205 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004206 return false;
4207 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004208 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004209 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004210 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004211 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4212 // even then only when it is used with the 'interface struct ...' syntax
4213 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004214 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004215 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004216 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004217 case UTT_IsSealed:
4218 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004219 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004220 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004221 case UTT_IsSigned:
4222 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004223 case UTT_IsUnsigned:
4224 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004225
4226 // Type trait expressions which query classes regarding their construction,
4227 // destruction, and copying. Rather than being based directly on the
4228 // related type predicates in the standard, they are specified by both
4229 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4230 // specifications.
4231 //
4232 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4233 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004234 //
4235 // Note that these builtins do not behave as documented in g++: if a class
4236 // has both a trivial and a non-trivial special member of a particular kind,
4237 // they return false! For now, we emulate this behavior.
4238 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4239 // does not correctly compute triviality in the presence of multiple special
4240 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004241 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004242 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4243 // If __is_pod (type) is true then the trait is true, else if type is
4244 // a cv class or union type (or array thereof) with a trivial default
4245 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004246 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004247 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004248 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4249 return RD->hasTrivialDefaultConstructor() &&
4250 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004251 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004252 case UTT_HasTrivialMoveConstructor:
4253 // This trait is implemented by MSVC 2012 and needed to parse the
4254 // standard library headers. Specifically this is used as the logic
4255 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004256 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004257 return true;
4258 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4259 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4260 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004261 case UTT_HasTrivialCopy:
4262 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4263 // If __is_pod (type) is true or type is a reference type then
4264 // the trait is true, else if type is a cv class or union type
4265 // with a trivial copy constructor ([class.copy]) then the trait
4266 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004267 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004268 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004269 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4270 return RD->hasTrivialCopyConstructor() &&
4271 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004272 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004273 case UTT_HasTrivialMoveAssign:
4274 // This trait is implemented by MSVC 2012 and needed to parse the
4275 // standard library headers. Specifically it is used as the logic
4276 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004277 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004278 return true;
4279 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4280 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4281 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004282 case UTT_HasTrivialAssign:
4283 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4284 // If type is const qualified or is a reference type then the
4285 // trait is false. Otherwise if __is_pod (type) is true then the
4286 // trait is true, else if type is a cv class or union type with
4287 // a trivial copy assignment ([class.copy]) then the trait is
4288 // true, else it is false.
4289 // Note: the const and reference restrictions are interesting,
4290 // given that const and reference members don't prevent a class
4291 // from having a trivial copy assignment operator (but do cause
4292 // errors if the copy assignment operator is actually used, q.v.
4293 // [class.copy]p12).
4294
Richard Smith92f241f2012-12-08 02:53:02 +00004295 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004296 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004297 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004298 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004299 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4300 return RD->hasTrivialCopyAssignment() &&
4301 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004302 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004303 case UTT_IsDestructible:
4304 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004305 // C++14 [meta.unary.prop]:
4306 // For reference types, is_destructible<T>::value is true.
4307 if (T->isReferenceType())
4308 return true;
4309
4310 // Objective-C++ ARC: autorelease types don't require destruction.
4311 if (T->isObjCLifetimeType() &&
4312 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4313 return true;
4314
4315 // C++14 [meta.unary.prop]:
4316 // For incomplete types and function types, is_destructible<T>::value is
4317 // false.
4318 if (T->isIncompleteType() || T->isFunctionType())
4319 return false;
4320
4321 // C++14 [meta.unary.prop]:
4322 // For object types and given U equal to remove_all_extents_t<T>, if the
4323 // expression std::declval<U&>().~U() is well-formed when treated as an
4324 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4325 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4326 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4327 if (!Destructor)
4328 return false;
4329 // C++14 [dcl.fct.def.delete]p2:
4330 // A program that refers to a deleted function implicitly or
4331 // explicitly, other than to declare it, is ill-formed.
4332 if (Destructor->isDeleted())
4333 return false;
4334 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4335 return false;
4336 if (UTT == UTT_IsNothrowDestructible) {
4337 const FunctionProtoType *CPT =
4338 Destructor->getType()->getAs<FunctionProtoType>();
4339 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4340 if (!CPT || !CPT->isNothrow(C))
4341 return false;
4342 }
4343 }
4344 return true;
4345
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004346 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004347 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004348 // If __is_pod (type) is true or type is a reference type
4349 // then the trait is true, else if type is a cv class or union
4350 // type (or array thereof) with a trivial destructor
4351 // ([class.dtor]) then the trait is true, else it is
4352 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004353 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004354 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004355
John McCall31168b02011-06-15 23:02:42 +00004356 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004357 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004358 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4359 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004360
Richard Smith92f241f2012-12-08 02:53:02 +00004361 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4362 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004363 return false;
4364 // TODO: Propagate nothrowness for implicitly declared special members.
4365 case UTT_HasNothrowAssign:
4366 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4367 // If type is const qualified or is a reference type then the
4368 // trait is false. Otherwise if __has_trivial_assign (type)
4369 // is true then the trait is true, else if type is a cv class
4370 // or union type with copy assignment operators that are known
4371 // not to throw an exception then the trait is true, else it is
4372 // false.
4373 if (C.getBaseElementType(T).isConstQualified())
4374 return false;
4375 if (T->isReferenceType())
4376 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004377 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004378 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004379
Joao Matosc9523d42013-03-27 01:34:16 +00004380 if (const RecordType *RT = T->getAs<RecordType>())
4381 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4382 &CXXRecordDecl::hasTrivialCopyAssignment,
4383 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4384 &CXXMethodDecl::isCopyAssignmentOperator);
4385 return false;
4386 case UTT_HasNothrowMoveAssign:
4387 // This trait is implemented by MSVC 2012 and needed to parse the
4388 // standard library headers. Specifically this is used as the logic
4389 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004390 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004391 return true;
4392
4393 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4394 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4395 &CXXRecordDecl::hasTrivialMoveAssignment,
4396 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4397 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004398 return false;
4399 case UTT_HasNothrowCopy:
4400 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4401 // If __has_trivial_copy (type) is true then the trait is true, else
4402 // if type is a cv class or union type with copy constructors that are
4403 // known not to throw an exception then the trait is true, else it is
4404 // false.
John McCall31168b02011-06-15 23:02:42 +00004405 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004406 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004407 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4408 if (RD->hasTrivialCopyConstructor() &&
4409 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004410 return true;
4411
4412 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004413 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004414 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004415 // A template constructor is never a copy constructor.
4416 // FIXME: However, it may actually be selected at the actual overload
4417 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004418 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004419 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004420 // UsingDecl itself is not a constructor
4421 if (isa<UsingDecl>(ND))
4422 continue;
4423 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004424 if (Constructor->isCopyConstructor(FoundTQs)) {
4425 FoundConstructor = true;
4426 const FunctionProtoType *CPT
4427 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004428 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4429 if (!CPT)
4430 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004431 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004432 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004433 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004434 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004435 }
4436 }
4437
Richard Smith938f40b2011-06-11 17:19:42 +00004438 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004439 }
4440 return false;
4441 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004442 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004443 // If __has_trivial_constructor (type) is true then the trait is
4444 // true, else if type is a cv class or union type (or array
4445 // thereof) with a default constructor that is known not to
4446 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004447 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004448 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004449 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4450 if (RD->hasTrivialDefaultConstructor() &&
4451 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004452 return true;
4453
Alp Tokerb4bca412014-01-20 00:23:47 +00004454 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004455 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004456 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004457 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004458 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004459 // UsingDecl itself is not a constructor
4460 if (isa<UsingDecl>(ND))
4461 continue;
4462 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004463 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004464 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004465 const FunctionProtoType *CPT
4466 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004467 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4468 if (!CPT)
4469 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004470 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004471 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004472 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004473 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004474 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004475 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004476 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004477 }
4478 return false;
4479 case UTT_HasVirtualDestructor:
4480 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4481 // If type is a class type with a virtual destructor ([class.dtor])
4482 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004483 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004484 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004485 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004486 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004487
4488 // These type trait expressions are modeled on the specifications for the
4489 // Embarcadero C++0x type trait functions:
4490 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4491 case UTT_IsCompleteType:
4492 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4493 // Returns True if and only if T is a complete type at the point of the
4494 // function call.
4495 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004496 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004497}
Sebastian Redl5822f082009-02-07 20:10:22 +00004498
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004499/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4500/// ARC mode.
4501static bool hasNontrivialObjCLifetime(QualType T) {
4502 switch (T.getObjCLifetime()) {
4503 case Qualifiers::OCL_ExplicitNone:
4504 return false;
4505
4506 case Qualifiers::OCL_Strong:
4507 case Qualifiers::OCL_Weak:
4508 case Qualifiers::OCL_Autoreleasing:
4509 return true;
4510
4511 case Qualifiers::OCL_None:
4512 return T->isObjCLifetimeType();
4513 }
4514
4515 llvm_unreachable("Unknown ObjC lifetime qualifier");
4516}
4517
Alp Tokercbb90342013-12-13 20:49:58 +00004518static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4519 QualType RhsT, SourceLocation KeyLoc);
4520
Douglas Gregor29c42f22012-02-24 07:38:34 +00004521static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4522 ArrayRef<TypeSourceInfo *> Args,
4523 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004524 if (Kind <= UTT_Last)
4525 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4526
Alp Tokercbb90342013-12-13 20:49:58 +00004527 if (Kind <= BTT_Last)
4528 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4529 Args[1]->getType(), RParenLoc);
4530
Douglas Gregor29c42f22012-02-24 07:38:34 +00004531 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004532 case clang::TT_IsConstructible:
4533 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004534 case clang::TT_IsTriviallyConstructible: {
4535 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004536 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004537 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004538 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004539 // definition for is_constructible, as defined below, is known to call
4540 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004541 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004542 // The predicate condition for a template specialization
4543 // is_constructible<T, Args...> shall be satisfied if and only if the
4544 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004545 // variable t:
4546 //
4547 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004548 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004549
4550 // Precondition: T and all types in the parameter pack Args shall be
4551 // complete types, (possibly cv-qualified) void, or arrays of
4552 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004553 for (const auto *TSI : Args) {
4554 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004555 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004556 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004557
Simon Pilgrim75c26882016-09-30 14:25:09 +00004558 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004559 diag::err_incomplete_type_used_in_type_trait_expr))
4560 return false;
4561 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004562
David Majnemer9658ecc2015-11-13 05:32:43 +00004563 // Make sure the first argument is not incomplete nor a function type.
4564 QualType T = Args[0]->getType();
4565 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004566 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004567
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004568 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004569 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004570 if (RD && RD->isAbstract())
4571 return false;
4572
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004573 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4574 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004575 ArgExprs.reserve(Args.size() - 1);
4576 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004577 QualType ArgTy = Args[I]->getType();
4578 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4579 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004580 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004581 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4582 ArgTy.getNonLValueExprType(S.Context),
4583 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004584 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004585 for (Expr &E : OpaqueArgExprs)
4586 ArgExprs.push_back(&E);
4587
Simon Pilgrim75c26882016-09-30 14:25:09 +00004588 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004589 // trap at translation unit scope.
4590 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4591 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4592 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4593 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4594 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4595 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004596 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004597 if (Init.Failed())
4598 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004599
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004600 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004601 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4602 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004603
Alp Toker73287bf2014-01-20 00:24:09 +00004604 if (Kind == clang::TT_IsConstructible)
4605 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004606
Alp Toker73287bf2014-01-20 00:24:09 +00004607 if (Kind == clang::TT_IsNothrowConstructible)
4608 return S.canThrow(Result.get()) == CT_Cannot;
4609
4610 if (Kind == clang::TT_IsTriviallyConstructible) {
4611 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4612 // lifetime, this is a non-trivial construction.
4613 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004614 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004615 return false;
4616
4617 // The initialization succeeded; now make sure there are no non-trivial
4618 // calls.
4619 return !Result.get()->hasNonTrivialCall(S.Context);
4620 }
4621
4622 llvm_unreachable("unhandled type trait");
4623 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004624 }
Alp Tokercbb90342013-12-13 20:49:58 +00004625 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004626 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004627
Douglas Gregor29c42f22012-02-24 07:38:34 +00004628 return false;
4629}
4630
Simon Pilgrim75c26882016-09-30 14:25:09 +00004631ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4632 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004633 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004634 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004635
Alp Toker95e7ff22014-01-01 05:57:51 +00004636 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4637 *this, Kind, KWLoc, Args[0]->getType()))
4638 return ExprError();
4639
Douglas Gregor29c42f22012-02-24 07:38:34 +00004640 bool Dependent = false;
4641 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4642 if (Args[I]->getType()->isDependentType()) {
4643 Dependent = true;
4644 break;
4645 }
4646 }
Alp Tokercbb90342013-12-13 20:49:58 +00004647
4648 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004649 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004650 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4651
4652 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4653 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004654}
4655
Alp Toker88f64e62013-12-13 21:19:30 +00004656ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4657 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004658 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004659 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004660 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004661
Douglas Gregor29c42f22012-02-24 07:38:34 +00004662 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4663 TypeSourceInfo *TInfo;
4664 QualType T = GetTypeFromParser(Args[I], &TInfo);
4665 if (!TInfo)
4666 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004667
4668 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004669 }
Alp Tokercbb90342013-12-13 20:49:58 +00004670
Douglas Gregor29c42f22012-02-24 07:38:34 +00004671 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4672}
4673
Alp Tokercbb90342013-12-13 20:49:58 +00004674static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4675 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004676 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4677 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004678
4679 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004680 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004681 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004682 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004683 // Base and Derived are not unions and name the same class type without
4684 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004685
John McCall388ef532011-01-28 22:02:36 +00004686 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4687 if (!lhsRecord) return false;
4688
4689 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4690 if (!rhsRecord) return false;
4691
4692 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4693 == (lhsRecord == rhsRecord));
4694
4695 if (lhsRecord == rhsRecord)
4696 return !lhsRecord->getDecl()->isUnion();
4697
4698 // C++0x [meta.rel]p2:
4699 // If Base and Derived are class types and are different types
4700 // (ignoring possible cv-qualifiers) then Derived shall be a
4701 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004702 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004703 diag::err_incomplete_type_used_in_type_trait_expr))
4704 return false;
4705
4706 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4707 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4708 }
John Wiegley65497cc2011-04-27 23:09:49 +00004709 case BTT_IsSame:
4710 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004711 case BTT_TypeCompatible:
4712 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4713 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004714 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004715 case BTT_IsConvertibleTo: {
4716 // C++0x [meta.rel]p4:
4717 // Given the following function prototype:
4718 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004719 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004720 // typename add_rvalue_reference<T>::type create();
4721 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004722 // the predicate condition for a template specialization
4723 // is_convertible<From, To> shall be satisfied if and only if
4724 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004725 // well-formed, including any implicit conversions to the return
4726 // type of the function:
4727 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004728 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004729 // return create<From>();
4730 // }
4731 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004732 // Access checking is performed as if in a context unrelated to To and
4733 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004734 // of the return-statement (including conversions to the return type)
4735 // is considered.
4736 //
4737 // We model the initialization as a copy-initialization of a temporary
4738 // of the appropriate type, which for this expression is identical to the
4739 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004740
4741 // Functions aren't allowed to return function or array types.
4742 if (RhsT->isFunctionType() || RhsT->isArrayType())
4743 return false;
4744
4745 // A return statement in a void function must have void type.
4746 if (RhsT->isVoidType())
4747 return LhsT->isVoidType();
4748
4749 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004750 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004751 return false;
4752
4753 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004754 if (LhsT->isObjectType() || LhsT->isFunctionType())
4755 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004756
4757 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004758 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004759 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004760 Expr::getValueKindForType(LhsT));
4761 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004762 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004763 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004764
4765 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004766 // trap at translation unit scope.
4767 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004768 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4769 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004770 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004771 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004772 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004773
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004774 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004775 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4776 }
Alp Toker73287bf2014-01-20 00:24:09 +00004777
David Majnemerb3d96882016-05-23 17:21:55 +00004778 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004779 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004780 case BTT_IsTriviallyAssignable: {
4781 // C++11 [meta.unary.prop]p3:
4782 // is_trivially_assignable is defined as:
4783 // is_assignable<T, U>::value is true and the assignment, as defined by
4784 // is_assignable, is known to call no operation that is not trivial
4785 //
4786 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004787 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004788 // treated as an unevaluated operand (Clause 5).
4789 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004790 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004791 // void, or arrays of unknown bound.
4792 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004793 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004794 diag::err_incomplete_type_used_in_type_trait_expr))
4795 return false;
4796 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004797 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004798 diag::err_incomplete_type_used_in_type_trait_expr))
4799 return false;
4800
4801 // cv void is never assignable.
4802 if (LhsT->isVoidType() || RhsT->isVoidType())
4803 return false;
4804
Simon Pilgrim75c26882016-09-30 14:25:09 +00004805 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004806 // declval<U>().
4807 if (LhsT->isObjectType() || LhsT->isFunctionType())
4808 LhsT = Self.Context.getRValueReferenceType(LhsT);
4809 if (RhsT->isObjectType() || RhsT->isFunctionType())
4810 RhsT = Self.Context.getRValueReferenceType(RhsT);
4811 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4812 Expr::getValueKindForType(LhsT));
4813 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4814 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004815
4816 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004817 // trap at translation unit scope.
4818 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4819 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4820 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004821 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4822 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004823 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4824 return false;
4825
David Majnemerb3d96882016-05-23 17:21:55 +00004826 if (BTT == BTT_IsAssignable)
4827 return true;
4828
Alp Toker73287bf2014-01-20 00:24:09 +00004829 if (BTT == BTT_IsNothrowAssignable)
4830 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004831
Alp Toker73287bf2014-01-20 00:24:09 +00004832 if (BTT == BTT_IsTriviallyAssignable) {
4833 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4834 // lifetime, this is a non-trivial assignment.
4835 if (Self.getLangOpts().ObjCAutoRefCount &&
4836 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4837 return false;
4838
4839 return !Result.get()->hasNonTrivialCall(Self.Context);
4840 }
4841
4842 llvm_unreachable("unhandled type trait");
4843 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004844 }
Alp Tokercbb90342013-12-13 20:49:58 +00004845 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004846 }
4847 llvm_unreachable("Unknown type trait or not implemented");
4848}
4849
John Wiegley6242b6a2011-04-28 00:16:57 +00004850ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4851 SourceLocation KWLoc,
4852 ParsedType Ty,
4853 Expr* DimExpr,
4854 SourceLocation RParen) {
4855 TypeSourceInfo *TSInfo;
4856 QualType T = GetTypeFromParser(Ty, &TSInfo);
4857 if (!TSInfo)
4858 TSInfo = Context.getTrivialTypeSourceInfo(T);
4859
4860 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4861}
4862
4863static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4864 QualType T, Expr *DimExpr,
4865 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004866 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004867
4868 switch(ATT) {
4869 case ATT_ArrayRank:
4870 if (T->isArrayType()) {
4871 unsigned Dim = 0;
4872 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4873 ++Dim;
4874 T = AT->getElementType();
4875 }
4876 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004877 }
John Wiegleyd3522222011-04-28 02:06:46 +00004878 return 0;
4879
John Wiegley6242b6a2011-04-28 00:16:57 +00004880 case ATT_ArrayExtent: {
4881 llvm::APSInt Value;
4882 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004883 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004884 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004885 false).isInvalid())
4886 return 0;
4887 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004888 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4889 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004890 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004891 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004892 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004893
4894 if (T->isArrayType()) {
4895 unsigned D = 0;
4896 bool Matched = false;
4897 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4898 if (Dim == D) {
4899 Matched = true;
4900 break;
4901 }
4902 ++D;
4903 T = AT->getElementType();
4904 }
4905
John Wiegleyd3522222011-04-28 02:06:46 +00004906 if (Matched && T->isArrayType()) {
4907 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4908 return CAT->getSize().getLimitedValue();
4909 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004910 }
John Wiegleyd3522222011-04-28 02:06:46 +00004911 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004912 }
4913 }
4914 llvm_unreachable("Unknown type trait or not implemented");
4915}
4916
4917ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4918 SourceLocation KWLoc,
4919 TypeSourceInfo *TSInfo,
4920 Expr* DimExpr,
4921 SourceLocation RParen) {
4922 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004923
Chandler Carruthc5276e52011-05-01 08:48:21 +00004924 // FIXME: This should likely be tracked as an APInt to remove any host
4925 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004926 uint64_t Value = 0;
4927 if (!T->isDependentType())
4928 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4929
Chandler Carruthc5276e52011-05-01 08:48:21 +00004930 // While the specification for these traits from the Embarcadero C++
4931 // compiler's documentation says the return type is 'unsigned int', Clang
4932 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4933 // compiler, there is no difference. On several other platforms this is an
4934 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004935 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4936 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004937}
4938
John Wiegleyf9f65842011-04-25 06:54:41 +00004939ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004940 SourceLocation KWLoc,
4941 Expr *Queried,
4942 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004943 // If error parsing the expression, ignore.
4944 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004945 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004946
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004947 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004948
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004949 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004950}
4951
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004952static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4953 switch (ET) {
4954 case ET_IsLValueExpr: return E->isLValue();
4955 case ET_IsRValueExpr: return E->isRValue();
4956 }
4957 llvm_unreachable("Expression trait not covered by switch");
4958}
4959
John Wiegleyf9f65842011-04-25 06:54:41 +00004960ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004961 SourceLocation KWLoc,
4962 Expr *Queried,
4963 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004964 if (Queried->isTypeDependent()) {
4965 // Delay type-checking for type-dependent expressions.
4966 } else if (Queried->getType()->isPlaceholderType()) {
4967 ExprResult PE = CheckPlaceholderExpr(Queried);
4968 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004969 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004970 }
4971
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004972 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004973
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004974 return new (Context)
4975 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004976}
4977
Richard Trieu82402a02011-09-15 21:56:47 +00004978QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004979 ExprValueKind &VK,
4980 SourceLocation Loc,
4981 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004982 assert(!LHS.get()->getType()->isPlaceholderType() &&
4983 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004984 "placeholders should have been weeded out by now");
4985
Richard Smith4baaa5a2016-12-03 01:14:32 +00004986 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
4987 // temporary materialization conversion otherwise.
4988 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004989 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00004990 else if (LHS.get()->isRValue())
4991 LHS = TemporaryMaterializationConversion(LHS.get());
4992 if (LHS.isInvalid())
4993 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004994
4995 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004996 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004997 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004998
Sebastian Redl5822f082009-02-07 20:10:22 +00004999 const char *OpSpelling = isIndirect ? "->*" : ".*";
5000 // C++ 5.5p2
5001 // The binary operator .* [p3: ->*] binds its second operand, which shall
5002 // be of type "pointer to member of T" (where T is a completely-defined
5003 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005004 QualType RHSType = RHS.get()->getType();
5005 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005006 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005007 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005008 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005009 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005010 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005011
Sebastian Redl5822f082009-02-07 20:10:22 +00005012 QualType Class(MemPtr->getClass(), 0);
5013
Douglas Gregord07ba342010-10-13 20:41:14 +00005014 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5015 // member pointer points must be completely-defined. However, there is no
5016 // reason for this semantic distinction, and the rule is not enforced by
5017 // other compilers. Therefore, we do not check this property, as it is
5018 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005019
Sebastian Redl5822f082009-02-07 20:10:22 +00005020 // C++ 5.5p2
5021 // [...] to its first operand, which shall be of class T or of a class of
5022 // which T is an unambiguous and accessible base class. [p3: a pointer to
5023 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005024 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005025 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005026 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5027 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005028 else {
5029 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005030 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005031 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005032 return QualType();
5033 }
5034 }
5035
Richard Trieu82402a02011-09-15 21:56:47 +00005036 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005037 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005038 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5039 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005040 return QualType();
5041 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005042
Richard Smith0f59cb32015-12-18 21:45:41 +00005043 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005044 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005045 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005046 return QualType();
5047 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005048
5049 CXXCastPath BasePath;
5050 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5051 SourceRange(LHS.get()->getLocStart(),
5052 RHS.get()->getLocEnd()),
5053 &BasePath))
5054 return QualType();
5055
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005056 // Cast LHS to type of use.
5057 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005058 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005059 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005060 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005061 }
5062
Richard Trieu82402a02011-09-15 21:56:47 +00005063 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005064 // Diagnose use of pointer-to-member type which when used as
5065 // the functional cast in a pointer-to-member expression.
5066 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5067 return QualType();
5068 }
John McCall7decc9e2010-11-18 06:31:45 +00005069
Sebastian Redl5822f082009-02-07 20:10:22 +00005070 // C++ 5.5p2
5071 // The result is an object or a function of the type specified by the
5072 // second operand.
5073 // The cv qualifiers are the union of those in the pointer and the left side,
5074 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005075 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005076 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005077
Douglas Gregor1d042092011-01-26 16:40:18 +00005078 // C++0x [expr.mptr.oper]p6:
5079 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080 // ill-formed if the second operand is a pointer to member function with
5081 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5082 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005083 // is a pointer to member function with ref-qualifier &&.
5084 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5085 switch (Proto->getRefQualifier()) {
5086 case RQ_None:
5087 // Do nothing
5088 break;
5089
5090 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005091 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005092 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005093 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005094 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Douglas Gregor1d042092011-01-26 16:40:18 +00005096 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005097 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005098 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005099 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005100 break;
5101 }
5102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103
John McCall7decc9e2010-11-18 06:31:45 +00005104 // C++ [expr.mptr.oper]p6:
5105 // The result of a .* expression whose second operand is a pointer
5106 // to a data member is of the same value category as its
5107 // first operand. The result of a .* expression whose second
5108 // operand is a pointer to a member function is a prvalue. The
5109 // result of an ->* expression is an lvalue if its second operand
5110 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005111 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005112 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005113 return Context.BoundMemberTy;
5114 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005115 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005116 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005117 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005118 }
John McCall7decc9e2010-11-18 06:31:45 +00005119
Sebastian Redl5822f082009-02-07 20:10:22 +00005120 return Result;
5121}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005122
Richard Smith2414bca2016-04-25 19:30:37 +00005123/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005124///
5125/// This is part of the parameter validation for the ? operator. If either
5126/// value operand is a class type, the two operands are attempted to be
5127/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005128/// It returns true if the program is ill-formed and has already been diagnosed
5129/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005130static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5131 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005132 bool &HaveConversion,
5133 QualType &ToType) {
5134 HaveConversion = false;
5135 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005136
5137 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005138 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005139 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005140 // The process for determining whether an operand expression E1 of type T1
5141 // can be converted to match an operand expression E2 of type T2 is defined
5142 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005143 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5144 // implicitly converted to type "lvalue reference to T2", subject to the
5145 // constraint that in the conversion the reference must bind directly to
5146 // an lvalue.
5147 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5148 // implicitly conveted to the type "rvalue reference to R2", subject to
5149 // the constraint that the reference must bind directly.
5150 if (To->isLValue() || To->isXValue()) {
5151 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5152 : Self.Context.getRValueReferenceType(ToType);
5153
Douglas Gregor838fcc32010-03-26 20:14:36 +00005154 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005156 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005157 if (InitSeq.isDirectReferenceBinding()) {
5158 ToType = T;
5159 HaveConversion = true;
5160 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005162
Douglas Gregor838fcc32010-03-26 20:14:36 +00005163 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005164 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005165 }
John McCall65eb8792010-02-25 01:37:24 +00005166
Sebastian Redl1a99f442009-04-16 17:51:27 +00005167 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5168 // -- if E1 and E2 have class type, and the underlying class types are
5169 // the same or one is a base class of the other:
5170 QualType FTy = From->getType();
5171 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005172 const RecordType *FRec = FTy->getAs<RecordType>();
5173 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005174 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005175 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5176 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5177 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005178 // E1 can be converted to match E2 if the class of T2 is the
5179 // same type as, or a base class of, the class of T1, and
5180 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005181 if (FRec == TRec || FDerivedFromT) {
5182 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005183 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005184 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005185 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005186 HaveConversion = true;
5187 return false;
5188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Douglas Gregor838fcc32010-03-26 20:14:36 +00005190 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005191 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005192 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194
Douglas Gregor838fcc32010-03-26 20:14:36 +00005195 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
Douglas Gregor838fcc32010-03-26 20:14:36 +00005198 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5199 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005201 // an rvalue).
5202 //
5203 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5204 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005205 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Douglas Gregor838fcc32010-03-26 20:14:36 +00005207 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005208 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005209 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005210 ToType = TTy;
5211 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005212 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005213
Sebastian Redl1a99f442009-04-16 17:51:27 +00005214 return false;
5215}
5216
5217/// \brief Try to find a common type for two according to C++0x 5.16p5.
5218///
5219/// This is part of the parameter validation for the ? operator. If either
5220/// value operand is a class type, overload resolution is used to find a
5221/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005222static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005223 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005224 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005225 OverloadCandidateSet CandidateSet(QuestionLoc,
5226 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005227 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005228 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005229
5230 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005231 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005232 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005233 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005234 ExprResult LHSRes =
5235 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5236 Best->Conversions[0], Sema::AA_Converting);
5237 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005238 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005239 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005240
5241 ExprResult RHSRes =
5242 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5243 Best->Conversions[1], Sema::AA_Converting);
5244 if (RHSRes.isInvalid())
5245 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005246 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005247 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005248 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005249 return false;
John Wiegley01296292011-04-08 18:41:53 +00005250 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005251
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005252 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005253
5254 // Emit a better diagnostic if one of the expressions is a null pointer
5255 // constant and the other is a pointer type. In this case, the user most
5256 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005257 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005258 return true;
5259
5260 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005261 << LHS.get()->getType() << RHS.get()->getType()
5262 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005263 return true;
5264
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005265 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005266 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005267 << LHS.get()->getType() << RHS.get()->getType()
5268 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005269 // FIXME: Print the possible common types by printing the return types of
5270 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005271 break;
5272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005274 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005275 }
5276 return true;
5277}
5278
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005279/// \brief Perform an "extended" implicit conversion as returned by
5280/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005281static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005282 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005283 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005284 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005285 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005286 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005287 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005288 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005289 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005290
John Wiegley01296292011-04-08 18:41:53 +00005291 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005292 return false;
5293}
5294
Sebastian Redl1a99f442009-04-16 17:51:27 +00005295/// \brief Check the operands of ?: under C++ semantics.
5296///
5297/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5298/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005299QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5300 ExprResult &RHS, ExprValueKind &VK,
5301 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005302 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005303 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5304 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005305
Richard Smith45edb702012-08-07 22:06:48 +00005306 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005307 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005308 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005309 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005310 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005311 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005312 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005313 }
5314
John McCall7decc9e2010-11-18 06:31:45 +00005315 // Assume r-value.
5316 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005317 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005318
Sebastian Redl1a99f442009-04-16 17:51:27 +00005319 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005320 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005321 return Context.DependentTy;
5322
Richard Smith45edb702012-08-07 22:06:48 +00005323 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005324 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005325 QualType LTy = LHS.get()->getType();
5326 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 bool LVoid = LTy->isVoidType();
5328 bool RVoid = RTy->isVoidType();
5329 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005330 // ... one of the following shall hold:
5331 // -- The second or the third operand (but not both) is a (possibly
5332 // parenthesized) throw-expression; the result is of the type
5333 // and value category of the other.
5334 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5335 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5336 if (LThrow != RThrow) {
5337 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5338 VK = NonThrow->getValueKind();
5339 // DR (no number yet): the result is a bit-field if the
5340 // non-throw-expression operand is a bit-field.
5341 OK = NonThrow->getObjectKind();
5342 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005343 }
5344
Sebastian Redl1a99f442009-04-16 17:51:27 +00005345 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005346 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005347 if (LVoid && RVoid)
5348 return Context.VoidTy;
5349
5350 // Neither holds, error.
5351 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5352 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005353 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005354 return QualType();
5355 }
5356
5357 // Neither is void.
5358
Richard Smithf2b084f2012-08-08 06:13:49 +00005359 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005360 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005361 // either has (cv) class type [...] an attempt is made to convert each of
5362 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005364 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005365 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005366 QualType L2RType, R2LType;
5367 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005368 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005369 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005370 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005371 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372
Sebastian Redl1a99f442009-04-16 17:51:27 +00005373 // If both can be converted, [...] the program is ill-formed.
5374 if (HaveL2R && HaveR2L) {
5375 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005376 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005377 return QualType();
5378 }
5379
5380 // If exactly one conversion is possible, that conversion is applied to
5381 // the chosen operand and the converted operands are used in place of the
5382 // original operands for the remainder of this section.
5383 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005384 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005385 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005386 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005387 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005388 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005389 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005390 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005391 }
5392 }
5393
Richard Smithf2b084f2012-08-08 06:13:49 +00005394 // C++11 [expr.cond]p3
5395 // if both are glvalues of the same value category and the same type except
5396 // for cv-qualification, an attempt is made to convert each of those
5397 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005398 // FIXME:
5399 // Resolving a defect in P0012R1: we extend this to cover all cases where
5400 // one of the operands is reference-compatible with the other, in order
5401 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005402 ExprValueKind LVK = LHS.get()->getValueKind();
5403 ExprValueKind RVK = RHS.get()->getValueKind();
5404 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005405 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005406 // DerivedToBase was already handled by the class-specific case above.
5407 // FIXME: Should we allow ObjC conversions here?
5408 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5409 if (CompareReferenceRelationship(
5410 QuestionLoc, LTy, RTy, DerivedToBase,
5411 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005412 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5413 // [...] subject to the constraint that the reference must bind
5414 // directly [...]
5415 !RHS.get()->refersToBitField() &&
5416 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005417 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005418 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005419 } else if (CompareReferenceRelationship(
5420 QuestionLoc, RTy, LTy, DerivedToBase,
5421 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005422 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5423 !LHS.get()->refersToBitField() &&
5424 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005425 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5426 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005427 }
5428 }
5429
5430 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005431 // If the second and third operands are glvalues of the same value
5432 // category and have the same type, the result is of that type and
5433 // value category and it is a bit-field if the second or the third
5434 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005435 // We only extend this to bitfields, not to the crazy other kinds of
5436 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005437 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005438 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005439 LHS.get()->isOrdinaryOrBitFieldObject() &&
5440 RHS.get()->isOrdinaryOrBitFieldObject()) {
5441 VK = LHS.get()->getValueKind();
5442 if (LHS.get()->getObjectKind() == OK_BitField ||
5443 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005444 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005445
5446 // If we have function pointer types, unify them anyway to unify their
5447 // exception specifications, if any.
5448 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5449 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005450 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005451 /*ConvertArgs*/false);
5452 LTy = Context.getQualifiedType(LTy, Qs);
5453
5454 assert(!LTy.isNull() && "failed to find composite pointer type for "
5455 "canonically equivalent function ptr types");
5456 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5457 }
5458
John McCall7decc9e2010-11-18 06:31:45 +00005459 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005460 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005461
Richard Smithf2b084f2012-08-08 06:13:49 +00005462 // C++11 [expr.cond]p5
5463 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005464 // do not have the same type, and either has (cv) class type, ...
5465 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5466 // ... overload resolution is used to determine the conversions (if any)
5467 // to be applied to the operands. If the overload resolution fails, the
5468 // program is ill-formed.
5469 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5470 return QualType();
5471 }
5472
Richard Smithf2b084f2012-08-08 06:13:49 +00005473 // C++11 [expr.cond]p6
5474 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005475 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005476 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5477 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005478 if (LHS.isInvalid() || RHS.isInvalid())
5479 return QualType();
5480 LTy = LHS.get()->getType();
5481 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005482
5483 // After those conversions, one of the following shall hold:
5484 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005485 // is of that type. If the operands have class type, the result
5486 // is a prvalue temporary of the result type, which is
5487 // copy-initialized from either the second operand or the third
5488 // operand depending on the value of the first operand.
5489 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5490 if (LTy->isRecordType()) {
5491 // The operands have class type. Make a temporary copy.
5492 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005493
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5495 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005496 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005497 if (LHSCopy.isInvalid())
5498 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005499
5500 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5501 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005502 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005503 if (RHSCopy.isInvalid())
5504 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
John Wiegley01296292011-04-08 18:41:53 +00005506 LHS = LHSCopy;
5507 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005508 }
5509
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005510 // If we have function pointer types, unify them anyway to unify their
5511 // exception specifications, if any.
5512 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5513 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5514 assert(!LTy.isNull() && "failed to find composite pointer type for "
5515 "canonically equivalent function ptr types");
5516 }
5517
Sebastian Redl1a99f442009-04-16 17:51:27 +00005518 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005519 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005520
Douglas Gregor46188682010-05-18 22:42:18 +00005521 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005523 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5524 /*AllowBothBool*/true,
5525 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005526
Sebastian Redl1a99f442009-04-16 17:51:27 +00005527 // -- The second and third operands have arithmetic or enumeration type;
5528 // the usual arithmetic conversions are performed to bring them to a
5529 // common type, and the result is of that type.
5530 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005531 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005532 if (LHS.isInvalid() || RHS.isInvalid())
5533 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005534 if (ResTy.isNull()) {
5535 Diag(QuestionLoc,
5536 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5537 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5538 return QualType();
5539 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005540
5541 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5542 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5543
5544 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005545 }
5546
5547 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005548 // type and the other is a null pointer constant, or both are null
5549 // pointer constants, at least one of which is non-integral; pointer
5550 // conversions and qualification conversions are performed to bring them
5551 // to their composite pointer type. The result is of the composite
5552 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005553 // -- The second and third operands have pointer to member type, or one has
5554 // pointer to member type and the other is a null pointer constant;
5555 // pointer to member conversions and qualification conversions are
5556 // performed to bring them to a common type, whose cv-qualification
5557 // shall match the cv-qualification of either the second or the third
5558 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005559 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5560 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005561 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Douglas Gregor697a3912010-04-01 22:47:07 +00005563 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005564 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5565 if (!Composite.isNull())
5566 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005567
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005568 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005569 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005570 return QualType();
5571
Sebastian Redl1a99f442009-04-16 17:51:27 +00005572 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005573 << LHS.get()->getType() << RHS.get()->getType()
5574 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005575 return QualType();
5576}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005577
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005578static FunctionProtoType::ExceptionSpecInfo
5579mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5580 FunctionProtoType::ExceptionSpecInfo ESI2,
5581 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5582 ExceptionSpecificationType EST1 = ESI1.Type;
5583 ExceptionSpecificationType EST2 = ESI2.Type;
5584
5585 // If either of them can throw anything, that is the result.
5586 if (EST1 == EST_None) return ESI1;
5587 if (EST2 == EST_None) return ESI2;
5588 if (EST1 == EST_MSAny) return ESI1;
5589 if (EST2 == EST_MSAny) return ESI2;
5590
5591 // If either of them is non-throwing, the result is the other.
5592 if (EST1 == EST_DynamicNone) return ESI2;
5593 if (EST2 == EST_DynamicNone) return ESI1;
5594 if (EST1 == EST_BasicNoexcept) return ESI2;
5595 if (EST2 == EST_BasicNoexcept) return ESI1;
5596
5597 // If either of them is a non-value-dependent computed noexcept, that
5598 // determines the result.
5599 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5600 !ESI2.NoexceptExpr->isValueDependent())
5601 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5602 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5603 !ESI1.NoexceptExpr->isValueDependent())
5604 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5605 // If we're left with value-dependent computed noexcept expressions, we're
5606 // stuck. Before C++17, we can just drop the exception specification entirely,
5607 // since it's not actually part of the canonical type. And this should never
5608 // happen in C++17, because it would mean we were computing the composite
5609 // pointer type of dependent types, which should never happen.
5610 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5611 assert(!S.getLangOpts().CPlusPlus1z &&
5612 "computing composite pointer type of dependent types");
5613 return FunctionProtoType::ExceptionSpecInfo();
5614 }
5615
5616 // Switch over the possibilities so that people adding new values know to
5617 // update this function.
5618 switch (EST1) {
5619 case EST_None:
5620 case EST_DynamicNone:
5621 case EST_MSAny:
5622 case EST_BasicNoexcept:
5623 case EST_ComputedNoexcept:
5624 llvm_unreachable("handled above");
5625
5626 case EST_Dynamic: {
5627 // This is the fun case: both exception specifications are dynamic. Form
5628 // the union of the two lists.
5629 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5630 llvm::SmallPtrSet<QualType, 8> Found;
5631 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5632 for (QualType E : Exceptions)
5633 if (Found.insert(S.Context.getCanonicalType(E)).second)
5634 ExceptionTypeStorage.push_back(E);
5635
5636 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5637 Result.Exceptions = ExceptionTypeStorage;
5638 return Result;
5639 }
5640
5641 case EST_Unevaluated:
5642 case EST_Uninstantiated:
5643 case EST_Unparsed:
5644 llvm_unreachable("shouldn't see unresolved exception specifications here");
5645 }
5646
5647 llvm_unreachable("invalid ExceptionSpecificationType");
5648}
5649
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005650/// \brief Find a merged pointer type and convert the two expressions to it.
5651///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005652/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005653/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005654/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005655/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005656///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005657/// \param Loc The location of the operator requiring these two expressions to
5658/// be converted to the composite pointer type.
5659///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005660/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005662 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005663 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005664 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005665
5666 // C++1z [expr]p14:
5667 // The composite pointer type of two operands p1 and p2 having types T1
5668 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005669 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005670
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005671 // where at least one is a pointer or pointer to member type or
5672 // std::nullptr_t is:
5673 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5674 T1->isNullPtrType();
5675 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5676 T2->isNullPtrType();
5677 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005678 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005679
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005680 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5681 // This can't actually happen, following the standard, but we also use this
5682 // to implement the end of [expr.conv], which hits this case.
5683 //
5684 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5685 if (T1IsPointerLike &&
5686 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005687 if (ConvertArgs)
5688 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5689 ? CK_NullToMemberPointer
5690 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005691 return T1;
5692 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005693 if (T2IsPointerLike &&
5694 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005695 if (ConvertArgs)
5696 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5697 ? CK_NullToMemberPointer
5698 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005699 return T2;
5700 }
Mike Stump11289f42009-09-09 15:08:12 +00005701
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005702 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005703 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005704 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005705 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5706 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005707
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005708 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5709 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5710 // the union of cv1 and cv2;
5711 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5712 // "pointer to function", where the function types are otherwise the same,
5713 // "pointer to function";
5714 // FIXME: This rule is defective: it should also permit removing noexcept
5715 // from a pointer to member function. As a Clang extension, we also
5716 // permit removing 'noreturn', so we generalize this rule to;
5717 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5718 // "pointer to member function" and the pointee types can be unified
5719 // by a function pointer conversion, that conversion is applied
5720 // before checking the following rules.
5721 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5722 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5723 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5724 // respectively;
5725 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5726 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5727 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5728 // T1 or the cv-combined type of T1 and T2, respectively;
5729 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5730 // T2;
5731 //
5732 // If looked at in the right way, these bullets all do the same thing.
5733 // What we do here is, we build the two possible cv-combined types, and try
5734 // the conversions in both directions. If only one works, or if the two
5735 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005736 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005737 //
5738 // Note that this will fail to find a composite pointer type for "pointer
5739 // to void" and "pointer to function". We can't actually perform the final
5740 // conversion in this case, even though a composite pointer type formally
5741 // exists.
5742 SmallVector<unsigned, 4> QualifierUnion;
5743 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005744 QualType Composite1 = T1;
5745 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005747 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005748 const PointerType *Ptr1, *Ptr2;
5749 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5750 (Ptr2 = Composite2->getAs<PointerType>())) {
5751 Composite1 = Ptr1->getPointeeType();
5752 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005754 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005755 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005756 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005757 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005758
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005759 QualifierUnion.push_back(
5760 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005761 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005762 continue;
5763 }
Mike Stump11289f42009-09-09 15:08:12 +00005764
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005765 const MemberPointerType *MemPtr1, *MemPtr2;
5766 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5767 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5768 Composite1 = MemPtr1->getPointeeType();
5769 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005771 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005773 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005774 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005776 QualifierUnion.push_back(
5777 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5778 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5779 MemPtr2->getClass()));
5780 continue;
5781 }
Mike Stump11289f42009-09-09 15:08:12 +00005782
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005783 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005784
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005785 // Cannot unwrap any more types.
5786 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005787 }
Mike Stump11289f42009-09-09 15:08:12 +00005788
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005789 // Apply the function pointer conversion to unify the types. We've already
5790 // unwrapped down to the function types, and we want to merge rather than
5791 // just convert, so do this ourselves rather than calling
5792 // IsFunctionConversion.
5793 //
5794 // FIXME: In order to match the standard wording as closely as possible, we
5795 // currently only do this under a single level of pointers. Ideally, we would
5796 // allow this in general, and set NeedConstBefore to the relevant depth on
5797 // the side(s) where we changed anything.
5798 if (QualifierUnion.size() == 1) {
5799 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5800 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5801 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5802 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5803
5804 // The result is noreturn if both operands are.
5805 bool Noreturn =
5806 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5807 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5808 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5809
5810 // The result is nothrow if both operands are.
5811 SmallVector<QualType, 8> ExceptionTypeStorage;
5812 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5813 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5814 ExceptionTypeStorage);
5815
5816 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5817 FPT1->getParamTypes(), EPI1);
5818 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5819 FPT2->getParamTypes(), EPI2);
5820 }
5821 }
5822 }
5823
Richard Smith5e9746f2016-10-21 22:00:42 +00005824 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005825 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005826 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005827 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005828 for (unsigned I = 0; I != NeedConstBefore; ++I)
5829 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005830 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005832
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005833 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005834 auto MOC = MemberOfClass.rbegin();
5835 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5836 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5837 auto Classes = *MOC++;
5838 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005839 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005840 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005841 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005842 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005843 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005844 } else {
5845 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005846 Composite1 =
5847 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5848 Composite2 =
5849 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005850 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005851 }
5852
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005853 struct Conversion {
5854 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005855 Expr *&E1, *&E2;
5856 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005857 InitializedEntity Entity;
5858 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005859 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005860 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005861
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005862 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5863 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005864 : S(S), E1(E1), E2(E2), Composite(Composite),
5865 Entity(InitializedEntity::InitializeTemporary(Composite)),
5866 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5867 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5868 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005869
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005870 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005871 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5872 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005873 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005874 E1 = E1Result.getAs<Expr>();
5875
5876 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5877 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005878 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005879 E2 = E2Result.getAs<Expr>();
5880
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005881 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005882 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005883 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005884
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005885 // Try to convert to each composite pointer type.
5886 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005887 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5888 if (ConvertArgs && C1.perform())
5889 return QualType();
5890 return C1.Composite;
5891 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005892 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005893
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005894 if (C1.Viable == C2.Viable) {
5895 // Either Composite1 and Composite2 are viable and are different, or
5896 // neither is viable.
5897 // FIXME: How both be viable and different?
5898 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005899 }
5900
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005901 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005902 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5903 return QualType();
5904
5905 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005906}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005907
John McCalldadc5752010-08-24 06:29:42 +00005908ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005909 if (!E)
5910 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005911
John McCall31168b02011-06-15 23:02:42 +00005912 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5913
5914 // If the result is a glvalue, we shouldn't bind it.
5915 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005916 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005917
John McCall31168b02011-06-15 23:02:42 +00005918 // In ARC, calls that return a retainable type can return retained,
5919 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005920 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005921 E->getType()->isObjCRetainableType()) {
5922
5923 bool ReturnsRetained;
5924
5925 // For actual calls, we compute this by examining the type of the
5926 // called value.
5927 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5928 Expr *Callee = Call->getCallee()->IgnoreParens();
5929 QualType T = Callee->getType();
5930
5931 if (T == Context.BoundMemberTy) {
5932 // Handle pointer-to-members.
5933 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5934 T = BinOp->getRHS()->getType();
5935 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5936 T = Mem->getMemberDecl()->getType();
5937 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005938
John McCall31168b02011-06-15 23:02:42 +00005939 if (const PointerType *Ptr = T->getAs<PointerType>())
5940 T = Ptr->getPointeeType();
5941 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5942 T = Ptr->getPointeeType();
5943 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5944 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005945
John McCall31168b02011-06-15 23:02:42 +00005946 const FunctionType *FTy = T->getAs<FunctionType>();
5947 assert(FTy && "call to value not of function type?");
5948 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5949
5950 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5951 // type always produce a +1 object.
5952 } else if (isa<StmtExpr>(E)) {
5953 ReturnsRetained = true;
5954
Ted Kremeneke65b0862012-03-06 20:05:56 +00005955 // We hit this case with the lambda conversion-to-block optimization;
5956 // we don't want any extra casts here.
5957 } else if (isa<CastExpr>(E) &&
5958 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005959 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005960
John McCall31168b02011-06-15 23:02:42 +00005961 // For message sends and property references, we try to find an
5962 // actual method. FIXME: we should infer retention by selector in
5963 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005964 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005965 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005966 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5967 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005968 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5969 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005970 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5971 D = ArrayLit->getArrayWithObjectsMethod();
5972 } else if (ObjCDictionaryLiteral *DictLit
5973 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5974 D = DictLit->getDictWithObjectsMethod();
5975 }
John McCall31168b02011-06-15 23:02:42 +00005976
5977 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005978
5979 // Don't do reclaims on performSelector calls; despite their
5980 // return type, the invoked method doesn't necessarily actually
5981 // return an object.
5982 if (!ReturnsRetained &&
5983 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005984 return E;
John McCall31168b02011-06-15 23:02:42 +00005985 }
5986
John McCall16de4d22011-11-14 19:53:16 +00005987 // Don't reclaim an object of Class type.
5988 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005989 return E;
John McCall16de4d22011-11-14 19:53:16 +00005990
Tim Shen4a05bb82016-06-21 20:29:17 +00005991 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00005992
John McCall2d637d22011-09-10 06:18:15 +00005993 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5994 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005995 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5996 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00005997 }
5998
David Blaikiebbafb8a2012-03-11 07:00:24 +00005999 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006000 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006001
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006002 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6003 // a fast path for the common case that the type is directly a RecordType.
6004 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006005 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006006 while (!RT) {
6007 switch (T->getTypeClass()) {
6008 case Type::Record:
6009 RT = cast<RecordType>(T);
6010 break;
6011 case Type::ConstantArray:
6012 case Type::IncompleteArray:
6013 case Type::VariableArray:
6014 case Type::DependentSizedArray:
6015 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6016 break;
6017 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006018 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006019 }
6020 }
Mike Stump11289f42009-09-09 15:08:12 +00006021
Richard Smithfd555f62012-02-22 02:04:18 +00006022 // That should be enough to guarantee that this type is complete, if we're
6023 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006024 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006025 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006026 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006027
6028 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006029 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006030
John McCall31168b02011-06-15 23:02:42 +00006031 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006032 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006033 CheckDestructorAccess(E->getExprLoc(), Destructor,
6034 PDiag(diag::err_access_dtor_temp)
6035 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006036 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6037 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006038
Richard Smithfd555f62012-02-22 02:04:18 +00006039 // If destructor is trivial, we can avoid the extra copy.
6040 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006041 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006042
John McCall28fc7092011-11-10 05:35:25 +00006043 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006044 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006045 }
Richard Smitheec915d62012-02-18 04:13:32 +00006046
6047 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006048 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6049
6050 if (IsDecltype)
6051 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6052
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006053 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006054}
6055
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056ExprResult
John McCall5d413782010-12-06 08:20:24 +00006057Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006058 if (SubExpr.isInvalid())
6059 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006060
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006061 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006062}
6063
John McCall28fc7092011-11-10 05:35:25 +00006064Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006065 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006066
Eli Friedman3bda6b12012-02-02 23:15:15 +00006067 CleanupVarDeclMarking();
6068
John McCall28fc7092011-11-10 05:35:25 +00006069 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6070 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006071 assert(Cleanup.exprNeedsCleanups() ||
6072 ExprCleanupObjects.size() == FirstCleanup);
6073 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006074 return SubExpr;
6075
Craig Topper5fc8fc22014-08-27 06:28:36 +00006076 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6077 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006078
Tim Shen4a05bb82016-06-21 20:29:17 +00006079 auto *E = ExprWithCleanups::Create(
6080 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006081 DiscardCleanupsInEvaluationContext();
6082
6083 return E;
6084}
6085
John McCall5d413782010-12-06 08:20:24 +00006086Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006087 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006088
Eli Friedman3bda6b12012-02-02 23:15:15 +00006089 CleanupVarDeclMarking();
6090
Tim Shen4a05bb82016-06-21 20:29:17 +00006091 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006092 return SubStmt;
6093
6094 // FIXME: In order to attach the temporaries, wrap the statement into
6095 // a StmtExpr; currently this is only used for asm statements.
6096 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6097 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006098 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006099 SourceLocation(),
6100 SourceLocation());
6101 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6102 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006103 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006104}
6105
Richard Smithfd555f62012-02-22 02:04:18 +00006106/// Process the expression contained within a decltype. For such expressions,
6107/// certain semantic checks on temporaries are delayed until this point, and
6108/// are omitted for the 'topmost' call in the decltype expression. If the
6109/// topmost call bound a temporary, strip that temporary off the expression.
6110ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006111 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006112
6113 // C++11 [expr.call]p11:
6114 // If a function call is a prvalue of object type,
6115 // -- if the function call is either
6116 // -- the operand of a decltype-specifier, or
6117 // -- the right operand of a comma operator that is the operand of a
6118 // decltype-specifier,
6119 // a temporary object is not introduced for the prvalue.
6120
6121 // Recursively rebuild ParenExprs and comma expressions to strip out the
6122 // outermost CXXBindTemporaryExpr, if any.
6123 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6124 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6125 if (SubExpr.isInvalid())
6126 return ExprError();
6127 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006128 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006129 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006130 }
6131 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6132 if (BO->getOpcode() == BO_Comma) {
6133 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6134 if (RHS.isInvalid())
6135 return ExprError();
6136 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006137 return E;
6138 return new (Context) BinaryOperator(
6139 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6140 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00006141 }
6142 }
6143
6144 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006145 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6146 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006147 if (TopCall)
6148 E = TopCall;
6149 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006150 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006151
6152 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006153 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006154
Richard Smithf86b0ae2012-07-28 19:54:11 +00006155 // In MS mode, don't perform any extra checking of call return types within a
6156 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006157 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006158 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006159
Richard Smithfd555f62012-02-22 02:04:18 +00006160 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006161 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6162 I != N; ++I) {
6163 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006164 if (Call == TopCall)
6165 continue;
6166
David Majnemerced8bdf2015-02-25 17:36:15 +00006167 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006168 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006169 Call, Call->getDirectCallee()))
6170 return ExprError();
6171 }
6172
6173 // Now all relevant types are complete, check the destructors are accessible
6174 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006175 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6176 I != N; ++I) {
6177 CXXBindTemporaryExpr *Bind =
6178 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006179 if (Bind == TopBind)
6180 continue;
6181
6182 CXXTemporary *Temp = Bind->getTemporary();
6183
6184 CXXRecordDecl *RD =
6185 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6186 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6187 Temp->setDestructor(Destructor);
6188
Richard Smith7d847b12012-05-11 22:20:10 +00006189 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6190 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006191 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006192 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006193 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6194 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006195
6196 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006197 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006198 }
6199
6200 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006201 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006202}
6203
Richard Smith79c927b2013-11-06 19:31:51 +00006204/// Note a set of 'operator->' functions that were used for a member access.
6205static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006206 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006207 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6208 // FIXME: Make this configurable?
6209 unsigned Limit = 9;
6210 if (OperatorArrows.size() > Limit) {
6211 // Produce Limit-1 normal notes and one 'skipping' note.
6212 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6213 SkipCount = OperatorArrows.size() - (Limit - 1);
6214 }
6215
6216 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6217 if (I == SkipStart) {
6218 S.Diag(OperatorArrows[I]->getLocation(),
6219 diag::note_operator_arrows_suppressed)
6220 << SkipCount;
6221 I += SkipCount;
6222 } else {
6223 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6224 << OperatorArrows[I]->getCallResultType();
6225 ++I;
6226 }
6227 }
6228}
6229
Nico Weber964d3322015-02-16 22:35:45 +00006230ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6231 SourceLocation OpLoc,
6232 tok::TokenKind OpKind,
6233 ParsedType &ObjectType,
6234 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006235 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006236 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006237 if (Result.isInvalid()) return ExprError();
6238 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006239
John McCall526ab472011-10-25 17:37:35 +00006240 Result = CheckPlaceholderExpr(Base);
6241 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006242 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006243
John McCallb268a282010-08-23 23:25:46 +00006244 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006245 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006246 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006247 // If we have a pointer to a dependent type and are using the -> operator,
6248 // the object type is the type that the pointer points to. We might still
6249 // have enough information about that type to do something useful.
6250 if (OpKind == tok::arrow)
6251 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6252 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006253
John McCallba7bf592010-08-24 05:47:05 +00006254 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006255 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006256 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006257 }
Mike Stump11289f42009-09-09 15:08:12 +00006258
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006259 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006260 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006261 // returned, with the original second operand.
6262 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006263 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006264 bool NoArrowOperatorFound = false;
6265 bool FirstIteration = true;
6266 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006267 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006268 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006269 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006270 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006271
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006272 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006273 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6274 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006275 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006276 noteOperatorArrows(*this, OperatorArrows);
6277 Diag(OpLoc, diag::note_operator_arrow_depth)
6278 << getLangOpts().ArrowDepth;
6279 return ExprError();
6280 }
6281
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006282 Result = BuildOverloadedArrowExpr(
6283 S, Base, OpLoc,
6284 // When in a template specialization and on the first loop iteration,
6285 // potentially give the default diagnostic (with the fixit in a
6286 // separate note) instead of having the error reported back to here
6287 // and giving a diagnostic with a fixit attached to the error itself.
6288 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006289 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006290 : &NoArrowOperatorFound);
6291 if (Result.isInvalid()) {
6292 if (NoArrowOperatorFound) {
6293 if (FirstIteration) {
6294 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006295 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006296 << FixItHint::CreateReplacement(OpLoc, ".");
6297 OpKind = tok::period;
6298 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006299 }
6300 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6301 << BaseType << Base->getSourceRange();
6302 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006303 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006304 Diag(CD->getLocStart(),
6305 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006306 }
6307 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006308 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006309 }
John McCallb268a282010-08-23 23:25:46 +00006310 Base = Result.get();
6311 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006312 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006313 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006314 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006315 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006316 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6317 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006318 return ExprError();
6319 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006320 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006321 }
Mike Stump11289f42009-09-09 15:08:12 +00006322
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006323 if (OpKind == tok::arrow &&
6324 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006325 BaseType = BaseType->getPointeeType();
6326 }
Mike Stump11289f42009-09-09 15:08:12 +00006327
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006328 // Objective-C properties allow "." access on Objective-C pointer types,
6329 // so adjust the base type to the object type itself.
6330 if (BaseType->isObjCObjectPointerType())
6331 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006332
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006333 // C++ [basic.lookup.classref]p2:
6334 // [...] If the type of the object expression is of pointer to scalar
6335 // type, the unqualified-id is looked up in the context of the complete
6336 // postfix-expression.
6337 //
6338 // This also indicates that we could be parsing a pseudo-destructor-name.
6339 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006340 // expressions or normal member (ivar or property) access expressions, and
6341 // it's legal for the type to be incomplete if this is a pseudo-destructor
6342 // call. We'll do more incomplete-type checks later in the lookup process,
6343 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006344 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006345 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006346 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006347 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006348 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006349 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006350 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006351 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006352 }
Mike Stump11289f42009-09-09 15:08:12 +00006353
Douglas Gregor3024f072012-04-16 07:05:22 +00006354 // The object type must be complete (or dependent), or
6355 // C++11 [expr.prim.general]p3:
6356 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006357 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006358 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006359 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006360 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006361 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006362 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006363
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006364 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006365 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006366 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006367 // type C (or of pointer to a class type C), the unqualified-id is looked
6368 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006369 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006370 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006371}
6372
Simon Pilgrim75c26882016-09-30 14:25:09 +00006373static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006374 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006375 if (Base->hasPlaceholderType()) {
6376 ExprResult result = S.CheckPlaceholderExpr(Base);
6377 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006378 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006379 }
6380 ObjectType = Base->getType();
6381
David Blaikie1d578782011-12-16 16:03:09 +00006382 // C++ [expr.pseudo]p2:
6383 // The left-hand side of the dot operator shall be of scalar type. The
6384 // left-hand side of the arrow operator shall be of pointer to scalar type.
6385 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006386 // Note that this is rather different from the normal handling for the
6387 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006388 if (OpKind == tok::arrow) {
6389 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6390 ObjectType = Ptr->getPointeeType();
6391 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006392 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006393 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6394 << ObjectType << true
6395 << FixItHint::CreateReplacement(OpLoc, ".");
6396 if (S.isSFINAEContext())
6397 return true;
6398
6399 OpKind = tok::period;
6400 }
6401 }
6402
6403 return false;
6404}
6405
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006406/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6407/// pointer objects.
6408static bool
6409canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6410 QualType DestructedType) {
6411 // If this is a record type, check if its destructor is callable.
6412 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6413 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6414 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6415 return false;
6416 }
6417
6418 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6419 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6420 DestructedType->isVectorType();
6421}
6422
John McCalldadc5752010-08-24 06:29:42 +00006423ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006424 SourceLocation OpLoc,
6425 tok::TokenKind OpKind,
6426 const CXXScopeSpec &SS,
6427 TypeSourceInfo *ScopeTypeInfo,
6428 SourceLocation CCLoc,
6429 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006430 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006431 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006432
Eli Friedman0ce4de42012-01-25 04:35:06 +00006433 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006434 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6435 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006436
Douglas Gregorc5c57342012-09-10 14:57:06 +00006437 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6438 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006439 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006440 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006441 else {
Nico Weber58829272012-01-23 05:50:57 +00006442 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6443 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006444 return ExprError();
6445 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006446 }
6447
6448 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006450 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006451 if (DestructedTypeInfo) {
6452 QualType DestructedType = DestructedTypeInfo->getType();
6453 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006454 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006455 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6456 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006457 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6458 // Foo *foo;
6459 // foo.~Foo();
6460 if (OpKind == tok::period && ObjectType->isPointerType() &&
6461 Context.hasSameUnqualifiedType(DestructedType,
6462 ObjectType->getPointeeType())) {
6463 auto Diagnostic =
6464 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6465 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006466
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006467 // Issue a fixit only when the destructor is valid.
6468 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6469 *this, DestructedType))
6470 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6471
6472 // Recover by setting the object type to the destructed type and the
6473 // operator to '->'.
6474 ObjectType = DestructedType;
6475 OpKind = tok::arrow;
6476 } else {
6477 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6478 << ObjectType << DestructedType << Base->getSourceRange()
6479 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6480
6481 // Recover by setting the destructed type to the object type.
6482 DestructedType = ObjectType;
6483 DestructedTypeInfo =
6484 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6485 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6486 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006487 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006488 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006489
John McCall31168b02011-06-15 23:02:42 +00006490 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6491 // Okay: just pretend that the user provided the correctly-qualified
6492 // type.
6493 } else {
6494 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6495 << ObjectType << DestructedType << Base->getSourceRange()
6496 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6497 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006498
John McCall31168b02011-06-15 23:02:42 +00006499 // Recover by setting the destructed type to the object type.
6500 DestructedType = ObjectType;
6501 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6502 DestructedTypeStart);
6503 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6504 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006505 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006507
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006508 // C++ [expr.pseudo]p2:
6509 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6510 // form
6511 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006513 //
6514 // shall designate the same scalar type.
6515 if (ScopeTypeInfo) {
6516 QualType ScopeType = ScopeTypeInfo->getType();
6517 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006518 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006520 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006521 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006522 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006523 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006524
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006525 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006526 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006527 }
6528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006529
John McCallb268a282010-08-23 23:25:46 +00006530 Expr *Result
6531 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6532 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006533 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006534 ScopeTypeInfo,
6535 CCLoc,
6536 TildeLoc,
6537 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538
David Majnemerced8bdf2015-02-25 17:36:15 +00006539 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006540}
6541
John McCalldadc5752010-08-24 06:29:42 +00006542ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006543 SourceLocation OpLoc,
6544 tok::TokenKind OpKind,
6545 CXXScopeSpec &SS,
6546 UnqualifiedId &FirstTypeName,
6547 SourceLocation CCLoc,
6548 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006549 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006550 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6551 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6552 "Invalid first type name in pseudo-destructor");
6553 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6554 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6555 "Invalid second type name in pseudo-destructor");
6556
Eli Friedman0ce4de42012-01-25 04:35:06 +00006557 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006558 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6559 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006560
6561 // Compute the object type that we should use for name lookup purposes. Only
6562 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006563 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006564 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006565 if (ObjectType->isRecordType())
6566 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006567 else if (ObjectType->isDependentType())
6568 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006570
6571 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006572 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006573 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006574 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006575 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006576 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006578 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006579 S, &SS, true, false, ObjectTypePtrForLookup,
6580 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006581 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006582 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6583 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006585 // couldn't find anything useful in scope. Just store the identifier and
6586 // it's location, and we'll perform (qualified) name lookup again at
6587 // template instantiation time.
6588 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6589 SecondTypeName.StartLocation);
6590 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006592 diag::err_pseudo_dtor_destructor_non_type)
6593 << SecondTypeName.Identifier << ObjectType;
6594 if (isSFINAEContext())
6595 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006597 // Recover by assuming we had the right type all along.
6598 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006599 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006600 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006601 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006602 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006603 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006604 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006605 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006606 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006607 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006608 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006609 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006610 TemplateId->TemplateNameLoc,
6611 TemplateId->LAngleLoc,
6612 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006613 TemplateId->RAngleLoc,
6614 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006615 if (T.isInvalid() || !T.get()) {
6616 // Recover by assuming we had the right type all along.
6617 DestructedType = ObjectType;
6618 } else
6619 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621
6622 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006623 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006624 if (!DestructedType.isNull()) {
6625 if (!DestructedTypeInfo)
6626 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006627 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006628 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6629 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006631 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006632 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006633 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006635 FirstTypeName.Identifier) {
6636 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006637 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006638 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006639 S, &SS, true, false, ObjectTypePtrForLookup,
6640 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006641 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006642 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006643 diag::err_pseudo_dtor_destructor_non_type)
6644 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006645
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006646 if (isSFINAEContext())
6647 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006648
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006649 // Just drop this type. It's unnecessary anyway.
6650 ScopeType = QualType();
6651 } else
6652 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006653 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006654 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006655 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006656 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006657 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006658 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006659 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006660 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006661 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006662 TemplateId->TemplateNameLoc,
6663 TemplateId->LAngleLoc,
6664 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006665 TemplateId->RAngleLoc,
6666 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006667 if (T.isInvalid() || !T.get()) {
6668 // Recover by dropping this type.
6669 ScopeType = QualType();
6670 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006672 }
6673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006674
Douglas Gregor90ad9222010-02-24 23:02:30 +00006675 if (!ScopeType.isNull() && !ScopeTypeInfo)
6676 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6677 FirstTypeName.StartLocation);
6678
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006679
John McCallb268a282010-08-23 23:25:46 +00006680 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006681 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006682 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006683}
6684
David Blaikie1d578782011-12-16 16:03:09 +00006685ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6686 SourceLocation OpLoc,
6687 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006688 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006689 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006690 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006691 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6692 return ExprError();
6693
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006694 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6695 false);
David Blaikie1d578782011-12-16 16:03:09 +00006696
6697 TypeLocBuilder TLB;
6698 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6699 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6700 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6701 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6702
6703 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006704 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006705 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006706}
6707
John Wiegley01296292011-04-08 18:41:53 +00006708ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006709 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006710 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006711 if (Method->getParent()->isLambda() &&
6712 Method->getConversionType()->isBlockPointerType()) {
6713 // This is a lambda coversion to block pointer; check if the argument
6714 // is a LambdaExpr.
6715 Expr *SubE = E;
6716 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6717 if (CE && CE->getCastKind() == CK_NoOp)
6718 SubE = CE->getSubExpr();
6719 SubE = SubE->IgnoreParens();
6720 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6721 SubE = BE->getSubExpr();
6722 if (isa<LambdaExpr>(SubE)) {
6723 // For the conversion to block pointer on a lambda expression, we
6724 // construct a special BlockLiteral instead; this doesn't really make
6725 // a difference in ARC, but outside of ARC the resulting block literal
6726 // follows the normal lifetime rules for block literals instead of being
6727 // autoreleased.
6728 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006729 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006730 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6731 E->getExprLoc(),
6732 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006733 PopExpressionEvaluationContext();
6734
Eli Friedman98b01ed2012-03-01 04:01:32 +00006735 if (Exp.isInvalid())
6736 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6737 return Exp;
6738 }
6739 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006740
Craig Topperc3ec1492014-05-26 06:22:03 +00006741 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006742 FoundDecl, Method);
6743 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006744 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006745
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006746 MemberExpr *ME = new (Context) MemberExpr(
6747 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6748 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006749 if (HadMultipleCandidates)
6750 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006751 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006752
Alp Toker314cc812014-01-25 16:55:45 +00006753 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006754 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6755 ResultType = ResultType.getNonLValueExprType(Context);
6756
Douglas Gregor27381f32009-11-23 12:27:39 +00006757 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006758 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006759 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006760 return CE;
6761}
6762
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006763ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6764 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006765 // If the operand is an unresolved lookup expression, the expression is ill-
6766 // formed per [over.over]p1, because overloaded function names cannot be used
6767 // without arguments except in explicit contexts.
6768 ExprResult R = CheckPlaceholderExpr(Operand);
6769 if (R.isInvalid())
6770 return R;
6771
6772 // The operand may have been modified when checking the placeholder type.
6773 Operand = R.get();
6774
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006775 if (ActiveTemplateInstantiations.empty() &&
6776 Operand->HasSideEffects(Context, false)) {
6777 // The expression operand for noexcept is in an unevaluated expression
6778 // context, so side effects could result in unintended consequences.
6779 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6780 }
6781
Richard Smithf623c962012-04-17 00:58:00 +00006782 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006783 return new (Context)
6784 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006785}
6786
6787ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6788 Expr *Operand, SourceLocation RParen) {
6789 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006790}
6791
Eli Friedmanf798f652012-05-24 22:04:19 +00006792static bool IsSpecialDiscardedValue(Expr *E) {
6793 // In C++11, discarded-value expressions of a certain form are special,
6794 // according to [expr]p10:
6795 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6796 // expression is an lvalue of volatile-qualified type and it has
6797 // one of the following forms:
6798 E = E->IgnoreParens();
6799
Eli Friedmanc49c2262012-05-24 22:36:31 +00006800 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006801 if (isa<DeclRefExpr>(E))
6802 return true;
6803
Eli Friedmanc49c2262012-05-24 22:36:31 +00006804 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006805 if (isa<ArraySubscriptExpr>(E))
6806 return true;
6807
Eli Friedmanc49c2262012-05-24 22:36:31 +00006808 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006809 if (isa<MemberExpr>(E))
6810 return true;
6811
Eli Friedmanc49c2262012-05-24 22:36:31 +00006812 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006813 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6814 if (UO->getOpcode() == UO_Deref)
6815 return true;
6816
6817 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006818 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006819 if (BO->isPtrMemOp())
6820 return true;
6821
Eli Friedmanc49c2262012-05-24 22:36:31 +00006822 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006823 if (BO->getOpcode() == BO_Comma)
6824 return IsSpecialDiscardedValue(BO->getRHS());
6825 }
6826
Eli Friedmanc49c2262012-05-24 22:36:31 +00006827 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006828 // operands are one of the above, or
6829 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6830 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6831 IsSpecialDiscardedValue(CO->getFalseExpr());
6832 // The related edge case of "*x ?: *x".
6833 if (BinaryConditionalOperator *BCO =
6834 dyn_cast<BinaryConditionalOperator>(E)) {
6835 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6836 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6837 IsSpecialDiscardedValue(BCO->getFalseExpr());
6838 }
6839
6840 // Objective-C++ extensions to the rule.
6841 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6842 return true;
6843
6844 return false;
6845}
6846
John McCall34376a62010-12-04 03:47:34 +00006847/// Perform the conversions required for an expression used in a
6848/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006849ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006850 if (E->hasPlaceholderType()) {
6851 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006852 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006853 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006854 }
6855
John McCallfee942d2010-12-02 02:07:15 +00006856 // C99 6.3.2.1:
6857 // [Except in specific positions,] an lvalue that does not have
6858 // array type is converted to the value stored in the
6859 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006860 if (E->isRValue()) {
6861 // In C, function designators (i.e. expressions of function type)
6862 // are r-values, but we still want to do function-to-pointer decay
6863 // on them. This is both technically correct and convenient for
6864 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006865 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006866 return DefaultFunctionArrayConversion(E);
6867
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006868 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006869 }
John McCallfee942d2010-12-02 02:07:15 +00006870
Eli Friedmanf798f652012-05-24 22:04:19 +00006871 if (getLangOpts().CPlusPlus) {
6872 // The C++11 standard defines the notion of a discarded-value expression;
6873 // normally, we don't need to do anything to handle it, but if it is a
6874 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6875 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006876 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006877 E->getType().isVolatileQualified() &&
6878 IsSpecialDiscardedValue(E)) {
6879 ExprResult Res = DefaultLvalueConversion(E);
6880 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006881 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006882 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006883 }
Richard Smith122f88d2016-12-06 23:52:28 +00006884
6885 // C++1z:
6886 // If the expression is a prvalue after this optional conversion, the
6887 // temporary materialization conversion is applied.
6888 //
6889 // We skip this step: IR generation is able to synthesize the storage for
6890 // itself in the aggregate case, and adding the extra node to the AST is
6891 // just clutter.
6892 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6893 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006894 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006895 }
John McCall34376a62010-12-04 03:47:34 +00006896
6897 // GCC seems to also exclude expressions of incomplete enum type.
6898 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6899 if (!T->getDecl()->isComplete()) {
6900 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006901 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006902 return E;
John McCall34376a62010-12-04 03:47:34 +00006903 }
6904 }
6905
John Wiegley01296292011-04-08 18:41:53 +00006906 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6907 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006908 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006909 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006910
John McCallca61b652010-12-04 12:29:11 +00006911 if (!E->getType()->isVoidType())
6912 RequireCompleteType(E->getExprLoc(), E->getType(),
6913 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006914 return E;
John McCall34376a62010-12-04 03:47:34 +00006915}
6916
Faisal Valia17d19f2013-11-07 05:17:06 +00006917// If we can unambiguously determine whether Var can never be used
6918// in a constant expression, return true.
6919// - if the variable and its initializer are non-dependent, then
6920// we can unambiguously check if the variable is a constant expression.
6921// - if the initializer is not value dependent - we can determine whether
6922// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006923// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006924// never be a constant expression.
6925// - FXIME: if the initializer is dependent, we can still do some analysis and
6926// identify certain cases unambiguously as non-const by using a Visitor:
6927// - such as those that involve odr-use of a ParmVarDecl, involve a new
6928// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006929static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006930 ASTContext &Context) {
6931 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006932 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006933
6934 // If there is no initializer - this can not be a constant expression.
6935 if (!Var->getAnyInitializer(DefVD)) return true;
6936 assert(DefVD);
6937 if (DefVD->isWeak()) return false;
6938 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006939
Faisal Valia17d19f2013-11-07 05:17:06 +00006940 Expr *Init = cast<Expr>(Eval->Value);
6941
6942 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006943 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6944 // of value-dependent expressions, and use it here to determine whether the
6945 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006946 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006947 }
6948
Simon Pilgrim75c26882016-09-30 14:25:09 +00006949 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006950}
6951
Simon Pilgrim75c26882016-09-30 14:25:09 +00006952/// \brief Check if the current lambda has any potential captures
6953/// that must be captured by any of its enclosing lambdas that are ready to
6954/// capture. If there is a lambda that can capture a nested
6955/// potential-capture, go ahead and do so. Also, check to see if any
6956/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006957/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006958
Faisal Valiab3d6462013-12-07 20:22:44 +00006959static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6960 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6961
Simon Pilgrim75c26882016-09-30 14:25:09 +00006962 assert(!S.isUnevaluatedContext());
6963 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00006964#ifndef NDEBUG
6965 DeclContext *DC = S.CurContext;
6966 while (DC && isa<CapturedDecl>(DC))
6967 DC = DC->getParent();
6968 assert(
6969 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006970 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00006971#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00006972
6973 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6974
6975 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6976 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006977
Faisal Valiab3d6462013-12-07 20:22:44 +00006978 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006979 // lambda (within a generic outer lambda), must be captured by an
6980 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006981 const unsigned NumPotentialCaptures =
6982 CurrentLSI->getNumPotentialVariableCaptures();
6983 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006984 Expr *VarExpr = nullptr;
6985 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006986 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006987 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00006988 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00006989 // need to check enclosing lambda's for speculative captures.
6990 // For e.g.:
6991 // Even though 'x' is not odr-used, it should be captured.
6992 // int test() {
6993 // const int x = 10;
6994 // auto L = [=](auto a) {
6995 // (void) +x + a;
6996 // };
6997 // }
6998 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006999 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007000 continue;
7001
7002 // If we have a capture-capable lambda for the variable, go ahead and
7003 // capture the variable in that lambda (and all its enclosing lambdas).
7004 if (const Optional<unsigned> Index =
7005 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7006 FunctionScopesArrayRef, Var, S)) {
7007 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7008 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7009 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007010 }
7011 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007012 VariableCanNeverBeAConstantExpression(Var, S.Context);
7013 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7014 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007015 // can not be used in a constant expression - which means
7016 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007017 // capture violation early, if the variable is un-captureable.
7018 // This is purely for diagnosing errors early. Otherwise, this
7019 // error would get diagnosed when the lambda becomes capture ready.
7020 QualType CaptureType, DeclRefType;
7021 SourceLocation ExprLoc = VarExpr->getExprLoc();
7022 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007023 /*EllipsisLoc*/ SourceLocation(),
7024 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007025 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007026 // We will never be able to capture this variable, and we need
7027 // to be able to in any and all instantiations, so diagnose it.
7028 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007029 /*EllipsisLoc*/ SourceLocation(),
7030 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007031 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007032 }
7033 }
7034 }
7035
Faisal Valiab3d6462013-12-07 20:22:44 +00007036 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007037 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007038 // If we have a capture-capable lambda for 'this', go ahead and capture
7039 // 'this' in that lambda (and all its enclosing lambdas).
7040 if (const Optional<unsigned> Index =
7041 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007042 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007043 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7044 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7045 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7046 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007047 }
7048 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007049
7050 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007051 CurrentLSI->clearPotentialCaptures();
7052}
7053
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007054static ExprResult attemptRecovery(Sema &SemaRef,
7055 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007056 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007057 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7058 Consumer.getLookupResult().getLookupKind());
7059 const CXXScopeSpec *SS = Consumer.getSS();
7060 CXXScopeSpec NewSS;
7061
7062 // Use an approprate CXXScopeSpec for building the expr.
7063 if (auto *NNS = TC.getCorrectionSpecifier())
7064 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7065 else if (SS && !TC.WillReplaceSpecifier())
7066 NewSS = *SS;
7067
Richard Smithde6d6c42015-12-29 19:43:10 +00007068 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007069 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007070 R.addDecl(ND);
7071 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007072 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007073 CXXRecordDecl *Record = nullptr;
7074 if (auto *NNS = TC.getCorrectionSpecifier())
7075 Record = NNS->getAsType()->getAsCXXRecordDecl();
7076 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007077 Record =
7078 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7079 if (Record)
7080 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007081
7082 // Detect and handle the case where the decl might be an implicit
7083 // member.
7084 bool MightBeImplicitMember;
7085 if (!Consumer.isAddressOfOperand())
7086 MightBeImplicitMember = true;
7087 else if (!NewSS.isEmpty())
7088 MightBeImplicitMember = false;
7089 else if (R.isOverloadedResult())
7090 MightBeImplicitMember = false;
7091 else if (R.isUnresolvableResult())
7092 MightBeImplicitMember = true;
7093 else
7094 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7095 isa<IndirectFieldDecl>(ND) ||
7096 isa<MSPropertyDecl>(ND);
7097
7098 if (MightBeImplicitMember)
7099 return SemaRef.BuildPossibleImplicitMemberExpr(
7100 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007101 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007102 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7103 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7104 Ivar->getIdentifier());
7105 }
7106 }
7107
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007108 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7109 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007110}
7111
Kaelyn Takata6c759512014-10-27 18:07:37 +00007112namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007113class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7114 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7115
7116public:
7117 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7118 : TypoExprs(TypoExprs) {}
7119 bool VisitTypoExpr(TypoExpr *TE) {
7120 TypoExprs.insert(TE);
7121 return true;
7122 }
7123};
7124
Kaelyn Takata6c759512014-10-27 18:07:37 +00007125class TransformTypos : public TreeTransform<TransformTypos> {
7126 typedef TreeTransform<TransformTypos> BaseTransform;
7127
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007128 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7129 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007130 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007131 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007132 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007133 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007134
7135 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7136 /// If the TypoExprs were successfully corrected, then the diagnostics should
7137 /// suggest the corrections. Otherwise the diagnostics will not suggest
7138 /// anything (having been passed an empty TypoCorrection).
7139 void EmitAllDiagnostics() {
7140 for (auto E : TypoExprs) {
7141 TypoExpr *TE = cast<TypoExpr>(E);
7142 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007143 if (State.DiagHandler) {
7144 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7145 ExprResult Replacement = TransformCache[TE];
7146
7147 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7148 // TypoCorrection, replacing the existing decls. This ensures the right
7149 // NamedDecl is used in diagnostics e.g. in the case where overload
7150 // resolution was used to select one from several possible decls that
7151 // had been stored in the TypoCorrection.
7152 if (auto *ND = getDeclFromExpr(
7153 Replacement.isInvalid() ? nullptr : Replacement.get()))
7154 TC.setCorrectionDecl(ND);
7155
7156 State.DiagHandler(TC);
7157 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007158 SemaRef.clearDelayedTypo(TE);
7159 }
7160 }
7161
7162 /// \brief If corrections for the first TypoExpr have been exhausted for a
7163 /// given combination of the other TypoExprs, retry those corrections against
7164 /// the next combination of substitutions for the other TypoExprs by advancing
7165 /// to the next potential correction of the second TypoExpr. For the second
7166 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7167 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7168 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7169 /// TransformCache). Returns true if there is still any untried combinations
7170 /// of corrections.
7171 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7172 for (auto TE : TypoExprs) {
7173 auto &State = SemaRef.getTypoExprState(TE);
7174 TransformCache.erase(TE);
7175 if (!State.Consumer->finished())
7176 return true;
7177 State.Consumer->resetCorrectionStream();
7178 }
7179 return false;
7180 }
7181
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007182 NamedDecl *getDeclFromExpr(Expr *E) {
7183 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7184 E = OverloadResolution[OE];
7185
7186 if (!E)
7187 return nullptr;
7188 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007189 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007190 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007191 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007192 // FIXME: Add any other expr types that could be be seen by the delayed typo
7193 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007194 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007195 return nullptr;
7196 }
7197
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007198 ExprResult TryTransform(Expr *E) {
7199 Sema::SFINAETrap Trap(SemaRef);
7200 ExprResult Res = TransformExpr(E);
7201 if (Trap.hasErrorOccurred() || Res.isInvalid())
7202 return ExprError();
7203
7204 return ExprFilter(Res.get());
7205 }
7206
Kaelyn Takata6c759512014-10-27 18:07:37 +00007207public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007208 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7209 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007210
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007211 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7212 MultiExprArg Args,
7213 SourceLocation RParenLoc,
7214 Expr *ExecConfig = nullptr) {
7215 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7216 RParenLoc, ExecConfig);
7217 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007218 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007219 Expr *ResultCall = Result.get();
7220 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7221 ResultCall = BE->getSubExpr();
7222 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7223 OverloadResolution[OE] = CE->getCallee();
7224 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007225 }
7226 return Result;
7227 }
7228
Kaelyn Takata6c759512014-10-27 18:07:37 +00007229 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7230
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007231 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7232
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007233 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7234 return Owned(E);
7235 }
7236
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007237 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7238 return Owned(E);
7239 }
7240
Kaelyn Takata6c759512014-10-27 18:07:37 +00007241 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007242 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007243 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007244 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007245
Kaelyn Takata6c759512014-10-27 18:07:37 +00007246 // Exit if either the transform was valid or if there were no TypoExprs
7247 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007248 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007249 !CheckAndAdvanceTypoExprCorrectionStreams())
7250 break;
7251 }
7252
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007253 // Ensure none of the TypoExprs have multiple typo correction candidates
7254 // with the same edit length that pass all the checks and filters.
7255 // TODO: Properly handle various permutations of possible corrections when
7256 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007257 // Also, disable typo correction while attempting the transform when
7258 // handling potentially ambiguous typo corrections as any new TypoExprs will
7259 // have been introduced by the application of one of the correction
7260 // candidates and add little to no value if corrected.
7261 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007262 while (!AmbiguousTypoExprs.empty()) {
7263 auto TE = AmbiguousTypoExprs.back();
7264 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007265 auto &State = SemaRef.getTypoExprState(TE);
7266 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007267 TransformCache.erase(TE);
7268 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007269 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007270 TransformCache.erase(TE);
7271 Res = ExprError();
7272 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007273 }
7274 AmbiguousTypoExprs.remove(TE);
7275 State.Consumer->restoreSavedPosition();
7276 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007277 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007278 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007279
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007280 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007281 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007282 FindTypoExprs(TypoExprs).TraverseStmt(E);
7283
Kaelyn Takata6c759512014-10-27 18:07:37 +00007284 EmitAllDiagnostics();
7285
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007286 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007287 }
7288
7289 ExprResult TransformTypoExpr(TypoExpr *E) {
7290 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7291 // cached transformation result if there is one and the TypoExpr isn't the
7292 // first one that was encountered.
7293 auto &CacheEntry = TransformCache[E];
7294 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7295 return CacheEntry;
7296 }
7297
7298 auto &State = SemaRef.getTypoExprState(E);
7299 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7300
7301 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7302 // typo correction and return it.
7303 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007304 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007305 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007306 // FIXME: If we would typo-correct to an invalid declaration, it's
7307 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007308 ExprResult NE = State.RecoveryHandler ?
7309 State.RecoveryHandler(SemaRef, E, TC) :
7310 attemptRecovery(SemaRef, *State.Consumer, TC);
7311 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007312 // Check whether there may be a second viable correction with the same
7313 // edit distance; if so, remember this TypoExpr may have an ambiguous
7314 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007315 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007316 if ((Next = State.Consumer->peekNextCorrection()) &&
7317 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7318 AmbiguousTypoExprs.insert(E);
7319 } else {
7320 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007321 }
7322 assert(!NE.isUnset() &&
7323 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007324 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007325 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007326 }
7327 return CacheEntry = ExprError();
7328 }
7329};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007330}
Faisal Valia17d19f2013-11-07 05:17:06 +00007331
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007332ExprResult
7333Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7334 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007335 // If the current evaluation context indicates there are uncorrected typos
7336 // and the current expression isn't guaranteed to not have typos, try to
7337 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007338 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007339 (E->isTypeDependent() || E->isValueDependent() ||
7340 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007341 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7342 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7343 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007344 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007345 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007346 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007347 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007348 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007349 ExprEvalContexts.back().NumTypos -= TyposResolved;
7350 return Result;
7351 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007352 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007353 }
7354 return E;
7355}
7356
Richard Smith945f8d32013-01-14 22:39:08 +00007357ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007358 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007359 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007360 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007361 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007362
7363 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007364 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007365
7366 // If we are an init-expression in a lambdas init-capture, we should not
7367 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007368 // containing full-expression is done).
7369 // template<class ... Ts> void test(Ts ... t) {
7370 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7371 // return a;
7372 // }() ...);
7373 // }
7374 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7375 // when we parse the lambda introducer, and teach capturing (but not
7376 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7377 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7378 // lambda where we've entered the introducer but not the body, or represent a
7379 // lambda where we've entered the body, depending on where the
7380 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007381 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007382 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007383 return ExprError();
7384
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007385 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007386 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007387 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007388 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007389 if (FullExpr.isInvalid())
7390 return ExprError();
7391 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007392
Richard Smith945f8d32013-01-14 22:39:08 +00007393 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007394 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007395 if (FullExpr.isInvalid())
7396 return ExprError();
7397
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007398 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007399 if (FullExpr.isInvalid())
7400 return ExprError();
7401 }
John Wiegley01296292011-04-08 18:41:53 +00007402
Kaelyn Takata49d84322014-11-11 23:26:56 +00007403 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7404 if (FullExpr.isInvalid())
7405 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007406
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007407 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007408
Simon Pilgrim75c26882016-09-30 14:25:09 +00007409 // At the end of this full expression (which could be a deeply nested
7410 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007411 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007412 // Consider the following code:
7413 // void f(int, int);
7414 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007415 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007416 // const int x = 10, y = 20;
7417 // auto L = [=](auto a) {
7418 // auto M = [=](auto b) {
7419 // f(x, b); <-- requires x to be captured by L and M
7420 // f(y, a); <-- requires y to be captured by L, but not all Ms
7421 // };
7422 // };
7423 // }
7424
Simon Pilgrim75c26882016-09-30 14:25:09 +00007425 // FIXME: Also consider what happens for something like this that involves
7426 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007427 // void f() {
7428 // const int n = 0;
7429 // auto L = [&](auto a) {
7430 // +n + ({ 0; a; });
7431 // };
7432 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007433 //
7434 // Here, we see +n, and then the full-expression 0; ends, so we don't
7435 // capture n (and instead remove it from our list of potential captures),
7436 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007437 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007438
Alexey Bataev31939e32016-11-11 12:36:20 +00007439 LambdaScopeInfo *const CurrentLSI =
7440 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007441 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007442 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007443 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007444 // By ensuring we are in the context of a lambda's call operator
7445 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007446 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007447 // PR, a proper fix would entail :
7448 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007449 // - Add to Sema an integer holding the smallest (outermost) scope
7450 // index that we are *lexically* within, and save/restore/set to
7451 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007452 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007453 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007454 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007455 DeclContext *DC = CurContext;
7456 while (DC && isa<CapturedDecl>(DC))
7457 DC = DC->getParent();
7458 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007459 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007460 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007461 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7462 *this);
John McCall5d413782010-12-06 08:20:24 +00007463 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007464}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007465
7466StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7467 if (!FullStmt) return StmtError();
7468
John McCall5d413782010-12-06 08:20:24 +00007469 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007470}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007471
Simon Pilgrim75c26882016-09-30 14:25:09 +00007472Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007473Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7474 CXXScopeSpec &SS,
7475 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007476 DeclarationName TargetName = TargetNameInfo.getName();
7477 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007478 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007479
Douglas Gregor43edb322011-10-24 22:31:10 +00007480 // If the name itself is dependent, then the result is dependent.
7481 if (TargetName.isDependentName())
7482 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007483
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007484 // Do the redeclaration lookup in the current scope.
7485 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7486 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007487 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007488 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007489
Douglas Gregor43edb322011-10-24 22:31:10 +00007490 switch (R.getResultKind()) {
7491 case LookupResult::Found:
7492 case LookupResult::FoundOverloaded:
7493 case LookupResult::FoundUnresolvedValue:
7494 case LookupResult::Ambiguous:
7495 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007496
Douglas Gregor43edb322011-10-24 22:31:10 +00007497 case LookupResult::NotFound:
7498 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007499
Douglas Gregor43edb322011-10-24 22:31:10 +00007500 case LookupResult::NotFoundInCurrentInstantiation:
7501 return IER_Dependent;
7502 }
David Blaikie8a40f702012-01-17 06:56:22 +00007503
7504 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007505}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007506
Simon Pilgrim75c26882016-09-30 14:25:09 +00007507Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007508Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7509 bool IsIfExists, CXXScopeSpec &SS,
7510 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007511 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007512
Richard Smith151c4562016-12-20 21:35:28 +00007513 // Check for an unexpanded parameter pack.
7514 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7515 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7516 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007517 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007518
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007519 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7520}