blob: 1379440e8a031afbb09203388f32402977c76b3b [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.
Eli Friedman73a04092012-01-07 04:59:52 +00001109 break;
1110 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001111 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1112 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1113 // This context can't implicitly capture 'this'; fail out.
1114 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001115 Diag(Loc, diag::err_this_capture)
1116 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001117 return true;
1118 }
Eli Friedman20139d32012-01-11 02:36:31 +00001119 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001120 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001121 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001122 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001123 (Explicit && idx == MaxFunctionScopesIndex)) {
1124 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1125 // iteration through can be an explicit capture, all enclosing closures,
1126 // if any, must perform implicit captures.
1127
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001128 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001129 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001130 continue;
1131 }
Eli Friedman20139d32012-01-11 02:36:31 +00001132 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001133 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001134 Diag(Loc, diag::err_this_capture)
1135 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001136 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001137 }
Eli Friedman73a04092012-01-07 04:59:52 +00001138 break;
1139 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001140 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001141
1142 // If we got here, then the closure at MaxFunctionScopesIndex on the
1143 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1144 // (including implicit by-reference captures in any enclosing closures).
1145
1146 // In the loop below, respect the ByCopy flag only for the closure requesting
1147 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001148 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001149 // implicitly capturing the *enclosing object* by reference (see loop
1150 // above)).
1151 assert((!ByCopy ||
1152 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1153 "Only a lambda can capture the enclosing object (referred to by "
1154 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001155 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1156 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001157 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001158 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001159 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001160 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001161 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001162
Faisal Validc6b5962016-03-21 09:25:37 +00001163 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1164 // For lambda expressions, build a field and an initializing expression,
1165 // and capture the *enclosing object* by copy only if this is the first
1166 // iteration.
1167 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1168 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001169
Faisal Validc6b5962016-03-21 09:25:37 +00001170 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001171 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001172 ThisExpr =
1173 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1174 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001175
Faisal Validc6b5962016-03-21 09:25:37 +00001176 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001177 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001178 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001179 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001180}
1181
Richard Smith938f40b2011-06-11 17:19:42 +00001182ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001183 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1184 /// is a non-lvalue expression whose value is the address of the object for
1185 /// which the function is called.
1186
Douglas Gregor09deffa2011-10-18 16:47:30 +00001187 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001188 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001189
Eli Friedman73a04092012-01-07 04:59:52 +00001190 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001191 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001192}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001193
Douglas Gregor3024f072012-04-16 07:05:22 +00001194bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1195 // If we're outside the body of a member function, then we'll have a specified
1196 // type for 'this'.
1197 if (CXXThisTypeOverride.isNull())
1198 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001199
Douglas Gregor3024f072012-04-16 07:05:22 +00001200 // Determine whether we're looking into a class that's currently being
1201 // defined.
1202 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1203 return Class && Class->isBeingDefined();
1204}
1205
John McCalldadc5752010-08-24 06:29:42 +00001206ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001207Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001208 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001209 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001210 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001211 if (!TypeRep)
1212 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001213
John McCall97513962010-01-15 18:39:57 +00001214 TypeSourceInfo *TInfo;
1215 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1216 if (!TInfo)
1217 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001218
Serge Pavlov38526372016-11-12 15:38:55 +00001219 // Handle errors like: int({0})
1220 if (exprs.size() == 1 && !canInitializeWithParenthesizedList(Ty) &&
1221 LParenLoc.isValid() && RParenLoc.isValid())
1222 if (auto IList = dyn_cast<InitListExpr>(exprs[0])) {
1223 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1224 << Ty << IList->getSourceRange()
1225 << FixItHint::CreateRemoval(LParenLoc)
1226 << FixItHint::CreateRemoval(RParenLoc);
1227 LParenLoc = RParenLoc = SourceLocation();
1228 }
1229
Richard Smithb8c414c2016-06-30 20:24:30 +00001230 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1231 // Avoid creating a non-type-dependent expression that contains typos.
1232 // Non-type-dependent expressions are liable to be discarded without
1233 // checking for embedded typos.
1234 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1235 !Result.get()->isTypeDependent())
1236 Result = CorrectDelayedTyposInExpr(Result.get());
1237 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001238}
1239
1240/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1241/// Can be interpreted either as function-style casting ("int(x)")
1242/// or class type construction ("ClassType(x,y,z)")
1243/// or creation of a value-initialized type ("int()").
1244ExprResult
1245Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1246 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001247 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001248 SourceLocation RParenLoc) {
1249 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001250 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001251
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001252 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001253 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1254 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001255 }
1256
Sebastian Redld74dd492012-02-12 18:41:05 +00001257 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001258 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001259 && "List initialization must have initializer list as expression.");
1260 SourceRange FullRange = SourceRange(TyBeginLoc,
1261 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1262
Douglas Gregordd04d332009-01-16 18:33:17 +00001263 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001264 // If the expression list is a single expression, the type conversion
1265 // expression is equivalent (in definedness, and if defined in meaning) to the
1266 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001267 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001268 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001269 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001270 }
1271
David Majnemer7eddcff2015-09-14 07:05:00 +00001272 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1273 // simple-type-specifier or typename-specifier for a non-array complete
1274 // object type or the (possibly cv-qualified) void type, creates a prvalue
1275 // of the specified type, whose value is that produced by value-initializing
1276 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001277 QualType ElemTy = Ty;
1278 if (Ty->isArrayType()) {
1279 if (!ListInitialization)
1280 return ExprError(Diag(TyBeginLoc,
1281 diag::err_value_init_for_array_type) << FullRange);
1282 ElemTy = Context.getBaseElementType(Ty);
1283 }
1284
David Majnemer7eddcff2015-09-14 07:05:00 +00001285 if (!ListInitialization && Ty->isFunctionType())
1286 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1287 << FullRange);
1288
Eli Friedman576cbd02012-02-29 00:00:28 +00001289 if (!Ty->isVoidType() &&
1290 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001291 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001292 return ExprError();
1293
Douglas Gregor8ec51732010-09-08 21:40:08 +00001294 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001295 InitializationKind Kind =
1296 Exprs.size() ? ListInitialization
1297 ? InitializationKind::CreateDirectList(TyBeginLoc)
1298 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1299 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1300 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1301 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001302
Richard Smith90061902013-09-23 02:20:00 +00001303 if (Result.isInvalid() || !ListInitialization)
1304 return Result;
1305
1306 Expr *Inner = Result.get();
1307 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1308 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001309 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1310 // If we created a CXXTemporaryObjectExpr, that node also represents the
1311 // functional cast. Otherwise, create an explicit cast to represent
1312 // the syntactic form of a functional-style cast that was used here.
1313 //
1314 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1315 // would give a more consistent AST representation than using a
1316 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1317 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001318 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001319 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001320 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001321 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001322 }
1323
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001324 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001325}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001326
Richard Smithb2f0f052016-10-10 18:54:32 +00001327/// \brief Determine whether the given function is a non-placement
1328/// deallocation function.
1329static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1330 if (FD->isInvalidDecl())
1331 return false;
1332
1333 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1334 return Method->isUsualDeallocationFunction();
1335
1336 if (FD->getOverloadedOperator() != OO_Delete &&
1337 FD->getOverloadedOperator() != OO_Array_Delete)
1338 return false;
1339
1340 unsigned UsualParams = 1;
1341
1342 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1343 S.Context.hasSameUnqualifiedType(
1344 FD->getParamDecl(UsualParams)->getType(),
1345 S.Context.getSizeType()))
1346 ++UsualParams;
1347
1348 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1349 S.Context.hasSameUnqualifiedType(
1350 FD->getParamDecl(UsualParams)->getType(),
1351 S.Context.getTypeDeclType(S.getStdAlignValT())))
1352 ++UsualParams;
1353
1354 return UsualParams == FD->getNumParams();
1355}
1356
1357namespace {
1358 struct UsualDeallocFnInfo {
1359 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001360 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001361 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001362 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001363 // A function template declaration is never a usual deallocation function.
1364 if (!FD)
1365 return;
1366 if (FD->getNumParams() == 3)
1367 HasAlignValT = HasSizeT = true;
1368 else if (FD->getNumParams() == 2) {
1369 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1370 HasAlignValT = !HasSizeT;
1371 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001372
1373 // In CUDA, determine how much we'd like / dislike to call this.
1374 if (S.getLangOpts().CUDA)
1375 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1376 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001377 }
1378
1379 operator bool() const { return FD; }
1380
Richard Smithf75dcbe2016-10-11 00:21:10 +00001381 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1382 bool WantAlign) const {
1383 // C++17 [expr.delete]p10:
1384 // If the type has new-extended alignment, a function with a parameter
1385 // of type std::align_val_t is preferred; otherwise a function without
1386 // such a parameter is preferred
1387 if (HasAlignValT != Other.HasAlignValT)
1388 return HasAlignValT == WantAlign;
1389
1390 if (HasSizeT != Other.HasSizeT)
1391 return HasSizeT == WantSize;
1392
1393 // Use CUDA call preference as a tiebreaker.
1394 return CUDAPref > Other.CUDAPref;
1395 }
1396
Richard Smithb2f0f052016-10-10 18:54:32 +00001397 DeclAccessPair Found;
1398 FunctionDecl *FD;
1399 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001400 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001401 };
1402}
1403
1404/// Determine whether a type has new-extended alignment. This may be called when
1405/// the type is incomplete (for a delete-expression with an incomplete pointee
1406/// type), in which case it will conservatively return false if the alignment is
1407/// not known.
1408static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1409 return S.getLangOpts().AlignedAllocation &&
1410 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1411 S.getASTContext().getTargetInfo().getNewAlign();
1412}
1413
1414/// Select the correct "usual" deallocation function to use from a selection of
1415/// deallocation functions (either global or class-scope).
1416static UsualDeallocFnInfo resolveDeallocationOverload(
1417 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1418 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1419 UsualDeallocFnInfo Best;
1420
Richard Smithb2f0f052016-10-10 18:54:32 +00001421 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001422 UsualDeallocFnInfo Info(S, I.getPair());
1423 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1424 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001425 continue;
1426
1427 if (!Best) {
1428 Best = Info;
1429 if (BestFns)
1430 BestFns->push_back(Info);
1431 continue;
1432 }
1433
Richard Smithf75dcbe2016-10-11 00:21:10 +00001434 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001435 continue;
1436
1437 // If more than one preferred function is found, all non-preferred
1438 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001439 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001440 BestFns->clear();
1441
1442 Best = Info;
1443 if (BestFns)
1444 BestFns->push_back(Info);
1445 }
1446
1447 return Best;
1448}
1449
1450/// Determine whether a given type is a class for which 'delete[]' would call
1451/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1452/// we need to store the array size (even if the type is
1453/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001454static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1455 QualType allocType) {
1456 const RecordType *record =
1457 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1458 if (!record) return false;
1459
1460 // Try to find an operator delete[] in class scope.
1461
1462 DeclarationName deleteName =
1463 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1464 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1465 S.LookupQualifiedName(ops, record->getDecl());
1466
1467 // We're just doing this for information.
1468 ops.suppressDiagnostics();
1469
1470 // Very likely: there's no operator delete[].
1471 if (ops.empty()) return false;
1472
1473 // If it's ambiguous, it should be illegal to call operator delete[]
1474 // on this thing, so it doesn't matter if we allocate extra space or not.
1475 if (ops.isAmbiguous()) return false;
1476
Richard Smithb2f0f052016-10-10 18:54:32 +00001477 // C++17 [expr.delete]p10:
1478 // If the deallocation functions have class scope, the one without a
1479 // parameter of type std::size_t is selected.
1480 auto Best = resolveDeallocationOverload(
1481 S, ops, /*WantSize*/false,
1482 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1483 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001484}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001485
Sebastian Redld74dd492012-02-12 18:41:05 +00001486/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001487///
Sebastian Redld74dd492012-02-12 18:41:05 +00001488/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001489/// @code new (memory) int[size][4] @endcode
1490/// or
1491/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001492///
1493/// \param StartLoc The first location of the expression.
1494/// \param UseGlobal True if 'new' was prefixed with '::'.
1495/// \param PlacementLParen Opening paren of the placement arguments.
1496/// \param PlacementArgs Placement new arguments.
1497/// \param PlacementRParen Closing paren of the placement arguments.
1498/// \param TypeIdParens If the type is in parens, the source range.
1499/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001500/// \param Initializer The initializing expression or initializer-list, or null
1501/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001502ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001503Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001504 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001506 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001507 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001508
Craig Topperc3ec1492014-05-26 06:22:03 +00001509 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001510 // If the specified type is an array, unwrap it and save the expression.
1511 if (D.getNumTypeObjects() > 0 &&
1512 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001513 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001514 if (TypeContainsAuto)
1515 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1516 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001517 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001518 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1519 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001520 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001521 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1522 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001523
Sebastian Redl351bb782008-12-02 14:43:59 +00001524 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001525 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001526 }
1527
Douglas Gregor73341c42009-09-11 00:18:58 +00001528 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001529 if (ArraySize) {
1530 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001531 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1532 break;
1533
1534 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1535 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001536 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001537 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001538 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1539 // shall be a converted constant expression (5.19) of type std::size_t
1540 // and shall evaluate to a strictly positive value.
1541 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1542 assert(IntWidth && "Builtin type of size 0?");
1543 llvm::APSInt Value(IntWidth);
1544 Array.NumElts
1545 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1546 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001547 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001548 } else {
1549 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001550 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001551 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001552 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001553 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001554 if (!Array.NumElts)
1555 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001556 }
1557 }
1558 }
1559 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001560
Craig Topperc3ec1492014-05-26 06:22:03 +00001561 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001562 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001563 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001564 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565
Sebastian Redl6047f072012-02-16 12:22:20 +00001566 SourceRange DirectInitRange;
Serge Pavlov38526372016-11-12 15:38:55 +00001567 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001568 DirectInitRange = List->getSourceRange();
Serge Pavlov38526372016-11-12 15:38:55 +00001569 // Handle errors like: new int a({0})
1570 if (List->getNumExprs() == 1 &&
1571 !canInitializeWithParenthesizedList(AllocType))
1572 if (auto IList = dyn_cast<InitListExpr>(List->getExpr(0))) {
1573 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1574 << AllocType << List->getSourceRange()
1575 << FixItHint::CreateRemoval(List->getLocStart())
1576 << FixItHint::CreateRemoval(List->getLocEnd());
1577 DirectInitRange = SourceRange();
1578 Initializer = IList;
1579 }
1580 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001581
David Blaikie7b97aef2012-11-07 00:12:38 +00001582 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001583 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001584 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001585 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001586 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001587 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001588 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001589 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001590 DirectInitRange,
1591 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001592 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001593}
1594
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001595static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1596 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001597 if (!Init)
1598 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001599 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1600 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001601 if (isa<ImplicitValueInitExpr>(Init))
1602 return true;
1603 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1604 return !CCE->isListInitialization() &&
1605 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001606 else if (Style == CXXNewExpr::ListInit) {
1607 assert(isa<InitListExpr>(Init) &&
1608 "Shouldn't create list CXXConstructExprs for arrays.");
1609 return true;
1610 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001611 return false;
1612}
1613
John McCalldadc5752010-08-24 06:29:42 +00001614ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001615Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001616 SourceLocation PlacementLParen,
1617 MultiExprArg PlacementArgs,
1618 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001619 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001620 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001621 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001622 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001623 SourceRange DirectInitRange,
1624 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001625 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001626 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001627 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001628
Sebastian Redl6047f072012-02-16 12:22:20 +00001629 CXXNewExpr::InitializationStyle initStyle;
1630 if (DirectInitRange.isValid()) {
1631 assert(Initializer && "Have parens but no initializer.");
1632 initStyle = CXXNewExpr::CallInit;
1633 } else if (Initializer && isa<InitListExpr>(Initializer))
1634 initStyle = CXXNewExpr::ListInit;
1635 else {
1636 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1637 isa<CXXConstructExpr>(Initializer)) &&
1638 "Initializer expression that cannot have been implicitly created.");
1639 initStyle = CXXNewExpr::NoInit;
1640 }
1641
1642 Expr **Inits = &Initializer;
1643 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001644 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1645 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1646 Inits = List->getExprs();
1647 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001648 }
1649
Richard Smith66204ec2014-03-12 17:42:45 +00001650 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001651 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001652 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001653 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1654 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001655 if (initStyle == CXXNewExpr::ListInit ||
1656 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001657 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001658 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001659 << AllocType << TypeRange);
1660 if (NumInits > 1) {
1661 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001662 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001663 diag::err_auto_new_ctor_multiple_expressions)
1664 << AllocType << TypeRange);
1665 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001666 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001667 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001668 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001669 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001670 << AllocType << Deduce->getType()
1671 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001672 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001673 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001674 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001675 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001676
Douglas Gregorcda95f42010-05-16 16:01:03 +00001677 // Per C++0x [expr.new]p5, the type being constructed may be a
1678 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001679 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001680 if (const ConstantArrayType *Array
1681 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001682 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1683 Context.getSizeType(),
1684 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001685 AllocType = Array->getElementType();
1686 }
1687 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001688
Douglas Gregor3999e152010-10-06 16:00:31 +00001689 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1690 return ExprError();
1691
Craig Topperc3ec1492014-05-26 06:22:03 +00001692 if (initStyle == CXXNewExpr::ListInit &&
1693 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001694 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1695 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001696 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001697 }
1698
Simon Pilgrim75c26882016-09-30 14:25:09 +00001699 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001700 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001701 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1702 AllocType->isObjCLifetimeType()) {
1703 AllocType = Context.getLifetimeQualifiedType(AllocType,
1704 AllocType->getObjCARCImplicitLifetime());
1705 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001706
John McCall31168b02011-06-15 23:02:42 +00001707 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001708
John McCall5e77d762013-04-16 07:28:30 +00001709 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1710 ExprResult result = CheckPlaceholderExpr(ArraySize);
1711 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001712 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001713 }
Richard Smith8dd34252012-02-04 07:07:42 +00001714 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1715 // integral or enumeration type with a non-negative value."
1716 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1717 // enumeration type, or a class type for which a single non-explicit
1718 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001719 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001720 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001721 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001722 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001723 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001724 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001725 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1726
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001727 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1728 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001729
Simon Pilgrim75c26882016-09-30 14:25:09 +00001730 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001731 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001732 // Diagnose the compatibility of this conversion.
1733 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1734 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001735 } else {
1736 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1737 protected:
1738 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001739
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001740 public:
1741 SizeConvertDiagnoser(Expr *ArraySize)
1742 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1743 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001744
1745 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1746 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001747 return S.Diag(Loc, diag::err_array_size_not_integral)
1748 << S.getLangOpts().CPlusPlus11 << T;
1749 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001750
1751 SemaDiagnosticBuilder diagnoseIncomplete(
1752 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001753 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1754 << T << ArraySize->getSourceRange();
1755 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001756
1757 SemaDiagnosticBuilder diagnoseExplicitConv(
1758 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001759 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1760 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001761
1762 SemaDiagnosticBuilder noteExplicitConv(
1763 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001764 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1765 << ConvTy->isEnumeralType() << ConvTy;
1766 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001767
1768 SemaDiagnosticBuilder diagnoseAmbiguous(
1769 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001770 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1771 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001772
1773 SemaDiagnosticBuilder noteAmbiguous(
1774 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001775 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1776 << ConvTy->isEnumeralType() << ConvTy;
1777 }
Richard Smithccc11812013-05-21 19:05:48 +00001778
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001779 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1780 QualType T,
1781 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001782 return S.Diag(Loc,
1783 S.getLangOpts().CPlusPlus11
1784 ? diag::warn_cxx98_compat_array_size_conversion
1785 : diag::ext_array_size_conversion)
1786 << T << ConvTy->isEnumeralType() << ConvTy;
1787 }
1788 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001789
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001790 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1791 SizeDiagnoser);
1792 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001793 if (ConvertedSize.isInvalid())
1794 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001795
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001796 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001797 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001798
Douglas Gregor0bf31402010-10-08 23:50:27 +00001799 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001800 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001801
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001802 // C++98 [expr.new]p7:
1803 // The expression in a direct-new-declarator shall have integral type
1804 // with a non-negative value.
1805 //
Richard Smith0511d232016-10-05 22:41:02 +00001806 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1807 // per CWG1464. Otherwise, if it's not a constant, we must have an
1808 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001809 if (!ArraySize->isValueDependent()) {
1810 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001811 // We've already performed any required implicit conversion to integer or
1812 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001813 // FIXME: Per CWG1464, we are required to check the value prior to
1814 // converting to size_t. This will never find a negative array size in
1815 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001816 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001817 if (Value.isSigned() && Value.isNegative()) {
1818 return ExprError(Diag(ArraySize->getLocStart(),
1819 diag::err_typecheck_negative_array_size)
1820 << ArraySize->getSourceRange());
1821 }
1822
1823 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001824 unsigned ActiveSizeBits =
1825 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001826 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1827 return ExprError(Diag(ArraySize->getLocStart(),
1828 diag::err_array_too_large)
1829 << Value.toString(10)
1830 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001831 }
Richard Smith0511d232016-10-05 22:41:02 +00001832
1833 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001834 } else if (TypeIdParens.isValid()) {
1835 // Can't have dynamic array size when the type-id is in parentheses.
1836 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1837 << ArraySize->getSourceRange()
1838 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1839 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Douglas Gregorf2753b32010-07-13 15:54:32 +00001841 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001842 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
John McCall036f2f62011-05-15 07:14:44 +00001845 // Note that we do *not* convert the argument in any way. It can
1846 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001847 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001848
Craig Topperc3ec1492014-05-26 06:22:03 +00001849 FunctionDecl *OperatorNew = nullptr;
1850 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001851 unsigned Alignment =
1852 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1853 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1854 bool PassAlignment = getLangOpts().AlignedAllocation &&
1855 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001857 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001858 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001859 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001860 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001861 UseGlobal, AllocType, ArraySize, PassAlignment,
1862 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001863 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001864
1865 // If this is an array allocation, compute whether the usual array
1866 // deallocation function for the type has a size_t parameter.
1867 bool UsualArrayDeleteWantsSize = false;
1868 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001869 UsualArrayDeleteWantsSize =
1870 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001871
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001872 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001873 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001875 OperatorNew->getType()->getAs<FunctionProtoType>();
1876 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1877 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878
Richard Smithd6f9e732014-05-13 19:56:21 +00001879 // We've already converted the placement args, just fill in any default
1880 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001881 // argument. Skip the second parameter too if we're passing in the
1882 // alignment; we've already filled it in.
1883 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1884 PassAlignment ? 2 : 1, PlacementArgs,
1885 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001886 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001888 if (!AllPlaceArgs.empty())
1889 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001890
Richard Smithd6f9e732014-05-13 19:56:21 +00001891 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001892 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001893
1894 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Richard Smithb2f0f052016-10-10 18:54:32 +00001896 // Warn if the type is over-aligned and is being allocated by (unaligned)
1897 // global operator new.
1898 if (PlacementArgs.empty() && !PassAlignment &&
1899 (OperatorNew->isImplicit() ||
1900 (OperatorNew->getLocStart().isValid() &&
1901 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1902 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001903 Diag(StartLoc, diag::warn_overaligned_type)
1904 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001905 << unsigned(Alignment / Context.getCharWidth())
1906 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001907 }
1908 }
1909
Sebastian Redl6047f072012-02-16 12:22:20 +00001910 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001911 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1912 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001913 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1914 SourceRange InitRange(Inits[0]->getLocStart(),
1915 Inits[NumInits - 1]->getLocEnd());
1916 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1917 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001918 }
1919
Richard Smithdd2ca572012-11-26 08:32:48 +00001920 // If we can perform the initialization, and we've not already done so,
1921 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001922 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001923 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001924 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001925 // The type we initialize is the complete type, including the array bound.
1926 QualType InitType;
1927 if (KnownArraySize)
1928 InitType = Context.getConstantArrayType(
1929 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1930 *KnownArraySize),
1931 ArrayType::Normal, 0);
1932 else if (ArraySize)
1933 InitType =
1934 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1935 else
1936 InitType = AllocType;
1937
Sebastian Redld74dd492012-02-12 18:41:05 +00001938 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001939 // A new-expression that creates an object of type T initializes that
1940 // object as follows:
1941 InitializationKind Kind
1942 // - If the new-initializer is omitted, the object is default-
1943 // initialized (8.5); if no initialization is performed,
1944 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001945 = initStyle == CXXNewExpr::NoInit
1946 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001948 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001949 : initStyle == CXXNewExpr::ListInit
1950 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1951 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1952 DirectInitRange.getBegin(),
1953 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Douglas Gregor85dabae2009-12-16 01:38:02 +00001955 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001956 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001957 InitializationSequence InitSeq(*this, Entity, Kind,
1958 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001960 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001961 if (FullInit.isInvalid())
1962 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Sebastian Redl6047f072012-02-16 12:22:20 +00001964 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1965 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001966 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001967 if (CXXBindTemporaryExpr *Binder =
1968 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001969 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001971 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Douglas Gregor6642ca22010-02-26 05:06:18 +00001974 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001975 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001976 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1977 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001978 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001979 }
1980 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001981 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1982 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001983 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001984 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001985
John McCall928a2572011-07-13 20:12:57 +00001986 // C++0x [expr.new]p17:
1987 // If the new expression creates an array of objects of class type,
1988 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001989 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1990 if (ArraySize && !BaseAllocType->isDependentType()) {
1991 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1992 if (CXXDestructorDecl *dtor = LookupDestructor(
1993 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1994 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001995 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00001996 PDiag(diag::err_access_dtor)
1997 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001998 if (DiagnoseUseOfDecl(dtor, StartLoc))
1999 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002000 }
John McCall928a2572011-07-13 20:12:57 +00002001 }
2002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002004 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002005 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002006 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2007 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2008 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002009}
2010
Sebastian Redl6047f072012-02-16 12:22:20 +00002011/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002012/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002013bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002014 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002015 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2016 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002017 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002018 return Diag(Loc, diag::err_bad_new_type)
2019 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002020 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002021 return Diag(Loc, diag::err_bad_new_type)
2022 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002023 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002024 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002025 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002026 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002027 diag::err_allocation_of_abstract_type))
2028 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002029 else if (AllocType->isVariablyModifiedType())
2030 return Diag(Loc, diag::err_variably_modified_new_type)
2031 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002032 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2033 return Diag(Loc, diag::err_address_space_qualified_new)
2034 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002035 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002036 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2037 QualType BaseAllocType = Context.getBaseElementType(AT);
2038 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2039 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002040 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002041 << BaseAllocType;
2042 }
2043 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002044
Sebastian Redlbd150f42008-11-21 19:14:01 +00002045 return false;
2046}
2047
Richard Smithb2f0f052016-10-10 18:54:32 +00002048static bool
2049resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2050 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2051 FunctionDecl *&Operator,
2052 OverloadCandidateSet *AlignedCandidates = nullptr,
2053 Expr *AlignArg = nullptr) {
2054 OverloadCandidateSet Candidates(R.getNameLoc(),
2055 OverloadCandidateSet::CSK_Normal);
2056 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2057 Alloc != AllocEnd; ++Alloc) {
2058 // Even member operator new/delete are implicitly treated as
2059 // static, so don't use AddMemberCandidate.
2060 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2061
2062 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2063 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2064 /*ExplicitTemplateArgs=*/nullptr, Args,
2065 Candidates,
2066 /*SuppressUserConversions=*/false);
2067 continue;
2068 }
2069
2070 FunctionDecl *Fn = cast<FunctionDecl>(D);
2071 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2072 /*SuppressUserConversions=*/false);
2073 }
2074
2075 // Do the resolution.
2076 OverloadCandidateSet::iterator Best;
2077 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2078 case OR_Success: {
2079 // Got one!
2080 FunctionDecl *FnDecl = Best->Function;
2081 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2082 Best->FoundDecl) == Sema::AR_inaccessible)
2083 return true;
2084
2085 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002086 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002087 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002088
Richard Smithb2f0f052016-10-10 18:54:32 +00002089 case OR_No_Viable_Function:
2090 // C++17 [expr.new]p13:
2091 // If no matching function is found and the allocated object type has
2092 // new-extended alignment, the alignment argument is removed from the
2093 // argument list, and overload resolution is performed again.
2094 if (PassAlignment) {
2095 PassAlignment = false;
2096 AlignArg = Args[1];
2097 Args.erase(Args.begin() + 1);
2098 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2099 Operator, &Candidates, AlignArg);
2100 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002101
Richard Smithb2f0f052016-10-10 18:54:32 +00002102 // MSVC will fall back on trying to find a matching global operator new
2103 // if operator new[] cannot be found. Also, MSVC will leak by not
2104 // generating a call to operator delete or operator delete[], but we
2105 // will not replicate that bug.
2106 // FIXME: Find out how this interacts with the std::align_val_t fallback
2107 // once MSVC implements it.
2108 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2109 S.Context.getLangOpts().MSVCCompat) {
2110 R.clear();
2111 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2112 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2113 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2114 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2115 Operator, nullptr);
2116 }
Richard Smith1cdec012013-09-29 04:40:38 +00002117
Richard Smithb2f0f052016-10-10 18:54:32 +00002118 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2119 << R.getLookupName() << Range;
2120
2121 // If we have aligned candidates, only note the align_val_t candidates
2122 // from AlignedCandidates and the non-align_val_t candidates from
2123 // Candidates.
2124 if (AlignedCandidates) {
2125 auto IsAligned = [](OverloadCandidate &C) {
2126 return C.Function->getNumParams() > 1 &&
2127 C.Function->getParamDecl(1)->getType()->isAlignValT();
2128 };
2129 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2130
2131 // This was an overaligned allocation, so list the aligned candidates
2132 // first.
2133 Args.insert(Args.begin() + 1, AlignArg);
2134 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2135 R.getNameLoc(), IsAligned);
2136 Args.erase(Args.begin() + 1);
2137 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2138 IsUnaligned);
2139 } else {
2140 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2141 }
Richard Smith1cdec012013-09-29 04:40:38 +00002142 return true;
2143
Richard Smithb2f0f052016-10-10 18:54:32 +00002144 case OR_Ambiguous:
2145 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2146 << R.getLookupName() << Range;
2147 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2148 return true;
2149
2150 case OR_Deleted: {
2151 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2152 << Best->Function->isDeleted()
2153 << R.getLookupName()
2154 << S.getDeletedOrUnavailableSuffix(Best->Function)
2155 << Range;
2156 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2157 return true;
2158 }
2159 }
2160 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002161}
2162
Richard Smithb2f0f052016-10-10 18:54:32 +00002163
Sebastian Redlfaf68082008-12-03 20:26:15 +00002164/// FindAllocationFunctions - Finds the overloads of operator new and delete
2165/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002166bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2167 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002168 bool IsArray, bool &PassAlignment,
2169 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002170 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002171 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002172 // --- Choosing an allocation function ---
2173 // C++ 5.3.4p8 - 14 & 18
2174 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2175 // in the scope of the allocated class.
2176 // 2) If an array size is given, look for operator new[], else look for
2177 // operator new.
2178 // 3) The first argument is always size_t. Append the arguments from the
2179 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002180
Richard Smithb2f0f052016-10-10 18:54:32 +00002181 SmallVector<Expr*, 8> AllocArgs;
2182 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2183
2184 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002185 // FIXME: Should the Sema create the expression and embed it in the syntax
2186 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002187 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002188 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002189 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002190 Context.getSizeType(),
2191 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002192 AllocArgs.push_back(&Size);
2193
2194 QualType AlignValT = Context.VoidTy;
2195 if (PassAlignment) {
2196 DeclareGlobalNewDelete();
2197 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2198 }
2199 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2200 if (PassAlignment)
2201 AllocArgs.push_back(&Align);
2202
2203 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002204
Douglas Gregor6642ca22010-02-26 05:06:18 +00002205 // C++ [expr.new]p8:
2206 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002207 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002208 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002209 // type, the allocation function's name is operator new[] and the
2210 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002211 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002212 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002213
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002214 QualType AllocElemType = Context.getBaseElementType(AllocType);
2215
Richard Smithb2f0f052016-10-10 18:54:32 +00002216 // Find the allocation function.
2217 {
2218 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2219
2220 // C++1z [expr.new]p9:
2221 // If the new-expression begins with a unary :: operator, the allocation
2222 // function's name is looked up in the global scope. Otherwise, if the
2223 // allocated type is a class type T or array thereof, the allocation
2224 // function's name is looked up in the scope of T.
2225 if (AllocElemType->isRecordType() && !UseGlobal)
2226 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2227
2228 // We can see ambiguity here if the allocation function is found in
2229 // multiple base classes.
2230 if (R.isAmbiguous())
2231 return true;
2232
2233 // If this lookup fails to find the name, or if the allocated type is not
2234 // a class type, the allocation function's name is looked up in the
2235 // global scope.
2236 if (R.empty())
2237 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2238
2239 assert(!R.empty() && "implicitly declared allocation functions not found");
2240 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2241
2242 // We do our own custom access checks below.
2243 R.suppressDiagnostics();
2244
2245 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2246 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002247 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002248 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002249
Richard Smithb2f0f052016-10-10 18:54:32 +00002250 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002251 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002252 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002253 return false;
2254 }
2255
Richard Smithb2f0f052016-10-10 18:54:32 +00002256 // Note, the name of OperatorNew might have been changed from array to
2257 // non-array by resolveAllocationOverload.
2258 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2259 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2260 ? OO_Array_Delete
2261 : OO_Delete);
2262
Douglas Gregor6642ca22010-02-26 05:06:18 +00002263 // C++ [expr.new]p19:
2264 //
2265 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002266 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002267 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002268 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002269 // the scope of T. If this lookup fails to find the name, or if
2270 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002271 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002272 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002273 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002274 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002275 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002276 LookupQualifiedName(FoundDelete, RD);
2277 }
John McCallfb6f5262010-03-18 08:19:33 +00002278 if (FoundDelete.isAmbiguous())
2279 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002280
Richard Smithb2f0f052016-10-10 18:54:32 +00002281 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002282 if (FoundDelete.empty()) {
2283 DeclareGlobalNewDelete();
2284 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2285 }
2286
2287 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002288
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002289 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002290
John McCalld3be2c82010-09-14 21:34:24 +00002291 // Whether we're looking for a placement operator delete is dictated
2292 // by whether we selected a placement operator new, not by whether
2293 // we had explicit placement arguments. This matters for things like
2294 // struct A { void *operator new(size_t, int = 0); ... };
2295 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002296 //
2297 // We don't have any definition for what a "placement allocation function"
2298 // is, but we assume it's any allocation function whose
2299 // parameter-declaration-clause is anything other than (size_t).
2300 //
2301 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2302 // This affects whether an exception from the constructor of an overaligned
2303 // type uses the sized or non-sized form of aligned operator delete.
2304 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2305 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002306
2307 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002308 // C++ [expr.new]p20:
2309 // A declaration of a placement deallocation function matches the
2310 // declaration of a placement allocation function if it has the
2311 // same number of parameters and, after parameter transformations
2312 // (8.3.5), all parameter types except the first are
2313 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002314 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002315 // To perform this comparison, we compute the function type that
2316 // the deallocation function should have, and use that type both
2317 // for template argument deduction and for comparison purposes.
2318 QualType ExpectedFunctionType;
2319 {
2320 const FunctionProtoType *Proto
2321 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002322
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002323 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002325 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2326 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002327
John McCalldb40c7f2010-12-14 08:05:40 +00002328 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002329 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002330 EPI.Variadic = Proto->isVariadic();
2331
Douglas Gregor6642ca22010-02-26 05:06:18 +00002332 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002333 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002334 }
2335
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002336 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002337 DEnd = FoundDelete.end();
2338 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002339 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002340 if (FunctionTemplateDecl *FnTmpl =
2341 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002342 // Perform template argument deduction to try to match the
2343 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002344 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002345 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2346 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002347 continue;
2348 } else
2349 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2350
Richard Smithbaa47832016-12-01 02:11:49 +00002351 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2352 ExpectedFunctionType,
2353 /*AdjustExcpetionSpec*/true),
2354 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002355 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002356 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002357
Richard Smithb2f0f052016-10-10 18:54:32 +00002358 if (getLangOpts().CUDA)
2359 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2360 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002361 // C++1y [expr.new]p22:
2362 // For a non-placement allocation function, the normal deallocation
2363 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002364 //
2365 // Per [expr.delete]p10, this lookup prefers a member operator delete
2366 // without a size_t argument, but prefers a non-member operator delete
2367 // with a size_t where possible (which it always is in this case).
2368 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2369 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2370 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2371 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2372 &BestDeallocFns);
2373 if (Selected)
2374 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2375 else {
2376 // If we failed to select an operator, all remaining functions are viable
2377 // but ambiguous.
2378 for (auto Fn : BestDeallocFns)
2379 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002380 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002381 }
2382
2383 // C++ [expr.new]p20:
2384 // [...] If the lookup finds a single matching deallocation
2385 // function, that function will be called; otherwise, no
2386 // deallocation function will be called.
2387 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002388 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002389
Richard Smithb2f0f052016-10-10 18:54:32 +00002390 // C++1z [expr.new]p23:
2391 // If the lookup finds a usual deallocation function (3.7.4.2)
2392 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002393 // as a placement deallocation function, would have been
2394 // selected as a match for the allocation function, the program
2395 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002396 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002397 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002398 UsualDeallocFnInfo Info(*this,
2399 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002400 // Core issue, per mail to core reflector, 2016-10-09:
2401 // If this is a member operator delete, and there is a corresponding
2402 // non-sized member operator delete, this isn't /really/ a sized
2403 // deallocation function, it just happens to have a size_t parameter.
2404 bool IsSizedDelete = Info.HasSizeT;
2405 if (IsSizedDelete && !FoundGlobalDelete) {
2406 auto NonSizedDelete =
2407 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2408 /*WantAlign*/Info.HasAlignValT);
2409 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2410 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2411 IsSizedDelete = false;
2412 }
2413
2414 if (IsSizedDelete) {
2415 SourceRange R = PlaceArgs.empty()
2416 ? SourceRange()
2417 : SourceRange(PlaceArgs.front()->getLocStart(),
2418 PlaceArgs.back()->getLocEnd());
2419 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2420 if (!OperatorDelete->isImplicit())
2421 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2422 << DeleteName;
2423 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002424 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002425
2426 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2427 Matches[0].first);
2428 } else if (!Matches.empty()) {
2429 // We found multiple suitable operators. Per [expr.new]p20, that means we
2430 // call no 'operator delete' function, but we should at least warn the user.
2431 // FIXME: Suppress this warning if the construction cannot throw.
2432 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2433 << DeleteName << AllocElemType;
2434
2435 for (auto &Match : Matches)
2436 Diag(Match.second->getLocation(),
2437 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002438 }
2439
Sebastian Redlfaf68082008-12-03 20:26:15 +00002440 return false;
2441}
2442
2443/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2444/// delete. These are:
2445/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002446/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002447/// void* operator new(std::size_t) throw(std::bad_alloc);
2448/// void* operator new[](std::size_t) throw(std::bad_alloc);
2449/// void operator delete(void *) throw();
2450/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002451/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002452/// void* operator new(std::size_t);
2453/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002454/// void operator delete(void *) noexcept;
2455/// void operator delete[](void *) noexcept;
2456/// // C++1y:
2457/// void* operator new(std::size_t);
2458/// void* operator new[](std::size_t);
2459/// void operator delete(void *) noexcept;
2460/// void operator delete[](void *) noexcept;
2461/// void operator delete(void *, std::size_t) noexcept;
2462/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002463/// @endcode
2464/// Note that the placement and nothrow forms of new are *not* implicitly
2465/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002466void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002467 if (GlobalNewDeleteDeclared)
2468 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002469
Douglas Gregor87f54062009-09-15 22:30:29 +00002470 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471 // [...] The following allocation and deallocation functions (18.4) are
2472 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002473 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002474 //
Sebastian Redl37588092011-03-14 18:08:30 +00002475 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002476 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002477 // void* operator new[](std::size_t) throw(std::bad_alloc);
2478 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002479 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002480 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002481 // void* operator new(std::size_t);
2482 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002483 // void operator delete(void*) noexcept;
2484 // void operator delete[](void*) noexcept;
2485 // C++1y:
2486 // void* operator new(std::size_t);
2487 // void* operator new[](std::size_t);
2488 // void operator delete(void*) noexcept;
2489 // void operator delete[](void*) noexcept;
2490 // void operator delete(void*, std::size_t) noexcept;
2491 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002492 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002493 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002494 // new, operator new[], operator delete, operator delete[].
2495 //
2496 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2497 // "std" or "bad_alloc" as necessary to form the exception specification.
2498 // However, we do not make these implicit declarations visible to name
2499 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002500 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002501 // The "std::bad_alloc" class has not yet been declared, so build it
2502 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002503 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2504 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002505 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002507 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002508 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002509 }
Richard Smith59139022016-09-30 22:41:36 +00002510 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002511 // The "std::align_val_t" enum class has not yet been declared, so build it
2512 // implicitly.
2513 auto *AlignValT = EnumDecl::Create(
2514 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2515 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2516 AlignValT->setIntegerType(Context.getSizeType());
2517 AlignValT->setPromotionType(Context.getSizeType());
2518 AlignValT->setImplicit(true);
2519 StdAlignValT = AlignValT;
2520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002521
Sebastian Redlfaf68082008-12-03 20:26:15 +00002522 GlobalNewDeleteDeclared = true;
2523
2524 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2525 QualType SizeT = Context.getSizeType();
2526
Richard Smith96269c52016-09-29 22:49:46 +00002527 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2528 QualType Return, QualType Param) {
2529 llvm::SmallVector<QualType, 3> Params;
2530 Params.push_back(Param);
2531
2532 // Create up to four variants of the function (sized/aligned).
2533 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2534 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002535 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002536
2537 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2538 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2539 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002540 if (Sized)
2541 Params.push_back(SizeT);
2542
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002543 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002544 if (Aligned)
2545 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2546
2547 DeclareGlobalAllocationFunction(
2548 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2549
2550 if (Aligned)
2551 Params.pop_back();
2552 }
2553 }
2554 };
2555
2556 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2557 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2558 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2559 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002560}
2561
2562/// DeclareGlobalAllocationFunction - Declares a single implicit global
2563/// allocation function if it doesn't already exist.
2564void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002565 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002566 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002567 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2568
2569 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002570 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2571 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2572 Alloc != AllocEnd; ++Alloc) {
2573 // Only look at non-template functions, as it is the predefined,
2574 // non-templated allocation function we are trying to declare here.
2575 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002576 if (Func->getNumParams() == Params.size()) {
2577 llvm::SmallVector<QualType, 3> FuncParams;
2578 for (auto *P : Func->parameters())
2579 FuncParams.push_back(
2580 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2581 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002582 // Make the function visible to name lookup, even if we found it in
2583 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002584 // allocation function, or is suppressing that function.
2585 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002586 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002587 }
Chandler Carruth93538422010-02-03 11:02:14 +00002588 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002589 }
2590 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002591
Richard Smithc015bc22014-02-07 22:39:53 +00002592 FunctionProtoType::ExtProtoInfo EPI;
2593
Richard Smithf8b417c2014-02-08 00:42:45 +00002594 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002596 = (Name.getCXXOverloadedOperator() == OO_New ||
2597 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002598 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002599 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002600 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002601 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002602 EPI.ExceptionSpec.Type = EST_Dynamic;
2603 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002604 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002605 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002606 EPI.ExceptionSpec =
2607 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609
Artem Belevich07db5cf2016-10-21 20:34:05 +00002610 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2611 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2612 FunctionDecl *Alloc = FunctionDecl::Create(
2613 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2614 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2615 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002616
Artem Belevich07db5cf2016-10-21 20:34:05 +00002617 // Implicit sized deallocation functions always have default visibility.
2618 Alloc->addAttr(
2619 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620
Artem Belevich07db5cf2016-10-21 20:34:05 +00002621 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2622 for (QualType T : Params) {
2623 ParamDecls.push_back(ParmVarDecl::Create(
2624 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2625 /*TInfo=*/nullptr, SC_None, nullptr));
2626 ParamDecls.back()->setImplicit();
2627 }
2628 Alloc->setParams(ParamDecls);
2629 if (ExtraAttr)
2630 Alloc->addAttr(ExtraAttr);
2631 Context.getTranslationUnitDecl()->addDecl(Alloc);
2632 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2633 };
2634
2635 if (!LangOpts.CUDA)
2636 CreateAllocationFunctionDecl(nullptr);
2637 else {
2638 // Host and device get their own declaration so each can be
2639 // defined or re-declared independently.
2640 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2641 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002642 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002643}
2644
Richard Smith1cdec012013-09-29 04:40:38 +00002645FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2646 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002647 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002648 DeclarationName Name) {
2649 DeclareGlobalNewDelete();
2650
2651 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2652 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2653
Richard Smithb2f0f052016-10-10 18:54:32 +00002654 // FIXME: It's possible for this to result in ambiguity, through a
2655 // user-declared variadic operator delete or the enable_if attribute. We
2656 // should probably not consider those cases to be usual deallocation
2657 // functions. But for now we just make an arbitrary choice in that case.
2658 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2659 Overaligned);
2660 assert(Result.FD && "operator delete missing from global scope?");
2661 return Result.FD;
2662}
Richard Smith1cdec012013-09-29 04:40:38 +00002663
Richard Smithb2f0f052016-10-10 18:54:32 +00002664FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2665 CXXRecordDecl *RD) {
2666 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002667
Richard Smithb2f0f052016-10-10 18:54:32 +00002668 FunctionDecl *OperatorDelete = nullptr;
2669 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2670 return nullptr;
2671 if (OperatorDelete)
2672 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002673
Richard Smithb2f0f052016-10-10 18:54:32 +00002674 // If there's no class-specific operator delete, look up the global
2675 // non-array delete.
2676 return FindUsualDeallocationFunction(
2677 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2678 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002679}
2680
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002681bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2682 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002683 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002684 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002685 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002686 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002687
John McCall27b18f82009-11-17 02:14:36 +00002688 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002689 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002690
Chandler Carruthb6f99172010-06-28 00:30:51 +00002691 Found.suppressDiagnostics();
2692
Richard Smithb2f0f052016-10-10 18:54:32 +00002693 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002694
Richard Smithb2f0f052016-10-10 18:54:32 +00002695 // C++17 [expr.delete]p10:
2696 // If the deallocation functions have class scope, the one without a
2697 // parameter of type std::size_t is selected.
2698 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2699 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2700 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002701
Richard Smithb2f0f052016-10-10 18:54:32 +00002702 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002703 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002704 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002705
Richard Smithb2f0f052016-10-10 18:54:32 +00002706 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002707 if (Operator->isDeleted()) {
2708 if (Diagnose) {
2709 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002710 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002711 }
2712 return true;
2713 }
2714
Richard Smith921bd202012-02-26 09:11:52 +00002715 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002716 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002717 return true;
2718
John McCall66a87592010-08-04 00:31:26 +00002719 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002720 }
John McCall66a87592010-08-04 00:31:26 +00002721
Richard Smithb2f0f052016-10-10 18:54:32 +00002722 // We found multiple suitable operators; complain about the ambiguity.
2723 // FIXME: The standard doesn't say to do this; it appears that the intent
2724 // is that this should never happen.
2725 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002726 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002727 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2728 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002729 for (auto &Match : Matches)
2730 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002731 }
John McCall66a87592010-08-04 00:31:26 +00002732 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002733 }
2734
2735 // We did find operator delete/operator delete[] declarations, but
2736 // none of them were suitable.
2737 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002738 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002739 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2740 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002741
Richard Smithb2f0f052016-10-10 18:54:32 +00002742 for (NamedDecl *D : Found)
2743 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002744 diag::note_member_declared_here) << Name;
2745 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002746 return true;
2747 }
2748
Craig Topperc3ec1492014-05-26 06:22:03 +00002749 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002750 return false;
2751}
2752
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002753namespace {
2754/// \brief Checks whether delete-expression, and new-expression used for
2755/// initializing deletee have the same array form.
2756class MismatchingNewDeleteDetector {
2757public:
2758 enum MismatchResult {
2759 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2760 NoMismatch,
2761 /// Indicates that variable is initialized with mismatching form of \a new.
2762 VarInitMismatches,
2763 /// Indicates that member is initialized with mismatching form of \a new.
2764 MemberInitMismatches,
2765 /// Indicates that 1 or more constructors' definitions could not been
2766 /// analyzed, and they will be checked again at the end of translation unit.
2767 AnalyzeLater
2768 };
2769
2770 /// \param EndOfTU True, if this is the final analysis at the end of
2771 /// translation unit. False, if this is the initial analysis at the point
2772 /// delete-expression was encountered.
2773 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002774 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002775 HasUndefinedConstructors(false) {}
2776
2777 /// \brief Checks whether pointee of a delete-expression is initialized with
2778 /// matching form of new-expression.
2779 ///
2780 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2781 /// point where delete-expression is encountered, then a warning will be
2782 /// issued immediately. If return value is \c AnalyzeLater at the point where
2783 /// delete-expression is seen, then member will be analyzed at the end of
2784 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2785 /// couldn't be analyzed. If at least one constructor initializes the member
2786 /// with matching type of new, the return value is \c NoMismatch.
2787 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2788 /// \brief Analyzes a class member.
2789 /// \param Field Class member to analyze.
2790 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2791 /// for deleting the \p Field.
2792 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002793 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002794 /// List of mismatching new-expressions used for initialization of the pointee
2795 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2796 /// Indicates whether delete-expression was in array form.
2797 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002798
2799private:
2800 const bool EndOfTU;
2801 /// \brief Indicates that there is at least one constructor without body.
2802 bool HasUndefinedConstructors;
2803 /// \brief Returns \c CXXNewExpr from given initialization expression.
2804 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002805 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002806 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2807 /// \brief Returns whether member is initialized with mismatching form of
2808 /// \c new either by the member initializer or in-class initialization.
2809 ///
2810 /// If bodies of all constructors are not visible at the end of translation
2811 /// unit or at least one constructor initializes member with the matching
2812 /// form of \c new, mismatch cannot be proven, and this function will return
2813 /// \c NoMismatch.
2814 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2815 /// \brief Returns whether variable is initialized with mismatching form of
2816 /// \c new.
2817 ///
2818 /// If variable is initialized with matching form of \c new or variable is not
2819 /// initialized with a \c new expression, this function will return true.
2820 /// If variable is initialized with mismatching form of \c new, returns false.
2821 /// \param D Variable to analyze.
2822 bool hasMatchingVarInit(const DeclRefExpr *D);
2823 /// \brief Checks whether the constructor initializes pointee with mismatching
2824 /// form of \c new.
2825 ///
2826 /// Returns true, if member is initialized with matching form of \c new in
2827 /// member initializer list. Returns false, if member is initialized with the
2828 /// matching form of \c new in this constructor's initializer or given
2829 /// constructor isn't defined at the point where delete-expression is seen, or
2830 /// member isn't initialized by the constructor.
2831 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2832 /// \brief Checks whether member is initialized with matching form of
2833 /// \c new in member initializer list.
2834 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2835 /// Checks whether member is initialized with mismatching form of \c new by
2836 /// in-class initializer.
2837 MismatchResult analyzeInClassInitializer();
2838};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002839}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002840
2841MismatchingNewDeleteDetector::MismatchResult
2842MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2843 NewExprs.clear();
2844 assert(DE && "Expected delete-expression");
2845 IsArrayForm = DE->isArrayForm();
2846 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2847 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2848 return analyzeMemberExpr(ME);
2849 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2850 if (!hasMatchingVarInit(D))
2851 return VarInitMismatches;
2852 }
2853 return NoMismatch;
2854}
2855
2856const CXXNewExpr *
2857MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2858 assert(E != nullptr && "Expected a valid initializer expression");
2859 E = E->IgnoreParenImpCasts();
2860 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2861 if (ILE->getNumInits() == 1)
2862 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2863 }
2864
2865 return dyn_cast_or_null<const CXXNewExpr>(E);
2866}
2867
2868bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2869 const CXXCtorInitializer *CI) {
2870 const CXXNewExpr *NE = nullptr;
2871 if (Field == CI->getMember() &&
2872 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2873 if (NE->isArray() == IsArrayForm)
2874 return true;
2875 else
2876 NewExprs.push_back(NE);
2877 }
2878 return false;
2879}
2880
2881bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2882 const CXXConstructorDecl *CD) {
2883 if (CD->isImplicit())
2884 return false;
2885 const FunctionDecl *Definition = CD;
2886 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2887 HasUndefinedConstructors = true;
2888 return EndOfTU;
2889 }
2890 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2891 if (hasMatchingNewInCtorInit(CI))
2892 return true;
2893 }
2894 return false;
2895}
2896
2897MismatchingNewDeleteDetector::MismatchResult
2898MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2899 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002900 const Expr *InitExpr = Field->getInClassInitializer();
2901 if (!InitExpr)
2902 return EndOfTU ? NoMismatch : AnalyzeLater;
2903 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002904 if (NE->isArray() != IsArrayForm) {
2905 NewExprs.push_back(NE);
2906 return MemberInitMismatches;
2907 }
2908 }
2909 return NoMismatch;
2910}
2911
2912MismatchingNewDeleteDetector::MismatchResult
2913MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2914 bool DeleteWasArrayForm) {
2915 assert(Field != nullptr && "Analysis requires a valid class member.");
2916 this->Field = Field;
2917 IsArrayForm = DeleteWasArrayForm;
2918 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2919 for (const auto *CD : RD->ctors()) {
2920 if (hasMatchingNewInCtor(CD))
2921 return NoMismatch;
2922 }
2923 if (HasUndefinedConstructors)
2924 return EndOfTU ? NoMismatch : AnalyzeLater;
2925 if (!NewExprs.empty())
2926 return MemberInitMismatches;
2927 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2928 : NoMismatch;
2929}
2930
2931MismatchingNewDeleteDetector::MismatchResult
2932MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2933 assert(ME != nullptr && "Expected a member expression");
2934 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2935 return analyzeField(F, IsArrayForm);
2936 return NoMismatch;
2937}
2938
2939bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2940 const CXXNewExpr *NE = nullptr;
2941 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2942 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2943 NE->isArray() != IsArrayForm) {
2944 NewExprs.push_back(NE);
2945 }
2946 }
2947 return NewExprs.empty();
2948}
2949
2950static void
2951DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2952 const MismatchingNewDeleteDetector &Detector) {
2953 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2954 FixItHint H;
2955 if (!Detector.IsArrayForm)
2956 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2957 else {
2958 SourceLocation RSquare = Lexer::findLocationAfterToken(
2959 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2960 SemaRef.getLangOpts(), true);
2961 if (RSquare.isValid())
2962 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2963 }
2964 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2965 << Detector.IsArrayForm << H;
2966
2967 for (const auto *NE : Detector.NewExprs)
2968 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2969 << Detector.IsArrayForm;
2970}
2971
2972void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2973 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2974 return;
2975 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2976 switch (Detector.analyzeDeleteExpr(DE)) {
2977 case MismatchingNewDeleteDetector::VarInitMismatches:
2978 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2979 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2980 break;
2981 }
2982 case MismatchingNewDeleteDetector::AnalyzeLater: {
2983 DeleteExprs[Detector.Field].push_back(
2984 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2985 break;
2986 }
2987 case MismatchingNewDeleteDetector::NoMismatch:
2988 break;
2989 }
2990}
2991
2992void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2993 bool DeleteWasArrayForm) {
2994 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2995 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2996 case MismatchingNewDeleteDetector::VarInitMismatches:
2997 llvm_unreachable("This analysis should have been done for class members.");
2998 case MismatchingNewDeleteDetector::AnalyzeLater:
2999 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3000 "translation unit.");
3001 case MismatchingNewDeleteDetector::MemberInitMismatches:
3002 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3003 break;
3004 case MismatchingNewDeleteDetector::NoMismatch:
3005 break;
3006 }
3007}
3008
Sebastian Redlbd150f42008-11-21 19:14:01 +00003009/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3010/// @code ::delete ptr; @endcode
3011/// or
3012/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003013ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003014Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003015 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003016 // C++ [expr.delete]p1:
3017 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003018 // non-explicit conversion function to a pointer type. The result has type
3019 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003020 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003021 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3022
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003023 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003024 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003025 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003026 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003027
John Wiegley01296292011-04-08 18:41:53 +00003028 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003029 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003030 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003031 if (Ex.isInvalid())
3032 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003033
John Wiegley01296292011-04-08 18:41:53 +00003034 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003035
Richard Smithccc11812013-05-21 19:05:48 +00003036 class DeleteConverter : public ContextualImplicitConverter {
3037 public:
3038 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039
Craig Toppere14c0f82014-03-12 04:55:44 +00003040 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003041 // FIXME: If we have an operator T* and an operator void*, we must pick
3042 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003043 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003044 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003045 return true;
3046 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003047 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003048
Richard Smithccc11812013-05-21 19:05:48 +00003049 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003050 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003051 return S.Diag(Loc, diag::err_delete_operand) << T;
3052 }
3053
3054 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003055 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003056 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3057 }
3058
3059 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003060 QualType T,
3061 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003062 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3063 }
3064
3065 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003066 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003067 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3068 << ConvTy;
3069 }
3070
3071 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003072 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003073 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3074 }
3075
3076 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003077 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003078 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3079 << ConvTy;
3080 }
3081
3082 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003083 QualType T,
3084 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003085 llvm_unreachable("conversion functions are permitted");
3086 }
3087 } Converter;
3088
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003089 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003090 if (Ex.isInvalid())
3091 return ExprError();
3092 Type = Ex.get()->getType();
3093 if (!Converter.match(Type))
3094 // FIXME: PerformContextualImplicitConversion should return ExprError
3095 // itself in this case.
3096 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003097
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003098 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003099 QualType PointeeElem = Context.getBaseElementType(Pointee);
3100
3101 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003102 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003103 diag::err_address_space_qualified_delete)
3104 << Pointee.getUnqualifiedType() << AddressSpace;
3105
Craig Topperc3ec1492014-05-26 06:22:03 +00003106 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003107 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003108 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003109 // effectively bans deletion of "void*". However, most compilers support
3110 // this, so we treat it as a warning unless we're in a SFINAE context.
3111 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003112 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003113 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003114 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003115 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003116 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003117 // FIXME: This can result in errors if the definition was imported from a
3118 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003119 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003120 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003121 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3122 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3123 }
3124 }
3125
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003126 if (Pointee->isArrayType() && !ArrayForm) {
3127 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003128 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003129 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003130 ArrayForm = true;
3131 }
3132
Anders Carlssona471db02009-08-16 20:29:29 +00003133 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3134 ArrayForm ? OO_Array_Delete : OO_Delete);
3135
Eli Friedmanae4280f2011-07-26 22:25:31 +00003136 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003137 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003138 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3139 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003140 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141
John McCall284c48f2011-01-27 09:37:56 +00003142 // If we're allocating an array of records, check whether the
3143 // usual operator delete[] has a size_t parameter.
3144 if (ArrayForm) {
3145 // If the user specifically asked to use the global allocator,
3146 // we'll need to do the lookup into the class.
3147 if (UseGlobal)
3148 UsualArrayDeleteWantsSize =
3149 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3150
3151 // Otherwise, the usual operator delete[] should be the
3152 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003153 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003154 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003155 UsualDeallocFnInfo(*this,
3156 DeclAccessPair::make(OperatorDelete, AS_public))
3157 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003158 }
3159
Richard Smitheec915d62012-02-18 04:13:32 +00003160 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003161 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003162 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003163 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003164 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3165 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003166 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003167
Nico Weber5a9259c2016-01-15 21:45:31 +00003168 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3169 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3170 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3171 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
Richard Smithb2f0f052016-10-10 18:54:32 +00003174 if (!OperatorDelete) {
3175 bool IsComplete = isCompleteType(StartLoc, Pointee);
3176 bool CanProvideSize =
3177 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3178 Pointee.isDestructedType());
3179 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3180
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003181 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003182 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3183 Overaligned, DeleteName);
3184 }
Mike Stump11289f42009-09-09 15:08:12 +00003185
Eli Friedmanfa0df832012-02-02 03:46:19 +00003186 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003187
Douglas Gregorfa778132011-02-01 15:50:11 +00003188 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003189 if (PointeeRD) {
3190 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003191 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003192 PDiag(diag::err_access_dtor) << PointeeElem);
3193 }
3194 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003195 }
3196
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003197 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003198 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3199 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003200 AnalyzeDeleteExprMismatch(Result);
3201 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003202}
3203
Nico Weber5a9259c2016-01-15 21:45:31 +00003204void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3205 bool IsDelete, bool CallCanBeVirtual,
3206 bool WarnOnNonAbstractTypes,
3207 SourceLocation DtorLoc) {
3208 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3209 return;
3210
3211 // C++ [expr.delete]p3:
3212 // In the first alternative (delete object), if the static type of the
3213 // object to be deleted is different from its dynamic type, the static
3214 // type shall be a base class of the dynamic type of the object to be
3215 // deleted and the static type shall have a virtual destructor or the
3216 // behavior is undefined.
3217 //
3218 const CXXRecordDecl *PointeeRD = dtor->getParent();
3219 // Note: a final class cannot be derived from, no issue there
3220 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3221 return;
3222
3223 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3224 if (PointeeRD->isAbstract()) {
3225 // If the class is abstract, we warn by default, because we're
3226 // sure the code has undefined behavior.
3227 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3228 << ClassType;
3229 } else if (WarnOnNonAbstractTypes) {
3230 // Otherwise, if this is not an array delete, it's a bit suspect,
3231 // but not necessarily wrong.
3232 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3233 << ClassType;
3234 }
3235 if (!IsDelete) {
3236 std::string TypeStr;
3237 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3238 Diag(DtorLoc, diag::note_delete_non_virtual)
3239 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3240 }
3241}
3242
Richard Smith03a4aa32016-06-23 19:02:52 +00003243Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3244 SourceLocation StmtLoc,
3245 ConditionKind CK) {
3246 ExprResult E =
3247 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3248 if (E.isInvalid())
3249 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003250 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3251 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003252}
3253
Douglas Gregor633caca2009-11-23 23:44:04 +00003254/// \brief Check the use of the given variable as a C++ condition in an if,
3255/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003256ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003257 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003258 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003259 if (ConditionVar->isInvalidDecl())
3260 return ExprError();
3261
Douglas Gregor633caca2009-11-23 23:44:04 +00003262 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263
Douglas Gregor633caca2009-11-23 23:44:04 +00003264 // C++ [stmt.select]p2:
3265 // The declarator shall not specify a function or an array.
3266 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003268 diag::err_invalid_use_of_function_type)
3269 << ConditionVar->getSourceRange());
3270 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003272 diag::err_invalid_use_of_array_type)
3273 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003274
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003275 ExprResult Condition = DeclRefExpr::Create(
3276 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3277 /*enclosing*/ false, ConditionVar->getLocation(),
3278 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003279
Eli Friedmanfa0df832012-02-02 03:46:19 +00003280 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003281
Richard Smith03a4aa32016-06-23 19:02:52 +00003282 switch (CK) {
3283 case ConditionKind::Boolean:
3284 return CheckBooleanCondition(StmtLoc, Condition.get());
3285
Richard Smithb130fe72016-06-23 19:16:49 +00003286 case ConditionKind::ConstexprIf:
3287 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3288
Richard Smith03a4aa32016-06-23 19:02:52 +00003289 case ConditionKind::Switch:
3290 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292
Richard Smith03a4aa32016-06-23 19:02:52 +00003293 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003294}
3295
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003296/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003297ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003298 // C++ 6.4p4:
3299 // The value of a condition that is an initialized declaration in a statement
3300 // other than a switch statement is the value of the declared variable
3301 // implicitly converted to type bool. If that conversion is ill-formed, the
3302 // program is ill-formed.
3303 // The value of a condition that is an expression is the value of the
3304 // expression, implicitly converted to bool.
3305 //
Richard Smithb130fe72016-06-23 19:16:49 +00003306 // FIXME: Return this value to the caller so they don't need to recompute it.
3307 llvm::APSInt Value(/*BitWidth*/1);
3308 return (IsConstexpr && !CondExpr->isValueDependent())
3309 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3310 CCEK_ConstexprIf)
3311 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003312}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003313
3314/// Helper function to determine whether this is the (deprecated) C++
3315/// conversion from a string literal to a pointer to non-const char or
3316/// non-const wchar_t (for narrow and wide string literals,
3317/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003318bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003319Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3320 // Look inside the implicit cast, if it exists.
3321 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3322 From = Cast->getSubExpr();
3323
3324 // A string literal (2.13.4) that is not a wide string literal can
3325 // be converted to an rvalue of type "pointer to char"; a wide
3326 // string literal can be converted to an rvalue of type "pointer
3327 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003328 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003329 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003330 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003331 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003332 // This conversion is considered only when there is an
3333 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003334 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3335 switch (StrLit->getKind()) {
3336 case StringLiteral::UTF8:
3337 case StringLiteral::UTF16:
3338 case StringLiteral::UTF32:
3339 // We don't allow UTF literals to be implicitly converted
3340 break;
3341 case StringLiteral::Ascii:
3342 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3343 ToPointeeType->getKind() == BuiltinType::Char_S);
3344 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003345 return Context.typesAreCompatible(Context.getWideCharType(),
3346 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003347 }
3348 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003349 }
3350
3351 return false;
3352}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003355 SourceLocation CastLoc,
3356 QualType Ty,
3357 CastKind Kind,
3358 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003359 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003360 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003361 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003362 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003363 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003364 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003365 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003366 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
Richard Smith72d74052013-07-20 19:41:36 +00003368 if (S.RequireNonAbstractType(CastLoc, Ty,
3369 diag::err_allocation_of_abstract_type))
3370 return ExprError();
3371
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003372 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003373 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374
Richard Smith5179eb72016-06-28 19:03:57 +00003375 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3376 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003377 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003378 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003379
Richard Smithf8adcdc2014-07-17 05:12:35 +00003380 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003381 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003382 ConstructorArgs, HadMultipleCandidates,
3383 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3384 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003385 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003386 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003388 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
John McCalle3027922010-08-25 11:45:40 +00003391 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003392 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393
Richard Smithd3f2d322015-02-24 21:16:19 +00003394 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003395 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003396 return ExprError();
3397
Douglas Gregora4253922010-04-16 22:17:36 +00003398 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003399 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3400 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003401 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003402 if (Result.isInvalid())
3403 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003404 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003405 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3406 CK_UserDefinedConversion, Result.get(),
3407 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Douglas Gregor668443e2011-01-20 00:18:04 +00003409 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003410 }
3411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412}
Douglas Gregora4253922010-04-16 22:17:36 +00003413
Douglas Gregor5fb53972009-01-14 15:45:31 +00003414/// PerformImplicitConversion - Perform an implicit conversion of the
3415/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003416/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003417/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003418/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003419ExprResult
3420Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003421 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003422 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003423 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003424 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003425 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003426 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3427 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003428 if (Res.isInvalid())
3429 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003430 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003431 break;
John Wiegley01296292011-04-08 18:41:53 +00003432 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003433
Anders Carlsson110b07b2009-09-15 06:28:28 +00003434 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003436 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003437 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003438 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003439 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003440 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003441 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
Anders Carlsson110b07b2009-09-15 06:28:28 +00003443 // If the user-defined conversion is specified by a conversion function,
3444 // the initial standard conversion sequence converts the source type to
3445 // the implicit object parameter of the conversion function.
3446 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003447 } else {
3448 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003449 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003450 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003451 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003453 // initial standard conversion sequence converts the source type to
3454 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003455 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457 }
Richard Smith72d74052013-07-20 19:41:36 +00003458 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003459 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003460 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003461 PerformImplicitConversion(From, BeforeToType,
3462 ICS.UserDefined.Before, AA_Converting,
3463 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003464 if (Res.isInvalid())
3465 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003466 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
3469 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003470 = BuildCXXCastArgument(*this,
3471 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003472 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003473 CastKind, cast<CXXMethodDecl>(FD),
3474 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003475 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003476 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003477
3478 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003479 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003480
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003481 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003482
Richard Smith507840d2011-11-29 22:48:16 +00003483 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3484 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003485 }
John McCall0d1da222010-01-12 00:44:57 +00003486
3487 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003488 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003489 PDiag(diag::err_typecheck_ambiguous_condition)
3490 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003491 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003492
Douglas Gregor39c16d42008-10-24 04:54:22 +00003493 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003494 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003495
3496 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003497 bool Diagnosed =
3498 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3499 From->getType(), From, Action);
3500 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003501 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003502 }
3503
3504 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003505 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003506}
3507
Richard Smith507840d2011-11-29 22:48:16 +00003508/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003509/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003510/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003511/// expression. Flavor is the context in which we're performing this
3512/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003513ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003514Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003515 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003516 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003517 CheckedConversionKind CCK) {
3518 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003519
Mike Stump87c57ac2009-05-16 07:39:55 +00003520 // Overall FIXME: we are recomputing too many types here and doing far too
3521 // much extra work. What this means is that we need to keep track of more
3522 // information that is computed when we try the implicit conversion initially,
3523 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003524 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003525
Douglas Gregor2fe98832008-11-03 19:09:14 +00003526 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003527 // FIXME: When can ToType be a reference type?
3528 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003529 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003530 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003531 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003532 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003533 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003534 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003535 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003536 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3537 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003538 ConstructorArgs, /*HadMultipleCandidates*/ false,
3539 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3540 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003541 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003542 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003543 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3544 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003545 From, /*HadMultipleCandidates*/ false,
3546 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3547 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003548 }
3549
Douglas Gregor980fb162010-04-29 18:24:40 +00003550 // Resolve overloaded function references.
3551 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3552 DeclAccessPair Found;
3553 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3554 true, Found);
3555 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003556 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003557
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003558 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003559 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560
Douglas Gregor980fb162010-04-29 18:24:40 +00003561 From = FixOverloadedFunctionReference(From, Found, Fn);
3562 FromType = From->getType();
3563 }
3564
Richard Smitha23ab512013-05-23 00:30:41 +00003565 // If we're converting to an atomic type, first convert to the corresponding
3566 // non-atomic type.
3567 QualType ToAtomicType;
3568 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3569 ToAtomicType = ToType;
3570 ToType = ToAtomic->getValueType();
3571 }
3572
George Burgess IV8d141e02015-12-14 22:00:49 +00003573 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003574 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003575 switch (SCS.First) {
3576 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003577 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3578 FromType = FromAtomic->getValueType().getUnqualifiedType();
3579 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3580 From, /*BasePath=*/nullptr, VK_RValue);
3581 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003582 break;
3583
Eli Friedman946b7b52012-01-24 22:51:26 +00003584 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003585 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003586 ExprResult FromRes = DefaultLvalueConversion(From);
3587 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003588 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003589 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003590 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003591 }
John McCall34376a62010-12-04 03:47:34 +00003592
Douglas Gregor39c16d42008-10-24 04:54:22 +00003593 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003594 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003595 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003596 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003597 break;
3598
3599 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003600 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003601 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003602 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003603 break;
3604
3605 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003606 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003607 }
3608
Richard Smith507840d2011-11-29 22:48:16 +00003609 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003610 switch (SCS.Second) {
3611 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003612 // C++ [except.spec]p5:
3613 // [For] assignment to and initialization of pointers to functions,
3614 // pointers to member functions, and references to functions: the
3615 // target entity shall allow at least the exceptions allowed by the
3616 // source value in the assignment or initialization.
3617 switch (Action) {
3618 case AA_Assigning:
3619 case AA_Initializing:
3620 // Note, function argument passing and returning are initialization.
3621 case AA_Passing:
3622 case AA_Returning:
3623 case AA_Sending:
3624 case AA_Passing_CFAudited:
3625 if (CheckExceptionSpecCompatibility(From, ToType))
3626 return ExprError();
3627 break;
3628
3629 case AA_Casting:
3630 case AA_Converting:
3631 // Casts and implicit conversions are not initialization, so are not
3632 // checked for exception specification mismatches.
3633 break;
3634 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003635 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003636 break;
3637
3638 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003639 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003640 if (ToType->isBooleanType()) {
3641 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3642 SCS.Second == ICK_Integral_Promotion &&
3643 "only enums with fixed underlying type can promote to bool");
3644 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003645 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003646 } else {
3647 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003648 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003649 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003650 break;
3651
3652 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003653 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003654 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003655 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003656 break;
3657
3658 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003659 case ICK_Complex_Conversion: {
3660 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3661 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3662 CastKind CK;
3663 if (FromEl->isRealFloatingType()) {
3664 if (ToEl->isRealFloatingType())
3665 CK = CK_FloatingComplexCast;
3666 else
3667 CK = CK_FloatingComplexToIntegralComplex;
3668 } else if (ToEl->isRealFloatingType()) {
3669 CK = CK_IntegralComplexToFloatingComplex;
3670 } else {
3671 CK = CK_IntegralComplexCast;
3672 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003673 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003674 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003675 break;
John McCall8cb679e2010-11-15 09:13:47 +00003676 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003677
Douglas Gregor39c16d42008-10-24 04:54:22 +00003678 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003679 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003680 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003681 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003682 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003683 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003684 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003685 break;
3686
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003687 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003688 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003689 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003690 break;
3691
John McCall31168b02011-06-15 23:02:42 +00003692 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003693 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003694 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003695 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003696 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003697 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003698 diag::ext_typecheck_convert_incompatible_pointer)
3699 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003700 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003701 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003702 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003703 diag::ext_typecheck_convert_incompatible_pointer)
3704 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003705 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003706
Douglas Gregor33823722011-06-11 01:09:30 +00003707 if (From->getType()->isObjCObjectPointerType() &&
3708 ToType->isObjCObjectPointerType())
3709 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003710 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003711 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003712 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003713 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003714 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003715 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003716 diag::err_arc_weak_unavailable_assign);
3717 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003718 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003719 diag::err_arc_convesion_of_weak_unavailable)
3720 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003721 << From->getSourceRange();
3722 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003723
John McCall8cb679e2010-11-15 09:13:47 +00003724 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003725 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003726 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003727 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003728
3729 // Make sure we extend blocks if necessary.
3730 // FIXME: doing this here is really ugly.
3731 if (Kind == CK_BlockPointerToObjCPointerCast) {
3732 ExprResult E = From;
3733 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003734 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003735 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003736 if (getLangOpts().ObjCAutoRefCount)
3737 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003738 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003739 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003740 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003743 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003744 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003745 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003746 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003747 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003748 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003749 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003750
3751 // We may not have been able to figure out what this member pointer resolved
3752 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003753 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003754 (void)isCompleteType(From->getExprLoc(), From->getType());
3755 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003756 }
David Majnemerd96b9972014-08-08 00:10:39 +00003757
Richard Smith507840d2011-11-29 22:48:16 +00003758 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003759 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003760 break;
3761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003763 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003764 // Perform half-to-boolean conversion via float.
3765 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003766 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003767 FromType = Context.FloatTy;
3768 }
3769
Richard Smith507840d2011-11-29 22:48:16 +00003770 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003771 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003772 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003773 break;
3774
Douglas Gregor88d292c2010-05-13 16:44:06 +00003775 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003776 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003778 ToType.getNonReferenceType(),
3779 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003781 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003782 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003783 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003784
Richard Smith507840d2011-11-29 22:48:16 +00003785 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3786 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003787 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003788 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003789 }
3790
Douglas Gregor46188682010-05-18 22:42:18 +00003791 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003792 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003793 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003794 break;
3795
George Burgess IVdf1ed002016-01-13 01:52:39 +00003796 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003797 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003798 Expr *Elem = prepareVectorSplat(ToType, From).get();
3799 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3800 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003801 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregor46188682010-05-18 22:42:18 +00003804 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003805 // Case 1. x -> _Complex y
3806 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3807 QualType ElType = ToComplex->getElementType();
3808 bool isFloatingComplex = ElType->isRealFloatingType();
3809
3810 // x -> y
3811 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3812 // do nothing
3813 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003814 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003815 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003816 } else {
3817 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003818 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003819 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003820 }
3821 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003822 From = ImpCastExprToType(From, ToType,
3823 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003824 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003825
3826 // Case 2. _Complex x -> y
3827 } else {
3828 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3829 assert(FromComplex);
3830
3831 QualType ElType = FromComplex->getElementType();
3832 bool isFloatingComplex = ElType->isRealFloatingType();
3833
3834 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003835 From = ImpCastExprToType(From, ElType,
3836 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003837 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003838 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003839
3840 // x -> y
3841 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3842 // do nothing
3843 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003844 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003845 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003846 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003847 } else {
3848 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003849 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003850 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003851 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003852 }
3853 }
Douglas Gregor46188682010-05-18 22:42:18 +00003854 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003855
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003856 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003857 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003858 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003859 break;
3860 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003861
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003862 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003863 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003864 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003865 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3866 if (FromRes.isInvalid())
3867 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003868 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003869 assert ((ConvTy == Sema::Compatible) &&
3870 "Improper transparent union conversion");
3871 (void)ConvTy;
3872 break;
3873 }
3874
Guy Benyei259f9f42013-02-07 16:05:33 +00003875 case ICK_Zero_Event_Conversion:
3876 From = ImpCastExprToType(From, ToType,
3877 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003878 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003879 break;
3880
Egor Churaev89831422016-12-23 14:55:49 +00003881 case ICK_Zero_Queue_Conversion:
3882 From = ImpCastExprToType(From, ToType,
3883 CK_ZeroToOCLQueue,
3884 From->getValueKind()).get();
3885 break;
3886
Douglas Gregor46188682010-05-18 22:42:18 +00003887 case ICK_Lvalue_To_Rvalue:
3888 case ICK_Array_To_Pointer:
3889 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003890 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003891 case ICK_Qualification:
3892 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003893 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003894 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003895 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003896 }
3897
3898 switch (SCS.Third) {
3899 case ICK_Identity:
3900 // Nothing to do.
3901 break;
3902
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003903 case ICK_Function_Conversion:
3904 // If both sides are functions (or pointers/references to them), there could
3905 // be incompatible exception declarations.
3906 if (CheckExceptionSpecCompatibility(From, ToType))
3907 return ExprError();
3908
3909 From = ImpCastExprToType(From, ToType, CK_NoOp,
3910 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3911 break;
3912
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003913 case ICK_Qualification: {
3914 // The qualification keeps the category of the inner expression, unless the
3915 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003916 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003917 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003918 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003919 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003920
Douglas Gregore981bb02011-03-14 16:13:32 +00003921 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003922 !getLangOpts().WritableStrings) {
3923 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3924 ? diag::ext_deprecated_string_literal_conversion
3925 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003926 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003927 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003928
Douglas Gregor39c16d42008-10-24 04:54:22 +00003929 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003930 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003931
Douglas Gregor39c16d42008-10-24 04:54:22 +00003932 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003933 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003934 }
3935
Douglas Gregor298f43d2012-04-12 20:42:30 +00003936 // If this conversion sequence involved a scalar -> atomic conversion, perform
3937 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003938 if (!ToAtomicType.isNull()) {
3939 assert(Context.hasSameType(
3940 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3941 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003942 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003943 }
3944
George Burgess IV8d141e02015-12-14 22:00:49 +00003945 // If this conversion sequence succeeded and involved implicitly converting a
3946 // _Nullable type to a _Nonnull one, complain.
3947 if (CCK == CCK_ImplicitConversion)
3948 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3949 From->getLocStart());
3950
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003951 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003952}
3953
Chandler Carruth8e172c62011-05-01 06:51:22 +00003954/// \brief Check the completeness of a type in a unary type trait.
3955///
3956/// If the particular type trait requires a complete type, tries to complete
3957/// it. If completing the type fails, a diagnostic is emitted and false
3958/// returned. If completing the type succeeds or no completion was required,
3959/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003960static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003961 SourceLocation Loc,
3962 QualType ArgTy) {
3963 // C++0x [meta.unary.prop]p3:
3964 // For all of the class templates X declared in this Clause, instantiating
3965 // that template with a template argument that is a class template
3966 // specialization may result in the implicit instantiation of the template
3967 // argument if and only if the semantics of X require that the argument
3968 // must be a complete type.
3969 // We apply this rule to all the type trait expressions used to implement
3970 // these class templates. We also try to follow any GCC documented behavior
3971 // in these expressions to ensure portability of standard libraries.
3972 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003973 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003974 // is_complete_type somewhat obviously cannot require a complete type.
3975 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003976 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003977
3978 // These traits are modeled on the type predicates in C++0x
3979 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3980 // requiring a complete type, as whether or not they return true cannot be
3981 // impacted by the completeness of the type.
3982 case UTT_IsVoid:
3983 case UTT_IsIntegral:
3984 case UTT_IsFloatingPoint:
3985 case UTT_IsArray:
3986 case UTT_IsPointer:
3987 case UTT_IsLvalueReference:
3988 case UTT_IsRvalueReference:
3989 case UTT_IsMemberFunctionPointer:
3990 case UTT_IsMemberObjectPointer:
3991 case UTT_IsEnum:
3992 case UTT_IsUnion:
3993 case UTT_IsClass:
3994 case UTT_IsFunction:
3995 case UTT_IsReference:
3996 case UTT_IsArithmetic:
3997 case UTT_IsFundamental:
3998 case UTT_IsObject:
3999 case UTT_IsScalar:
4000 case UTT_IsCompound:
4001 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004002 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004003
4004 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4005 // which requires some of its traits to have the complete type. However,
4006 // the completeness of the type cannot impact these traits' semantics, and
4007 // so they don't require it. This matches the comments on these traits in
4008 // Table 49.
4009 case UTT_IsConst:
4010 case UTT_IsVolatile:
4011 case UTT_IsSigned:
4012 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004013
4014 // This type trait always returns false, checking the type is moot.
4015 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004016 return true;
4017
David Majnemer213bea32015-11-16 06:58:51 +00004018 // C++14 [meta.unary.prop]:
4019 // If T is a non-union class type, T shall be a complete type.
4020 case UTT_IsEmpty:
4021 case UTT_IsPolymorphic:
4022 case UTT_IsAbstract:
4023 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4024 if (!RD->isUnion())
4025 return !S.RequireCompleteType(
4026 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4027 return true;
4028
4029 // C++14 [meta.unary.prop]:
4030 // If T is a class type, T shall be a complete type.
4031 case UTT_IsFinal:
4032 case UTT_IsSealed:
4033 if (ArgTy->getAsCXXRecordDecl())
4034 return !S.RequireCompleteType(
4035 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4036 return true;
4037
4038 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4039 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004040 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004041 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004042 case UTT_IsStandardLayout:
4043 case UTT_IsPOD:
4044 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004045
Alp Toker73287bf2014-01-20 00:24:09 +00004046 case UTT_IsDestructible:
4047 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004048 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004049
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004050 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004051 // [meta.unary.prop] despite not being named the same. They are specified
4052 // by both GCC and the Embarcadero C++ compiler, and require the complete
4053 // type due to the overarching C++0x type predicates being implemented
4054 // requiring the complete type.
4055 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004056 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004057 case UTT_HasNothrowConstructor:
4058 case UTT_HasNothrowCopy:
4059 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004060 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004061 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004062 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004063 case UTT_HasTrivialCopy:
4064 case UTT_HasTrivialDestructor:
4065 case UTT_HasVirtualDestructor:
4066 // Arrays of unknown bound are expressly allowed.
4067 QualType ElTy = ArgTy;
4068 if (ArgTy->isIncompleteArrayType())
4069 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4070
4071 // The void type is expressly allowed.
4072 if (ElTy->isVoidType())
4073 return true;
4074
4075 return !S.RequireCompleteType(
4076 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004077 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004078}
4079
Joao Matosc9523d42013-03-27 01:34:16 +00004080static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4081 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004082 bool (CXXRecordDecl::*HasTrivial)() const,
4083 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004084 bool (CXXMethodDecl::*IsDesiredOp)() const)
4085{
4086 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4087 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4088 return true;
4089
4090 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4091 DeclarationNameInfo NameInfo(Name, KeyLoc);
4092 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4093 if (Self.LookupQualifiedName(Res, RD)) {
4094 bool FoundOperator = false;
4095 Res.suppressDiagnostics();
4096 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4097 Op != OpEnd; ++Op) {
4098 if (isa<FunctionTemplateDecl>(*Op))
4099 continue;
4100
4101 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4102 if((Operator->*IsDesiredOp)()) {
4103 FoundOperator = true;
4104 const FunctionProtoType *CPT =
4105 Operator->getType()->getAs<FunctionProtoType>();
4106 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004107 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004108 return false;
4109 }
4110 }
4111 return FoundOperator;
4112 }
4113 return false;
4114}
4115
Alp Toker95e7ff22014-01-01 05:57:51 +00004116static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004117 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004118 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004119
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004120 ASTContext &C = Self.Context;
4121 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004122 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004123 // Type trait expressions corresponding to the primary type category
4124 // predicates in C++0x [meta.unary.cat].
4125 case UTT_IsVoid:
4126 return T->isVoidType();
4127 case UTT_IsIntegral:
4128 return T->isIntegralType(C);
4129 case UTT_IsFloatingPoint:
4130 return T->isFloatingType();
4131 case UTT_IsArray:
4132 return T->isArrayType();
4133 case UTT_IsPointer:
4134 return T->isPointerType();
4135 case UTT_IsLvalueReference:
4136 return T->isLValueReferenceType();
4137 case UTT_IsRvalueReference:
4138 return T->isRValueReferenceType();
4139 case UTT_IsMemberFunctionPointer:
4140 return T->isMemberFunctionPointerType();
4141 case UTT_IsMemberObjectPointer:
4142 return T->isMemberDataPointerType();
4143 case UTT_IsEnum:
4144 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004145 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004146 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004147 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004148 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004149 case UTT_IsFunction:
4150 return T->isFunctionType();
4151
4152 // Type trait expressions which correspond to the convenient composition
4153 // predicates in C++0x [meta.unary.comp].
4154 case UTT_IsReference:
4155 return T->isReferenceType();
4156 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004157 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004158 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004159 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004160 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004161 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004162 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004163 // Note: semantic analysis depends on Objective-C lifetime types to be
4164 // considered scalar types. However, such types do not actually behave
4165 // like scalar types at run time (since they may require retain/release
4166 // operations), so we report them as non-scalar.
4167 if (T->isObjCLifetimeType()) {
4168 switch (T.getObjCLifetime()) {
4169 case Qualifiers::OCL_None:
4170 case Qualifiers::OCL_ExplicitNone:
4171 return true;
4172
4173 case Qualifiers::OCL_Strong:
4174 case Qualifiers::OCL_Weak:
4175 case Qualifiers::OCL_Autoreleasing:
4176 return false;
4177 }
4178 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004179
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004180 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004181 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004182 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004183 case UTT_IsMemberPointer:
4184 return T->isMemberPointerType();
4185
4186 // Type trait expressions which correspond to the type property predicates
4187 // in C++0x [meta.unary.prop].
4188 case UTT_IsConst:
4189 return T.isConstQualified();
4190 case UTT_IsVolatile:
4191 return T.isVolatileQualified();
4192 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004193 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004194 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004195 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004196 case UTT_IsStandardLayout:
4197 return T->isStandardLayoutType();
4198 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004199 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004200 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004201 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004202 case UTT_IsEmpty:
4203 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4204 return !RD->isUnion() && RD->isEmpty();
4205 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004206 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004207 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004208 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004209 return false;
4210 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004211 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004212 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004213 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004214 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4215 // even then only when it is used with the 'interface struct ...' syntax
4216 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004217 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004218 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004219 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004220 case UTT_IsSealed:
4221 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004222 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004223 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004224 case UTT_IsSigned:
4225 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004226 case UTT_IsUnsigned:
4227 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004228
4229 // Type trait expressions which query classes regarding their construction,
4230 // destruction, and copying. Rather than being based directly on the
4231 // related type predicates in the standard, they are specified by both
4232 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4233 // specifications.
4234 //
4235 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4236 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004237 //
4238 // Note that these builtins do not behave as documented in g++: if a class
4239 // has both a trivial and a non-trivial special member of a particular kind,
4240 // they return false! For now, we emulate this behavior.
4241 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4242 // does not correctly compute triviality in the presence of multiple special
4243 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004244 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004245 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4246 // If __is_pod (type) is true then the trait is true, else if type is
4247 // a cv class or union type (or array thereof) with a trivial default
4248 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004249 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004250 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004251 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4252 return RD->hasTrivialDefaultConstructor() &&
4253 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004254 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004255 case UTT_HasTrivialMoveConstructor:
4256 // This trait is implemented by MSVC 2012 and needed to parse the
4257 // standard library headers. Specifically this is used as the logic
4258 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004259 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004260 return true;
4261 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4262 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4263 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004264 case UTT_HasTrivialCopy:
4265 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4266 // If __is_pod (type) is true or type is a reference type then
4267 // the trait is true, else if type is a cv class or union type
4268 // with a trivial copy constructor ([class.copy]) then the trait
4269 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004270 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004271 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004272 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4273 return RD->hasTrivialCopyConstructor() &&
4274 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004275 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004276 case UTT_HasTrivialMoveAssign:
4277 // This trait is implemented by MSVC 2012 and needed to parse the
4278 // standard library headers. Specifically it is used as the logic
4279 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004280 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004281 return true;
4282 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4283 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4284 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004285 case UTT_HasTrivialAssign:
4286 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4287 // If type is const qualified or is a reference type then the
4288 // trait is false. Otherwise if __is_pod (type) is true then the
4289 // trait is true, else if type is a cv class or union type with
4290 // a trivial copy assignment ([class.copy]) then the trait is
4291 // true, else it is false.
4292 // Note: the const and reference restrictions are interesting,
4293 // given that const and reference members don't prevent a class
4294 // from having a trivial copy assignment operator (but do cause
4295 // errors if the copy assignment operator is actually used, q.v.
4296 // [class.copy]p12).
4297
Richard Smith92f241f2012-12-08 02:53:02 +00004298 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004299 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004300 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004301 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004302 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4303 return RD->hasTrivialCopyAssignment() &&
4304 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004305 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004306 case UTT_IsDestructible:
4307 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004308 // C++14 [meta.unary.prop]:
4309 // For reference types, is_destructible<T>::value is true.
4310 if (T->isReferenceType())
4311 return true;
4312
4313 // Objective-C++ ARC: autorelease types don't require destruction.
4314 if (T->isObjCLifetimeType() &&
4315 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4316 return true;
4317
4318 // C++14 [meta.unary.prop]:
4319 // For incomplete types and function types, is_destructible<T>::value is
4320 // false.
4321 if (T->isIncompleteType() || T->isFunctionType())
4322 return false;
4323
4324 // C++14 [meta.unary.prop]:
4325 // For object types and given U equal to remove_all_extents_t<T>, if the
4326 // expression std::declval<U&>().~U() is well-formed when treated as an
4327 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4328 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4329 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4330 if (!Destructor)
4331 return false;
4332 // C++14 [dcl.fct.def.delete]p2:
4333 // A program that refers to a deleted function implicitly or
4334 // explicitly, other than to declare it, is ill-formed.
4335 if (Destructor->isDeleted())
4336 return false;
4337 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4338 return false;
4339 if (UTT == UTT_IsNothrowDestructible) {
4340 const FunctionProtoType *CPT =
4341 Destructor->getType()->getAs<FunctionProtoType>();
4342 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4343 if (!CPT || !CPT->isNothrow(C))
4344 return false;
4345 }
4346 }
4347 return true;
4348
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004349 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004350 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004351 // If __is_pod (type) is true or type is a reference type
4352 // then the trait is true, else if type is a cv class or union
4353 // type (or array thereof) with a trivial destructor
4354 // ([class.dtor]) then the trait is true, else it is
4355 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004356 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004357 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004358
John McCall31168b02011-06-15 23:02:42 +00004359 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004360 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004361 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4362 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004363
Richard Smith92f241f2012-12-08 02:53:02 +00004364 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4365 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004366 return false;
4367 // TODO: Propagate nothrowness for implicitly declared special members.
4368 case UTT_HasNothrowAssign:
4369 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4370 // If type is const qualified or is a reference type then the
4371 // trait is false. Otherwise if __has_trivial_assign (type)
4372 // is true then the trait is true, else if type is a cv class
4373 // or union type with copy assignment operators that are known
4374 // not to throw an exception then the trait is true, else it is
4375 // false.
4376 if (C.getBaseElementType(T).isConstQualified())
4377 return false;
4378 if (T->isReferenceType())
4379 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004380 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004381 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004382
Joao Matosc9523d42013-03-27 01:34:16 +00004383 if (const RecordType *RT = T->getAs<RecordType>())
4384 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4385 &CXXRecordDecl::hasTrivialCopyAssignment,
4386 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4387 &CXXMethodDecl::isCopyAssignmentOperator);
4388 return false;
4389 case UTT_HasNothrowMoveAssign:
4390 // This trait is implemented by MSVC 2012 and needed to parse the
4391 // standard library headers. Specifically this is used as the logic
4392 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004393 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004394 return true;
4395
4396 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4397 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4398 &CXXRecordDecl::hasTrivialMoveAssignment,
4399 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4400 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004401 return false;
4402 case UTT_HasNothrowCopy:
4403 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4404 // If __has_trivial_copy (type) is true then the trait is true, else
4405 // if type is a cv class or union type with copy constructors that are
4406 // known not to throw an exception then the trait is true, else it is
4407 // false.
John McCall31168b02011-06-15 23:02:42 +00004408 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004409 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004410 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4411 if (RD->hasTrivialCopyConstructor() &&
4412 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004413 return true;
4414
4415 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004416 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004417 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004418 // A template constructor is never a copy constructor.
4419 // FIXME: However, it may actually be selected at the actual overload
4420 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004421 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004422 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004423 // UsingDecl itself is not a constructor
4424 if (isa<UsingDecl>(ND))
4425 continue;
4426 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004427 if (Constructor->isCopyConstructor(FoundTQs)) {
4428 FoundConstructor = true;
4429 const FunctionProtoType *CPT
4430 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004431 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4432 if (!CPT)
4433 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004434 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004435 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004436 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004437 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004438 }
4439 }
4440
Richard Smith938f40b2011-06-11 17:19:42 +00004441 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004442 }
4443 return false;
4444 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004445 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004446 // If __has_trivial_constructor (type) is true then the trait is
4447 // true, else if type is a cv class or union type (or array
4448 // thereof) with a default constructor that is known not to
4449 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004450 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004451 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004452 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4453 if (RD->hasTrivialDefaultConstructor() &&
4454 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004455 return true;
4456
Alp Tokerb4bca412014-01-20 00:23:47 +00004457 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004458 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004459 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004460 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004461 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004462 // UsingDecl itself is not a constructor
4463 if (isa<UsingDecl>(ND))
4464 continue;
4465 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004466 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004467 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004468 const FunctionProtoType *CPT
4469 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004470 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4471 if (!CPT)
4472 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004473 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004474 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004475 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004476 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004477 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004478 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004479 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004480 }
4481 return false;
4482 case UTT_HasVirtualDestructor:
4483 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4484 // If type is a class type with a virtual destructor ([class.dtor])
4485 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004486 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004487 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004488 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004489 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004490
4491 // These type trait expressions are modeled on the specifications for the
4492 // Embarcadero C++0x type trait functions:
4493 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4494 case UTT_IsCompleteType:
4495 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4496 // Returns True if and only if T is a complete type at the point of the
4497 // function call.
4498 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004499 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004500}
Sebastian Redl5822f082009-02-07 20:10:22 +00004501
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004502/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4503/// ARC mode.
4504static bool hasNontrivialObjCLifetime(QualType T) {
4505 switch (T.getObjCLifetime()) {
4506 case Qualifiers::OCL_ExplicitNone:
4507 return false;
4508
4509 case Qualifiers::OCL_Strong:
4510 case Qualifiers::OCL_Weak:
4511 case Qualifiers::OCL_Autoreleasing:
4512 return true;
4513
4514 case Qualifiers::OCL_None:
4515 return T->isObjCLifetimeType();
4516 }
4517
4518 llvm_unreachable("Unknown ObjC lifetime qualifier");
4519}
4520
Alp Tokercbb90342013-12-13 20:49:58 +00004521static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4522 QualType RhsT, SourceLocation KeyLoc);
4523
Douglas Gregor29c42f22012-02-24 07:38:34 +00004524static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4525 ArrayRef<TypeSourceInfo *> Args,
4526 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004527 if (Kind <= UTT_Last)
4528 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4529
Alp Tokercbb90342013-12-13 20:49:58 +00004530 if (Kind <= BTT_Last)
4531 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4532 Args[1]->getType(), RParenLoc);
4533
Douglas Gregor29c42f22012-02-24 07:38:34 +00004534 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004535 case clang::TT_IsConstructible:
4536 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004537 case clang::TT_IsTriviallyConstructible: {
4538 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004539 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004540 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004541 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004542 // definition for is_constructible, as defined below, is known to call
4543 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004544 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004545 // The predicate condition for a template specialization
4546 // is_constructible<T, Args...> shall be satisfied if and only if the
4547 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004548 // variable t:
4549 //
4550 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004551 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004552
4553 // Precondition: T and all types in the parameter pack Args shall be
4554 // complete types, (possibly cv-qualified) void, or arrays of
4555 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004556 for (const auto *TSI : Args) {
4557 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004558 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004559 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004560
Simon Pilgrim75c26882016-09-30 14:25:09 +00004561 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004562 diag::err_incomplete_type_used_in_type_trait_expr))
4563 return false;
4564 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004565
David Majnemer9658ecc2015-11-13 05:32:43 +00004566 // Make sure the first argument is not incomplete nor a function type.
4567 QualType T = Args[0]->getType();
4568 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004569 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004570
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004571 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004572 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004573 if (RD && RD->isAbstract())
4574 return false;
4575
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004576 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4577 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004578 ArgExprs.reserve(Args.size() - 1);
4579 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004580 QualType ArgTy = Args[I]->getType();
4581 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4582 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004583 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004584 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4585 ArgTy.getNonLValueExprType(S.Context),
4586 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004587 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004588 for (Expr &E : OpaqueArgExprs)
4589 ArgExprs.push_back(&E);
4590
Simon Pilgrim75c26882016-09-30 14:25:09 +00004591 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004592 // trap at translation unit scope.
4593 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4594 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4595 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4596 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4597 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4598 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004599 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004600 if (Init.Failed())
4601 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004602
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004603 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004604 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4605 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004606
Alp Toker73287bf2014-01-20 00:24:09 +00004607 if (Kind == clang::TT_IsConstructible)
4608 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004609
Alp Toker73287bf2014-01-20 00:24:09 +00004610 if (Kind == clang::TT_IsNothrowConstructible)
4611 return S.canThrow(Result.get()) == CT_Cannot;
4612
4613 if (Kind == clang::TT_IsTriviallyConstructible) {
4614 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4615 // lifetime, this is a non-trivial construction.
4616 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004617 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004618 return false;
4619
4620 // The initialization succeeded; now make sure there are no non-trivial
4621 // calls.
4622 return !Result.get()->hasNonTrivialCall(S.Context);
4623 }
4624
4625 llvm_unreachable("unhandled type trait");
4626 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004627 }
Alp Tokercbb90342013-12-13 20:49:58 +00004628 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004629 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004630
Douglas Gregor29c42f22012-02-24 07:38:34 +00004631 return false;
4632}
4633
Simon Pilgrim75c26882016-09-30 14:25:09 +00004634ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4635 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004636 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004637 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004638
Alp Toker95e7ff22014-01-01 05:57:51 +00004639 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4640 *this, Kind, KWLoc, Args[0]->getType()))
4641 return ExprError();
4642
Douglas Gregor29c42f22012-02-24 07:38:34 +00004643 bool Dependent = false;
4644 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4645 if (Args[I]->getType()->isDependentType()) {
4646 Dependent = true;
4647 break;
4648 }
4649 }
Alp Tokercbb90342013-12-13 20:49:58 +00004650
4651 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004652 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004653 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4654
4655 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4656 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004657}
4658
Alp Toker88f64e62013-12-13 21:19:30 +00004659ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4660 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004661 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004662 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004663 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004664
Douglas Gregor29c42f22012-02-24 07:38:34 +00004665 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4666 TypeSourceInfo *TInfo;
4667 QualType T = GetTypeFromParser(Args[I], &TInfo);
4668 if (!TInfo)
4669 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004670
4671 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004672 }
Alp Tokercbb90342013-12-13 20:49:58 +00004673
Douglas Gregor29c42f22012-02-24 07:38:34 +00004674 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4675}
4676
Alp Tokercbb90342013-12-13 20:49:58 +00004677static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4678 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004679 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4680 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004681
4682 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004683 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004684 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004685 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004686 // Base and Derived are not unions and name the same class type without
4687 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004688
John McCall388ef532011-01-28 22:02:36 +00004689 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4690 if (!lhsRecord) return false;
4691
4692 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4693 if (!rhsRecord) return false;
4694
4695 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4696 == (lhsRecord == rhsRecord));
4697
4698 if (lhsRecord == rhsRecord)
4699 return !lhsRecord->getDecl()->isUnion();
4700
4701 // C++0x [meta.rel]p2:
4702 // If Base and Derived are class types and are different types
4703 // (ignoring possible cv-qualifiers) then Derived shall be a
4704 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004705 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004706 diag::err_incomplete_type_used_in_type_trait_expr))
4707 return false;
4708
4709 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4710 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4711 }
John Wiegley65497cc2011-04-27 23:09:49 +00004712 case BTT_IsSame:
4713 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004714 case BTT_TypeCompatible:
4715 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4716 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004717 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004718 case BTT_IsConvertibleTo: {
4719 // C++0x [meta.rel]p4:
4720 // Given the following function prototype:
4721 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004722 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004723 // typename add_rvalue_reference<T>::type create();
4724 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004725 // the predicate condition for a template specialization
4726 // is_convertible<From, To> shall be satisfied if and only if
4727 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004728 // well-formed, including any implicit conversions to the return
4729 // type of the function:
4730 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004731 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004732 // return create<From>();
4733 // }
4734 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004735 // Access checking is performed as if in a context unrelated to To and
4736 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004737 // of the return-statement (including conversions to the return type)
4738 // is considered.
4739 //
4740 // We model the initialization as a copy-initialization of a temporary
4741 // of the appropriate type, which for this expression is identical to the
4742 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004743
4744 // Functions aren't allowed to return function or array types.
4745 if (RhsT->isFunctionType() || RhsT->isArrayType())
4746 return false;
4747
4748 // A return statement in a void function must have void type.
4749 if (RhsT->isVoidType())
4750 return LhsT->isVoidType();
4751
4752 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004753 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004754 return false;
4755
4756 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004757 if (LhsT->isObjectType() || LhsT->isFunctionType())
4758 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004759
4760 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004761 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004762 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004763 Expr::getValueKindForType(LhsT));
4764 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004765 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004766 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004767
4768 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004769 // trap at translation unit scope.
4770 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004771 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4772 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004773 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004774 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004775 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004776
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004777 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004778 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4779 }
Alp Toker73287bf2014-01-20 00:24:09 +00004780
David Majnemerb3d96882016-05-23 17:21:55 +00004781 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004782 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004783 case BTT_IsTriviallyAssignable: {
4784 // C++11 [meta.unary.prop]p3:
4785 // is_trivially_assignable is defined as:
4786 // is_assignable<T, U>::value is true and the assignment, as defined by
4787 // is_assignable, is known to call no operation that is not trivial
4788 //
4789 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004790 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004791 // treated as an unevaluated operand (Clause 5).
4792 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004793 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004794 // void, or arrays of unknown bound.
4795 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004796 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004797 diag::err_incomplete_type_used_in_type_trait_expr))
4798 return false;
4799 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004800 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004801 diag::err_incomplete_type_used_in_type_trait_expr))
4802 return false;
4803
4804 // cv void is never assignable.
4805 if (LhsT->isVoidType() || RhsT->isVoidType())
4806 return false;
4807
Simon Pilgrim75c26882016-09-30 14:25:09 +00004808 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004809 // declval<U>().
4810 if (LhsT->isObjectType() || LhsT->isFunctionType())
4811 LhsT = Self.Context.getRValueReferenceType(LhsT);
4812 if (RhsT->isObjectType() || RhsT->isFunctionType())
4813 RhsT = Self.Context.getRValueReferenceType(RhsT);
4814 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4815 Expr::getValueKindForType(LhsT));
4816 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4817 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004818
4819 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004820 // trap at translation unit scope.
4821 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4822 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4823 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004824 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4825 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004826 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4827 return false;
4828
David Majnemerb3d96882016-05-23 17:21:55 +00004829 if (BTT == BTT_IsAssignable)
4830 return true;
4831
Alp Toker73287bf2014-01-20 00:24:09 +00004832 if (BTT == BTT_IsNothrowAssignable)
4833 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004834
Alp Toker73287bf2014-01-20 00:24:09 +00004835 if (BTT == BTT_IsTriviallyAssignable) {
4836 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4837 // lifetime, this is a non-trivial assignment.
4838 if (Self.getLangOpts().ObjCAutoRefCount &&
4839 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4840 return false;
4841
4842 return !Result.get()->hasNonTrivialCall(Self.Context);
4843 }
4844
4845 llvm_unreachable("unhandled type trait");
4846 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004847 }
Alp Tokercbb90342013-12-13 20:49:58 +00004848 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004849 }
4850 llvm_unreachable("Unknown type trait or not implemented");
4851}
4852
John Wiegley6242b6a2011-04-28 00:16:57 +00004853ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4854 SourceLocation KWLoc,
4855 ParsedType Ty,
4856 Expr* DimExpr,
4857 SourceLocation RParen) {
4858 TypeSourceInfo *TSInfo;
4859 QualType T = GetTypeFromParser(Ty, &TSInfo);
4860 if (!TSInfo)
4861 TSInfo = Context.getTrivialTypeSourceInfo(T);
4862
4863 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4864}
4865
4866static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4867 QualType T, Expr *DimExpr,
4868 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004869 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004870
4871 switch(ATT) {
4872 case ATT_ArrayRank:
4873 if (T->isArrayType()) {
4874 unsigned Dim = 0;
4875 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4876 ++Dim;
4877 T = AT->getElementType();
4878 }
4879 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004880 }
John Wiegleyd3522222011-04-28 02:06:46 +00004881 return 0;
4882
John Wiegley6242b6a2011-04-28 00:16:57 +00004883 case ATT_ArrayExtent: {
4884 llvm::APSInt Value;
4885 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004886 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004887 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004888 false).isInvalid())
4889 return 0;
4890 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004891 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4892 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004893 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004894 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004895 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004896
4897 if (T->isArrayType()) {
4898 unsigned D = 0;
4899 bool Matched = false;
4900 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4901 if (Dim == D) {
4902 Matched = true;
4903 break;
4904 }
4905 ++D;
4906 T = AT->getElementType();
4907 }
4908
John Wiegleyd3522222011-04-28 02:06:46 +00004909 if (Matched && T->isArrayType()) {
4910 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4911 return CAT->getSize().getLimitedValue();
4912 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004913 }
John Wiegleyd3522222011-04-28 02:06:46 +00004914 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004915 }
4916 }
4917 llvm_unreachable("Unknown type trait or not implemented");
4918}
4919
4920ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4921 SourceLocation KWLoc,
4922 TypeSourceInfo *TSInfo,
4923 Expr* DimExpr,
4924 SourceLocation RParen) {
4925 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004926
Chandler Carruthc5276e52011-05-01 08:48:21 +00004927 // FIXME: This should likely be tracked as an APInt to remove any host
4928 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004929 uint64_t Value = 0;
4930 if (!T->isDependentType())
4931 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4932
Chandler Carruthc5276e52011-05-01 08:48:21 +00004933 // While the specification for these traits from the Embarcadero C++
4934 // compiler's documentation says the return type is 'unsigned int', Clang
4935 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4936 // compiler, there is no difference. On several other platforms this is an
4937 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004938 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4939 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004940}
4941
John Wiegleyf9f65842011-04-25 06:54:41 +00004942ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004943 SourceLocation KWLoc,
4944 Expr *Queried,
4945 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004946 // If error parsing the expression, ignore.
4947 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004948 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004949
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004950 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004951
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004952 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004953}
4954
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004955static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4956 switch (ET) {
4957 case ET_IsLValueExpr: return E->isLValue();
4958 case ET_IsRValueExpr: return E->isRValue();
4959 }
4960 llvm_unreachable("Expression trait not covered by switch");
4961}
4962
John Wiegleyf9f65842011-04-25 06:54:41 +00004963ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004964 SourceLocation KWLoc,
4965 Expr *Queried,
4966 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004967 if (Queried->isTypeDependent()) {
4968 // Delay type-checking for type-dependent expressions.
4969 } else if (Queried->getType()->isPlaceholderType()) {
4970 ExprResult PE = CheckPlaceholderExpr(Queried);
4971 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004972 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004973 }
4974
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004975 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004976
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004977 return new (Context)
4978 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004979}
4980
Richard Trieu82402a02011-09-15 21:56:47 +00004981QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004982 ExprValueKind &VK,
4983 SourceLocation Loc,
4984 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004985 assert(!LHS.get()->getType()->isPlaceholderType() &&
4986 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004987 "placeholders should have been weeded out by now");
4988
Richard Smith4baaa5a2016-12-03 01:14:32 +00004989 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
4990 // temporary materialization conversion otherwise.
4991 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004992 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00004993 else if (LHS.get()->isRValue())
4994 LHS = TemporaryMaterializationConversion(LHS.get());
4995 if (LHS.isInvalid())
4996 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004997
4998 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004999 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005000 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005001
Sebastian Redl5822f082009-02-07 20:10:22 +00005002 const char *OpSpelling = isIndirect ? "->*" : ".*";
5003 // C++ 5.5p2
5004 // The binary operator .* [p3: ->*] binds its second operand, which shall
5005 // be of type "pointer to member of T" (where T is a completely-defined
5006 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005007 QualType RHSType = RHS.get()->getType();
5008 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005009 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005010 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005011 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005012 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005013 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005014
Sebastian Redl5822f082009-02-07 20:10:22 +00005015 QualType Class(MemPtr->getClass(), 0);
5016
Douglas Gregord07ba342010-10-13 20:41:14 +00005017 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5018 // member pointer points must be completely-defined. However, there is no
5019 // reason for this semantic distinction, and the rule is not enforced by
5020 // other compilers. Therefore, we do not check this property, as it is
5021 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005022
Sebastian Redl5822f082009-02-07 20:10:22 +00005023 // C++ 5.5p2
5024 // [...] to its first operand, which shall be of class T or of a class of
5025 // which T is an unambiguous and accessible base class. [p3: a pointer to
5026 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005027 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005028 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005029 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5030 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005031 else {
5032 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005033 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005034 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005035 return QualType();
5036 }
5037 }
5038
Richard Trieu82402a02011-09-15 21:56:47 +00005039 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005040 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005041 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5042 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005043 return QualType();
5044 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005045
Richard Smith0f59cb32015-12-18 21:45:41 +00005046 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005047 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005048 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005049 return QualType();
5050 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005051
5052 CXXCastPath BasePath;
5053 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5054 SourceRange(LHS.get()->getLocStart(),
5055 RHS.get()->getLocEnd()),
5056 &BasePath))
5057 return QualType();
5058
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005059 // Cast LHS to type of use.
5060 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005061 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005062 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005063 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005064 }
5065
Richard Trieu82402a02011-09-15 21:56:47 +00005066 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005067 // Diagnose use of pointer-to-member type which when used as
5068 // the functional cast in a pointer-to-member expression.
5069 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5070 return QualType();
5071 }
John McCall7decc9e2010-11-18 06:31:45 +00005072
Sebastian Redl5822f082009-02-07 20:10:22 +00005073 // C++ 5.5p2
5074 // The result is an object or a function of the type specified by the
5075 // second operand.
5076 // The cv qualifiers are the union of those in the pointer and the left side,
5077 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005078 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005079 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005080
Douglas Gregor1d042092011-01-26 16:40:18 +00005081 // C++0x [expr.mptr.oper]p6:
5082 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083 // ill-formed if the second operand is a pointer to member function with
5084 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5085 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005086 // is a pointer to member function with ref-qualifier &&.
5087 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5088 switch (Proto->getRefQualifier()) {
5089 case RQ_None:
5090 // Do nothing
5091 break;
5092
5093 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005094 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005095 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005096 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005097 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098
Douglas Gregor1d042092011-01-26 16:40:18 +00005099 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005100 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005101 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005102 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005103 break;
5104 }
5105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106
John McCall7decc9e2010-11-18 06:31:45 +00005107 // C++ [expr.mptr.oper]p6:
5108 // The result of a .* expression whose second operand is a pointer
5109 // to a data member is of the same value category as its
5110 // first operand. The result of a .* expression whose second
5111 // operand is a pointer to a member function is a prvalue. The
5112 // result of an ->* expression is an lvalue if its second operand
5113 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005114 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005115 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005116 return Context.BoundMemberTy;
5117 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005118 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005119 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005120 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005121 }
John McCall7decc9e2010-11-18 06:31:45 +00005122
Sebastian Redl5822f082009-02-07 20:10:22 +00005123 return Result;
5124}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005125
Richard Smith2414bca2016-04-25 19:30:37 +00005126/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005127///
5128/// This is part of the parameter validation for the ? operator. If either
5129/// value operand is a class type, the two operands are attempted to be
5130/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005131/// It returns true if the program is ill-formed and has already been diagnosed
5132/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005133static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5134 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005135 bool &HaveConversion,
5136 QualType &ToType) {
5137 HaveConversion = false;
5138 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005139
5140 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005141 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005142 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005143 // The process for determining whether an operand expression E1 of type T1
5144 // can be converted to match an operand expression E2 of type T2 is defined
5145 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005146 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5147 // implicitly converted to type "lvalue reference to T2", subject to the
5148 // constraint that in the conversion the reference must bind directly to
5149 // an lvalue.
5150 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5151 // implicitly conveted to the type "rvalue reference to R2", subject to
5152 // the constraint that the reference must bind directly.
5153 if (To->isLValue() || To->isXValue()) {
5154 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5155 : Self.Context.getRValueReferenceType(ToType);
5156
Douglas Gregor838fcc32010-03-26 20:14:36 +00005157 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005159 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005160 if (InitSeq.isDirectReferenceBinding()) {
5161 ToType = T;
5162 HaveConversion = true;
5163 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005165
Douglas Gregor838fcc32010-03-26 20:14:36 +00005166 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005167 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005168 }
John McCall65eb8792010-02-25 01:37:24 +00005169
Sebastian Redl1a99f442009-04-16 17:51:27 +00005170 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5171 // -- if E1 and E2 have class type, and the underlying class types are
5172 // the same or one is a base class of the other:
5173 QualType FTy = From->getType();
5174 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005175 const RecordType *FRec = FTy->getAs<RecordType>();
5176 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005178 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5179 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5180 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005181 // E1 can be converted to match E2 if the class of T2 is the
5182 // same type as, or a base class of, the class of T1, and
5183 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005184 if (FRec == TRec || FDerivedFromT) {
5185 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005186 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005187 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005188 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005189 HaveConversion = true;
5190 return false;
5191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005192
Douglas Gregor838fcc32010-03-26 20:14:36 +00005193 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005194 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
Douglas Gregor838fcc32010-03-26 20:14:36 +00005198 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Douglas Gregor838fcc32010-03-26 20:14:36 +00005201 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5202 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005204 // an rvalue).
5205 //
5206 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5207 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005208 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005209
Douglas Gregor838fcc32010-03-26 20:14:36 +00005210 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005211 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005212 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005213 ToType = TTy;
5214 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005215 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005216
Sebastian Redl1a99f442009-04-16 17:51:27 +00005217 return false;
5218}
5219
5220/// \brief Try to find a common type for two according to C++0x 5.16p5.
5221///
5222/// This is part of the parameter validation for the ? operator. If either
5223/// value operand is a class type, overload resolution is used to find a
5224/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005225static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005226 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005227 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005228 OverloadCandidateSet CandidateSet(QuestionLoc,
5229 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005230 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005231 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005232
5233 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005234 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005235 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005236 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005237 ExprResult LHSRes =
5238 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5239 Best->Conversions[0], Sema::AA_Converting);
5240 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005241 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005242 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005243
5244 ExprResult RHSRes =
5245 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5246 Best->Conversions[1], Sema::AA_Converting);
5247 if (RHSRes.isInvalid())
5248 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005249 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005250 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005251 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005252 return false;
John Wiegley01296292011-04-08 18:41:53 +00005253 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005254
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005255 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005256
5257 // Emit a better diagnostic if one of the expressions is a null pointer
5258 // constant and the other is a pointer type. In this case, the user most
5259 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005260 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005261 return true;
5262
5263 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005264 << LHS.get()->getType() << RHS.get()->getType()
5265 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005266 return true;
5267
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005268 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005269 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005270 << LHS.get()->getType() << RHS.get()->getType()
5271 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005272 // FIXME: Print the possible common types by printing the return types of
5273 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005274 break;
5275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005276 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005277 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005278 }
5279 return true;
5280}
5281
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005282/// \brief Perform an "extended" implicit conversion as returned by
5283/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005284static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005285 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005286 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005287 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005288 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005289 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005290 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005291 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005292 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005293
John Wiegley01296292011-04-08 18:41:53 +00005294 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005295 return false;
5296}
5297
Sebastian Redl1a99f442009-04-16 17:51:27 +00005298/// \brief Check the operands of ?: under C++ semantics.
5299///
5300/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5301/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005302QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5303 ExprResult &RHS, ExprValueKind &VK,
5304 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005305 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005306 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5307 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005308
Richard Smith45edb702012-08-07 22:06:48 +00005309 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005310 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005311 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005312 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005313 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005314 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005315 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005316 }
5317
John McCall7decc9e2010-11-18 06:31:45 +00005318 // Assume r-value.
5319 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005320 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005321
Sebastian Redl1a99f442009-04-16 17:51:27 +00005322 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005323 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005324 return Context.DependentTy;
5325
Richard Smith45edb702012-08-07 22:06:48 +00005326 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005328 QualType LTy = LHS.get()->getType();
5329 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005330 bool LVoid = LTy->isVoidType();
5331 bool RVoid = RTy->isVoidType();
5332 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005333 // ... one of the following shall hold:
5334 // -- The second or the third operand (but not both) is a (possibly
5335 // parenthesized) throw-expression; the result is of the type
5336 // and value category of the other.
5337 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5338 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5339 if (LThrow != RThrow) {
5340 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5341 VK = NonThrow->getValueKind();
5342 // DR (no number yet): the result is a bit-field if the
5343 // non-throw-expression operand is a bit-field.
5344 OK = NonThrow->getObjectKind();
5345 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005346 }
5347
Sebastian Redl1a99f442009-04-16 17:51:27 +00005348 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005349 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005350 if (LVoid && RVoid)
5351 return Context.VoidTy;
5352
5353 // Neither holds, error.
5354 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5355 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005356 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005357 return QualType();
5358 }
5359
5360 // Neither is void.
5361
Richard Smithf2b084f2012-08-08 06:13:49 +00005362 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005363 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005364 // either has (cv) class type [...] an attempt is made to convert each of
5365 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005367 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005368 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005369 QualType L2RType, R2LType;
5370 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005371 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005372 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005373 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005374 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005375
Sebastian Redl1a99f442009-04-16 17:51:27 +00005376 // If both can be converted, [...] the program is ill-formed.
5377 if (HaveL2R && HaveR2L) {
5378 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005379 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005380 return QualType();
5381 }
5382
5383 // If exactly one conversion is possible, that conversion is applied to
5384 // the chosen operand and the converted operands are used in place of the
5385 // original operands for the remainder of this section.
5386 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005387 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005388 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005389 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005390 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005391 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005392 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005393 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005394 }
5395 }
5396
Richard Smithf2b084f2012-08-08 06:13:49 +00005397 // C++11 [expr.cond]p3
5398 // if both are glvalues of the same value category and the same type except
5399 // for cv-qualification, an attempt is made to convert each of those
5400 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005401 // FIXME:
5402 // Resolving a defect in P0012R1: we extend this to cover all cases where
5403 // one of the operands is reference-compatible with the other, in order
5404 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005405 ExprValueKind LVK = LHS.get()->getValueKind();
5406 ExprValueKind RVK = RHS.get()->getValueKind();
5407 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005408 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005409 // DerivedToBase was already handled by the class-specific case above.
5410 // FIXME: Should we allow ObjC conversions here?
5411 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5412 if (CompareReferenceRelationship(
5413 QuestionLoc, LTy, RTy, DerivedToBase,
5414 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005415 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5416 // [...] subject to the constraint that the reference must bind
5417 // directly [...]
5418 !RHS.get()->refersToBitField() &&
5419 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005420 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005421 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005422 } else if (CompareReferenceRelationship(
5423 QuestionLoc, RTy, LTy, DerivedToBase,
5424 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005425 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5426 !LHS.get()->refersToBitField() &&
5427 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005428 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5429 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005430 }
5431 }
5432
5433 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005434 // If the second and third operands are glvalues of the same value
5435 // category and have the same type, the result is of that type and
5436 // value category and it is a bit-field if the second or the third
5437 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005438 // We only extend this to bitfields, not to the crazy other kinds of
5439 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005440 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005441 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005442 LHS.get()->isOrdinaryOrBitFieldObject() &&
5443 RHS.get()->isOrdinaryOrBitFieldObject()) {
5444 VK = LHS.get()->getValueKind();
5445 if (LHS.get()->getObjectKind() == OK_BitField ||
5446 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005447 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005448
5449 // If we have function pointer types, unify them anyway to unify their
5450 // exception specifications, if any.
5451 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5452 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005453 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005454 /*ConvertArgs*/false);
5455 LTy = Context.getQualifiedType(LTy, Qs);
5456
5457 assert(!LTy.isNull() && "failed to find composite pointer type for "
5458 "canonically equivalent function ptr types");
5459 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5460 }
5461
John McCall7decc9e2010-11-18 06:31:45 +00005462 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005463 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005464
Richard Smithf2b084f2012-08-08 06:13:49 +00005465 // C++11 [expr.cond]p5
5466 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005467 // do not have the same type, and either has (cv) class type, ...
5468 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5469 // ... overload resolution is used to determine the conversions (if any)
5470 // to be applied to the operands. If the overload resolution fails, the
5471 // program is ill-formed.
5472 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5473 return QualType();
5474 }
5475
Richard Smithf2b084f2012-08-08 06:13:49 +00005476 // C++11 [expr.cond]p6
5477 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005478 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005479 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5480 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005481 if (LHS.isInvalid() || RHS.isInvalid())
5482 return QualType();
5483 LTy = LHS.get()->getType();
5484 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005485
5486 // After those conversions, one of the following shall hold:
5487 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005488 // is of that type. If the operands have class type, the result
5489 // is a prvalue temporary of the result type, which is
5490 // copy-initialized from either the second operand or the third
5491 // operand depending on the value of the first operand.
5492 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5493 if (LTy->isRecordType()) {
5494 // The operands have class type. Make a temporary copy.
5495 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005497 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5498 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005499 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005500 if (LHSCopy.isInvalid())
5501 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005502
5503 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5504 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005505 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005506 if (RHSCopy.isInvalid())
5507 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508
John Wiegley01296292011-04-08 18:41:53 +00005509 LHS = LHSCopy;
5510 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005511 }
5512
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005513 // If we have function pointer types, unify them anyway to unify their
5514 // exception specifications, if any.
5515 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5516 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5517 assert(!LTy.isNull() && "failed to find composite pointer type for "
5518 "canonically equivalent function ptr types");
5519 }
5520
Sebastian Redl1a99f442009-04-16 17:51:27 +00005521 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005522 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005523
Douglas Gregor46188682010-05-18 22:42:18 +00005524 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005526 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5527 /*AllowBothBool*/true,
5528 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005529
Sebastian Redl1a99f442009-04-16 17:51:27 +00005530 // -- The second and third operands have arithmetic or enumeration type;
5531 // the usual arithmetic conversions are performed to bring them to a
5532 // common type, and the result is of that type.
5533 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005534 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005535 if (LHS.isInvalid() || RHS.isInvalid())
5536 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005537 if (ResTy.isNull()) {
5538 Diag(QuestionLoc,
5539 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5541 return QualType();
5542 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005543
5544 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5545 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5546
5547 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005548 }
5549
5550 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005551 // type and the other is a null pointer constant, or both are null
5552 // pointer constants, at least one of which is non-integral; pointer
5553 // conversions and qualification conversions are performed to bring them
5554 // to their composite pointer type. The result is of the composite
5555 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005556 // -- The second and third operands have pointer to member type, or one has
5557 // pointer to member type and the other is a null pointer constant;
5558 // pointer to member conversions and qualification conversions are
5559 // performed to bring them to a common type, whose cv-qualification
5560 // shall match the cv-qualification of either the second or the third
5561 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005562 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5563 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005564 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005565
Douglas Gregor697a3912010-04-01 22:47:07 +00005566 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005567 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5568 if (!Composite.isNull())
5569 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005570
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005571 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005572 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005573 return QualType();
5574
Sebastian Redl1a99f442009-04-16 17:51:27 +00005575 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005576 << LHS.get()->getType() << RHS.get()->getType()
5577 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005578 return QualType();
5579}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005580
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005581static FunctionProtoType::ExceptionSpecInfo
5582mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5583 FunctionProtoType::ExceptionSpecInfo ESI2,
5584 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5585 ExceptionSpecificationType EST1 = ESI1.Type;
5586 ExceptionSpecificationType EST2 = ESI2.Type;
5587
5588 // If either of them can throw anything, that is the result.
5589 if (EST1 == EST_None) return ESI1;
5590 if (EST2 == EST_None) return ESI2;
5591 if (EST1 == EST_MSAny) return ESI1;
5592 if (EST2 == EST_MSAny) return ESI2;
5593
5594 // If either of them is non-throwing, the result is the other.
5595 if (EST1 == EST_DynamicNone) return ESI2;
5596 if (EST2 == EST_DynamicNone) return ESI1;
5597 if (EST1 == EST_BasicNoexcept) return ESI2;
5598 if (EST2 == EST_BasicNoexcept) return ESI1;
5599
5600 // If either of them is a non-value-dependent computed noexcept, that
5601 // determines the result.
5602 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5603 !ESI2.NoexceptExpr->isValueDependent())
5604 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5605 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5606 !ESI1.NoexceptExpr->isValueDependent())
5607 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5608 // If we're left with value-dependent computed noexcept expressions, we're
5609 // stuck. Before C++17, we can just drop the exception specification entirely,
5610 // since it's not actually part of the canonical type. And this should never
5611 // happen in C++17, because it would mean we were computing the composite
5612 // pointer type of dependent types, which should never happen.
5613 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5614 assert(!S.getLangOpts().CPlusPlus1z &&
5615 "computing composite pointer type of dependent types");
5616 return FunctionProtoType::ExceptionSpecInfo();
5617 }
5618
5619 // Switch over the possibilities so that people adding new values know to
5620 // update this function.
5621 switch (EST1) {
5622 case EST_None:
5623 case EST_DynamicNone:
5624 case EST_MSAny:
5625 case EST_BasicNoexcept:
5626 case EST_ComputedNoexcept:
5627 llvm_unreachable("handled above");
5628
5629 case EST_Dynamic: {
5630 // This is the fun case: both exception specifications are dynamic. Form
5631 // the union of the two lists.
5632 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5633 llvm::SmallPtrSet<QualType, 8> Found;
5634 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5635 for (QualType E : Exceptions)
5636 if (Found.insert(S.Context.getCanonicalType(E)).second)
5637 ExceptionTypeStorage.push_back(E);
5638
5639 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5640 Result.Exceptions = ExceptionTypeStorage;
5641 return Result;
5642 }
5643
5644 case EST_Unevaluated:
5645 case EST_Uninstantiated:
5646 case EST_Unparsed:
5647 llvm_unreachable("shouldn't see unresolved exception specifications here");
5648 }
5649
5650 llvm_unreachable("invalid ExceptionSpecificationType");
5651}
5652
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005653/// \brief Find a merged pointer type and convert the two expressions to it.
5654///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005655/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005656/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005657/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005658/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005659///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005660/// \param Loc The location of the operator requiring these two expressions to
5661/// be converted to the composite pointer type.
5662///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005663/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005665 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005666 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005667 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005668
5669 // C++1z [expr]p14:
5670 // The composite pointer type of two operands p1 and p2 having types T1
5671 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005672 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005673
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005674 // where at least one is a pointer or pointer to member type or
5675 // std::nullptr_t is:
5676 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5677 T1->isNullPtrType();
5678 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5679 T2->isNullPtrType();
5680 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005681 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005682
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005683 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5684 // This can't actually happen, following the standard, but we also use this
5685 // to implement the end of [expr.conv], which hits this case.
5686 //
5687 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5688 if (T1IsPointerLike &&
5689 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005690 if (ConvertArgs)
5691 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5692 ? CK_NullToMemberPointer
5693 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005694 return T1;
5695 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005696 if (T2IsPointerLike &&
5697 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005698 if (ConvertArgs)
5699 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5700 ? CK_NullToMemberPointer
5701 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005702 return T2;
5703 }
Mike Stump11289f42009-09-09 15:08:12 +00005704
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005705 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005706 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005707 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005708 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5709 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005710
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005711 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5712 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5713 // the union of cv1 and cv2;
5714 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5715 // "pointer to function", where the function types are otherwise the same,
5716 // "pointer to function";
5717 // FIXME: This rule is defective: it should also permit removing noexcept
5718 // from a pointer to member function. As a Clang extension, we also
5719 // permit removing 'noreturn', so we generalize this rule to;
5720 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5721 // "pointer to member function" and the pointee types can be unified
5722 // by a function pointer conversion, that conversion is applied
5723 // before checking the following rules.
5724 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5725 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5726 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5727 // respectively;
5728 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5729 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5730 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5731 // T1 or the cv-combined type of T1 and T2, respectively;
5732 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5733 // T2;
5734 //
5735 // If looked at in the right way, these bullets all do the same thing.
5736 // What we do here is, we build the two possible cv-combined types, and try
5737 // the conversions in both directions. If only one works, or if the two
5738 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005739 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005740 //
5741 // Note that this will fail to find a composite pointer type for "pointer
5742 // to void" and "pointer to function". We can't actually perform the final
5743 // conversion in this case, even though a composite pointer type formally
5744 // exists.
5745 SmallVector<unsigned, 4> QualifierUnion;
5746 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005747 QualType Composite1 = T1;
5748 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005750 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005751 const PointerType *Ptr1, *Ptr2;
5752 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5753 (Ptr2 = Composite2->getAs<PointerType>())) {
5754 Composite1 = Ptr1->getPointeeType();
5755 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005756
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005757 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005758 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005759 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005760 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005762 QualifierUnion.push_back(
5763 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005764 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005765 continue;
5766 }
Mike Stump11289f42009-09-09 15:08:12 +00005767
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005768 const MemberPointerType *MemPtr1, *MemPtr2;
5769 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5770 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5771 Composite1 = MemPtr1->getPointeeType();
5772 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005774 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005776 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005777 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005779 QualifierUnion.push_back(
5780 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5781 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5782 MemPtr2->getClass()));
5783 continue;
5784 }
Mike Stump11289f42009-09-09 15:08:12 +00005785
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005786 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005787
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005788 // Cannot unwrap any more types.
5789 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005792 // Apply the function pointer conversion to unify the types. We've already
5793 // unwrapped down to the function types, and we want to merge rather than
5794 // just convert, so do this ourselves rather than calling
5795 // IsFunctionConversion.
5796 //
5797 // FIXME: In order to match the standard wording as closely as possible, we
5798 // currently only do this under a single level of pointers. Ideally, we would
5799 // allow this in general, and set NeedConstBefore to the relevant depth on
5800 // the side(s) where we changed anything.
5801 if (QualifierUnion.size() == 1) {
5802 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5803 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5804 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5805 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5806
5807 // The result is noreturn if both operands are.
5808 bool Noreturn =
5809 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5810 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5811 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5812
5813 // The result is nothrow if both operands are.
5814 SmallVector<QualType, 8> ExceptionTypeStorage;
5815 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5816 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5817 ExceptionTypeStorage);
5818
5819 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5820 FPT1->getParamTypes(), EPI1);
5821 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5822 FPT2->getParamTypes(), EPI2);
5823 }
5824 }
5825 }
5826
Richard Smith5e9746f2016-10-21 22:00:42 +00005827 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005828 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005830 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005831 for (unsigned I = 0; I != NeedConstBefore; ++I)
5832 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005833 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005835
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005836 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005837 auto MOC = MemberOfClass.rbegin();
5838 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5839 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5840 auto Classes = *MOC++;
5841 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005842 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005843 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005844 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005845 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005846 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005847 } else {
5848 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005849 Composite1 =
5850 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5851 Composite2 =
5852 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005853 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005854 }
5855
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005856 struct Conversion {
5857 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005858 Expr *&E1, *&E2;
5859 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005860 InitializedEntity Entity;
5861 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005862 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005863 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005864
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005865 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5866 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005867 : S(S), E1(E1), E2(E2), Composite(Composite),
5868 Entity(InitializedEntity::InitializeTemporary(Composite)),
5869 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5870 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5871 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005872
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005873 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005874 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5875 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005876 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005877 E1 = E1Result.getAs<Expr>();
5878
5879 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5880 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005881 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005882 E2 = E2Result.getAs<Expr>();
5883
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005884 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005885 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005886 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005887
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005888 // Try to convert to each composite pointer type.
5889 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005890 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5891 if (ConvertArgs && C1.perform())
5892 return QualType();
5893 return C1.Composite;
5894 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005895 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005896
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005897 if (C1.Viable == C2.Viable) {
5898 // Either Composite1 and Composite2 are viable and are different, or
5899 // neither is viable.
5900 // FIXME: How both be viable and different?
5901 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005902 }
5903
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005904 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005905 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5906 return QualType();
5907
5908 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005909}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005910
John McCalldadc5752010-08-24 06:29:42 +00005911ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005912 if (!E)
5913 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005914
John McCall31168b02011-06-15 23:02:42 +00005915 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5916
5917 // If the result is a glvalue, we shouldn't bind it.
5918 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005919 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005920
John McCall31168b02011-06-15 23:02:42 +00005921 // In ARC, calls that return a retainable type can return retained,
5922 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005923 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005924 E->getType()->isObjCRetainableType()) {
5925
5926 bool ReturnsRetained;
5927
5928 // For actual calls, we compute this by examining the type of the
5929 // called value.
5930 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5931 Expr *Callee = Call->getCallee()->IgnoreParens();
5932 QualType T = Callee->getType();
5933
5934 if (T == Context.BoundMemberTy) {
5935 // Handle pointer-to-members.
5936 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5937 T = BinOp->getRHS()->getType();
5938 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5939 T = Mem->getMemberDecl()->getType();
5940 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005941
John McCall31168b02011-06-15 23:02:42 +00005942 if (const PointerType *Ptr = T->getAs<PointerType>())
5943 T = Ptr->getPointeeType();
5944 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5945 T = Ptr->getPointeeType();
5946 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5947 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005948
John McCall31168b02011-06-15 23:02:42 +00005949 const FunctionType *FTy = T->getAs<FunctionType>();
5950 assert(FTy && "call to value not of function type?");
5951 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5952
5953 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5954 // type always produce a +1 object.
5955 } else if (isa<StmtExpr>(E)) {
5956 ReturnsRetained = true;
5957
Ted Kremeneke65b0862012-03-06 20:05:56 +00005958 // We hit this case with the lambda conversion-to-block optimization;
5959 // we don't want any extra casts here.
5960 } else if (isa<CastExpr>(E) &&
5961 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005962 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005963
John McCall31168b02011-06-15 23:02:42 +00005964 // For message sends and property references, we try to find an
5965 // actual method. FIXME: we should infer retention by selector in
5966 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005967 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005968 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005969 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5970 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005971 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5972 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005973 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5974 D = ArrayLit->getArrayWithObjectsMethod();
5975 } else if (ObjCDictionaryLiteral *DictLit
5976 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5977 D = DictLit->getDictWithObjectsMethod();
5978 }
John McCall31168b02011-06-15 23:02:42 +00005979
5980 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005981
5982 // Don't do reclaims on performSelector calls; despite their
5983 // return type, the invoked method doesn't necessarily actually
5984 // return an object.
5985 if (!ReturnsRetained &&
5986 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005987 return E;
John McCall31168b02011-06-15 23:02:42 +00005988 }
5989
John McCall16de4d22011-11-14 19:53:16 +00005990 // Don't reclaim an object of Class type.
5991 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005992 return E;
John McCall16de4d22011-11-14 19:53:16 +00005993
Tim Shen4a05bb82016-06-21 20:29:17 +00005994 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00005995
John McCall2d637d22011-09-10 06:18:15 +00005996 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5997 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005998 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5999 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006000 }
6001
David Blaikiebbafb8a2012-03-11 07:00:24 +00006002 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006003 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006004
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006005 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6006 // a fast path for the common case that the type is directly a RecordType.
6007 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006008 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006009 while (!RT) {
6010 switch (T->getTypeClass()) {
6011 case Type::Record:
6012 RT = cast<RecordType>(T);
6013 break;
6014 case Type::ConstantArray:
6015 case Type::IncompleteArray:
6016 case Type::VariableArray:
6017 case Type::DependentSizedArray:
6018 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6019 break;
6020 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006021 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006022 }
6023 }
Mike Stump11289f42009-09-09 15:08:12 +00006024
Richard Smithfd555f62012-02-22 02:04:18 +00006025 // That should be enough to guarantee that this type is complete, if we're
6026 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006027 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006028 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006029 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006030
6031 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006032 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006033
John McCall31168b02011-06-15 23:02:42 +00006034 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006035 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006036 CheckDestructorAccess(E->getExprLoc(), Destructor,
6037 PDiag(diag::err_access_dtor_temp)
6038 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006039 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6040 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006041
Richard Smithfd555f62012-02-22 02:04:18 +00006042 // If destructor is trivial, we can avoid the extra copy.
6043 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006044 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006045
John McCall28fc7092011-11-10 05:35:25 +00006046 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006047 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006048 }
Richard Smitheec915d62012-02-18 04:13:32 +00006049
6050 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006051 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6052
6053 if (IsDecltype)
6054 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6055
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006056 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006057}
6058
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059ExprResult
John McCall5d413782010-12-06 08:20:24 +00006060Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006061 if (SubExpr.isInvalid())
6062 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006064 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006065}
6066
John McCall28fc7092011-11-10 05:35:25 +00006067Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006068 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006069
Eli Friedman3bda6b12012-02-02 23:15:15 +00006070 CleanupVarDeclMarking();
6071
John McCall28fc7092011-11-10 05:35:25 +00006072 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6073 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006074 assert(Cleanup.exprNeedsCleanups() ||
6075 ExprCleanupObjects.size() == FirstCleanup);
6076 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006077 return SubExpr;
6078
Craig Topper5fc8fc22014-08-27 06:28:36 +00006079 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6080 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006081
Tim Shen4a05bb82016-06-21 20:29:17 +00006082 auto *E = ExprWithCleanups::Create(
6083 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006084 DiscardCleanupsInEvaluationContext();
6085
6086 return E;
6087}
6088
John McCall5d413782010-12-06 08:20:24 +00006089Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006090 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006091
Eli Friedman3bda6b12012-02-02 23:15:15 +00006092 CleanupVarDeclMarking();
6093
Tim Shen4a05bb82016-06-21 20:29:17 +00006094 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006095 return SubStmt;
6096
6097 // FIXME: In order to attach the temporaries, wrap the statement into
6098 // a StmtExpr; currently this is only used for asm statements.
6099 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6100 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006101 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006102 SourceLocation(),
6103 SourceLocation());
6104 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6105 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006106 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006107}
6108
Richard Smithfd555f62012-02-22 02:04:18 +00006109/// Process the expression contained within a decltype. For such expressions,
6110/// certain semantic checks on temporaries are delayed until this point, and
6111/// are omitted for the 'topmost' call in the decltype expression. If the
6112/// topmost call bound a temporary, strip that temporary off the expression.
6113ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006114 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006115
6116 // C++11 [expr.call]p11:
6117 // If a function call is a prvalue of object type,
6118 // -- if the function call is either
6119 // -- the operand of a decltype-specifier, or
6120 // -- the right operand of a comma operator that is the operand of a
6121 // decltype-specifier,
6122 // a temporary object is not introduced for the prvalue.
6123
6124 // Recursively rebuild ParenExprs and comma expressions to strip out the
6125 // outermost CXXBindTemporaryExpr, if any.
6126 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6127 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6128 if (SubExpr.isInvalid())
6129 return ExprError();
6130 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006131 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006132 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006133 }
6134 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6135 if (BO->getOpcode() == BO_Comma) {
6136 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6137 if (RHS.isInvalid())
6138 return ExprError();
6139 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006140 return E;
6141 return new (Context) BinaryOperator(
6142 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6143 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00006144 }
6145 }
6146
6147 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006148 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6149 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006150 if (TopCall)
6151 E = TopCall;
6152 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006153 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006154
6155 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006156 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006157
Richard Smithf86b0ae2012-07-28 19:54:11 +00006158 // In MS mode, don't perform any extra checking of call return types within a
6159 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006160 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006161 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006162
Richard Smithfd555f62012-02-22 02:04:18 +00006163 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006164 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6165 I != N; ++I) {
6166 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006167 if (Call == TopCall)
6168 continue;
6169
David Majnemerced8bdf2015-02-25 17:36:15 +00006170 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006171 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006172 Call, Call->getDirectCallee()))
6173 return ExprError();
6174 }
6175
6176 // Now all relevant types are complete, check the destructors are accessible
6177 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006178 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6179 I != N; ++I) {
6180 CXXBindTemporaryExpr *Bind =
6181 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006182 if (Bind == TopBind)
6183 continue;
6184
6185 CXXTemporary *Temp = Bind->getTemporary();
6186
6187 CXXRecordDecl *RD =
6188 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6189 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6190 Temp->setDestructor(Destructor);
6191
Richard Smith7d847b12012-05-11 22:20:10 +00006192 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6193 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006194 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006195 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006196 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6197 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006198
6199 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006200 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006201 }
6202
6203 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006204 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006205}
6206
Richard Smith79c927b2013-11-06 19:31:51 +00006207/// Note a set of 'operator->' functions that were used for a member access.
6208static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006209 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006210 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6211 // FIXME: Make this configurable?
6212 unsigned Limit = 9;
6213 if (OperatorArrows.size() > Limit) {
6214 // Produce Limit-1 normal notes and one 'skipping' note.
6215 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6216 SkipCount = OperatorArrows.size() - (Limit - 1);
6217 }
6218
6219 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6220 if (I == SkipStart) {
6221 S.Diag(OperatorArrows[I]->getLocation(),
6222 diag::note_operator_arrows_suppressed)
6223 << SkipCount;
6224 I += SkipCount;
6225 } else {
6226 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6227 << OperatorArrows[I]->getCallResultType();
6228 ++I;
6229 }
6230 }
6231}
6232
Nico Weber964d3322015-02-16 22:35:45 +00006233ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6234 SourceLocation OpLoc,
6235 tok::TokenKind OpKind,
6236 ParsedType &ObjectType,
6237 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006238 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006239 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006240 if (Result.isInvalid()) return ExprError();
6241 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006242
John McCall526ab472011-10-25 17:37:35 +00006243 Result = CheckPlaceholderExpr(Base);
6244 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006245 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006246
John McCallb268a282010-08-23 23:25:46 +00006247 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006248 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006249 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006250 // If we have a pointer to a dependent type and are using the -> operator,
6251 // the object type is the type that the pointer points to. We might still
6252 // have enough information about that type to do something useful.
6253 if (OpKind == tok::arrow)
6254 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6255 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006256
John McCallba7bf592010-08-24 05:47:05 +00006257 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006258 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006259 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006260 }
Mike Stump11289f42009-09-09 15:08:12 +00006261
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006262 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006263 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006264 // returned, with the original second operand.
6265 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006266 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006267 bool NoArrowOperatorFound = false;
6268 bool FirstIteration = true;
6269 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006270 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006271 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006272 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006273 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006275 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006276 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6277 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006278 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006279 noteOperatorArrows(*this, OperatorArrows);
6280 Diag(OpLoc, diag::note_operator_arrow_depth)
6281 << getLangOpts().ArrowDepth;
6282 return ExprError();
6283 }
6284
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006285 Result = BuildOverloadedArrowExpr(
6286 S, Base, OpLoc,
6287 // When in a template specialization and on the first loop iteration,
6288 // potentially give the default diagnostic (with the fixit in a
6289 // separate note) instead of having the error reported back to here
6290 // and giving a diagnostic with a fixit attached to the error itself.
6291 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006292 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006293 : &NoArrowOperatorFound);
6294 if (Result.isInvalid()) {
6295 if (NoArrowOperatorFound) {
6296 if (FirstIteration) {
6297 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006298 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006299 << FixItHint::CreateReplacement(OpLoc, ".");
6300 OpKind = tok::period;
6301 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006302 }
6303 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6304 << BaseType << Base->getSourceRange();
6305 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006306 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006307 Diag(CD->getLocStart(),
6308 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006309 }
6310 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006311 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006312 }
John McCallb268a282010-08-23 23:25:46 +00006313 Base = Result.get();
6314 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006315 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006316 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006317 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006318 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006319 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6320 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006321 return ExprError();
6322 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006323 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006326 if (OpKind == tok::arrow &&
6327 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006328 BaseType = BaseType->getPointeeType();
6329 }
Mike Stump11289f42009-09-09 15:08:12 +00006330
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006331 // Objective-C properties allow "." access on Objective-C pointer types,
6332 // so adjust the base type to the object type itself.
6333 if (BaseType->isObjCObjectPointerType())
6334 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006335
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006336 // C++ [basic.lookup.classref]p2:
6337 // [...] If the type of the object expression is of pointer to scalar
6338 // type, the unqualified-id is looked up in the context of the complete
6339 // postfix-expression.
6340 //
6341 // This also indicates that we could be parsing a pseudo-destructor-name.
6342 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006343 // expressions or normal member (ivar or property) access expressions, and
6344 // it's legal for the type to be incomplete if this is a pseudo-destructor
6345 // call. We'll do more incomplete-type checks later in the lookup process,
6346 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006347 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006348 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006349 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006350 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006351 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006352 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006353 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006354 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006355 }
Mike Stump11289f42009-09-09 15:08:12 +00006356
Douglas Gregor3024f072012-04-16 07:05:22 +00006357 // The object type must be complete (or dependent), or
6358 // C++11 [expr.prim.general]p3:
6359 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006360 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006361 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006362 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006363 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006364 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006365 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006366
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006367 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006368 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006369 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006370 // type C (or of pointer to a class type C), the unqualified-id is looked
6371 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006372 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006373 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006374}
6375
Simon Pilgrim75c26882016-09-30 14:25:09 +00006376static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006377 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006378 if (Base->hasPlaceholderType()) {
6379 ExprResult result = S.CheckPlaceholderExpr(Base);
6380 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006381 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006382 }
6383 ObjectType = Base->getType();
6384
David Blaikie1d578782011-12-16 16:03:09 +00006385 // C++ [expr.pseudo]p2:
6386 // The left-hand side of the dot operator shall be of scalar type. The
6387 // left-hand side of the arrow operator shall be of pointer to scalar type.
6388 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006389 // Note that this is rather different from the normal handling for the
6390 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006391 if (OpKind == tok::arrow) {
6392 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6393 ObjectType = Ptr->getPointeeType();
6394 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006395 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006396 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6397 << ObjectType << true
6398 << FixItHint::CreateReplacement(OpLoc, ".");
6399 if (S.isSFINAEContext())
6400 return true;
6401
6402 OpKind = tok::period;
6403 }
6404 }
6405
6406 return false;
6407}
6408
John McCalldadc5752010-08-24 06:29:42 +00006409ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006410 SourceLocation OpLoc,
6411 tok::TokenKind OpKind,
6412 const CXXScopeSpec &SS,
6413 TypeSourceInfo *ScopeTypeInfo,
6414 SourceLocation CCLoc,
6415 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006416 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006417 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006418
Eli Friedman0ce4de42012-01-25 04:35:06 +00006419 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006420 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6421 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006422
Douglas Gregorc5c57342012-09-10 14:57:06 +00006423 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6424 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006425 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006426 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006427 else {
Nico Weber58829272012-01-23 05:50:57 +00006428 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6429 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006430 return ExprError();
6431 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006432 }
6433
6434 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006435 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006436 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006437 if (DestructedTypeInfo) {
6438 QualType DestructedType = DestructedTypeInfo->getType();
6439 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006440 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006441 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6442 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6443 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6444 << ObjectType << DestructedType << Base->getSourceRange()
6445 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006446
John McCall31168b02011-06-15 23:02:42 +00006447 // Recover by setting the destructed type to the object type.
6448 DestructedType = ObjectType;
6449 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00006450 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00006451 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006452 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006453 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006454
John McCall31168b02011-06-15 23:02:42 +00006455 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6456 // Okay: just pretend that the user provided the correctly-qualified
6457 // type.
6458 } else {
6459 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6460 << ObjectType << DestructedType << Base->getSourceRange()
6461 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6462 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006463
John McCall31168b02011-06-15 23:02:42 +00006464 // Recover by setting the destructed type to the object type.
6465 DestructedType = ObjectType;
6466 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6467 DestructedTypeStart);
6468 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6469 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006470 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006473 // C++ [expr.pseudo]p2:
6474 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6475 // form
6476 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006478 //
6479 // shall designate the same scalar type.
6480 if (ScopeTypeInfo) {
6481 QualType ScopeType = ScopeTypeInfo->getType();
6482 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006483 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006485 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006486 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006487 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006488 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006489
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006490 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006491 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006492 }
6493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006494
John McCallb268a282010-08-23 23:25:46 +00006495 Expr *Result
6496 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6497 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006498 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006499 ScopeTypeInfo,
6500 CCLoc,
6501 TildeLoc,
6502 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006503
David Majnemerced8bdf2015-02-25 17:36:15 +00006504 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006505}
6506
John McCalldadc5752010-08-24 06:29:42 +00006507ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006508 SourceLocation OpLoc,
6509 tok::TokenKind OpKind,
6510 CXXScopeSpec &SS,
6511 UnqualifiedId &FirstTypeName,
6512 SourceLocation CCLoc,
6513 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006514 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006515 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6516 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6517 "Invalid first type name in pseudo-destructor");
6518 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6519 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6520 "Invalid second type name in pseudo-destructor");
6521
Eli Friedman0ce4de42012-01-25 04:35:06 +00006522 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006523 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6524 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006525
6526 // Compute the object type that we should use for name lookup purposes. Only
6527 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006528 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006529 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006530 if (ObjectType->isRecordType())
6531 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006532 else if (ObjectType->isDependentType())
6533 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
6536 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006537 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006538 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006539 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006540 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006541 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006542 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006543 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00006544 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006546 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6547 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006549 // couldn't find anything useful in scope. Just store the identifier and
6550 // it's location, and we'll perform (qualified) name lookup again at
6551 // template instantiation time.
6552 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6553 SecondTypeName.StartLocation);
6554 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006555 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006556 diag::err_pseudo_dtor_destructor_non_type)
6557 << SecondTypeName.Identifier << ObjectType;
6558 if (isSFINAEContext())
6559 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006560
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006561 // Recover by assuming we had the right type all along.
6562 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006563 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006564 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006565 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006566 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006567 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006568 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006569 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006570 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006571 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006572 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006573 TemplateId->TemplateNameLoc,
6574 TemplateId->LAngleLoc,
6575 TemplateArgsPtr,
6576 TemplateId->RAngleLoc);
6577 if (T.isInvalid() || !T.get()) {
6578 // Recover by assuming we had the right type all along.
6579 DestructedType = ObjectType;
6580 } else
6581 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583
6584 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006585 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006586 if (!DestructedType.isNull()) {
6587 if (!DestructedTypeInfo)
6588 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006589 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006590 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006593 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006594 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006595 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006597 FirstTypeName.Identifier) {
6598 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006600 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006601 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006602 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006604 diag::err_pseudo_dtor_destructor_non_type)
6605 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006606
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006607 if (isSFINAEContext())
6608 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006610 // Just drop this type. It's unnecessary anyway.
6611 ScopeType = QualType();
6612 } else
6613 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006614 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006615 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006616 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006617 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006618 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006619 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006620 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006621 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006622 TemplateId->TemplateNameLoc,
6623 TemplateId->LAngleLoc,
6624 TemplateArgsPtr,
6625 TemplateId->RAngleLoc);
6626 if (T.isInvalid() || !T.get()) {
6627 // Recover by dropping this type.
6628 ScopeType = QualType();
6629 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006631 }
6632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006633
Douglas Gregor90ad9222010-02-24 23:02:30 +00006634 if (!ScopeType.isNull() && !ScopeTypeInfo)
6635 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6636 FirstTypeName.StartLocation);
6637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006638
John McCallb268a282010-08-23 23:25:46 +00006639 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006640 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006641 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006642}
6643
David Blaikie1d578782011-12-16 16:03:09 +00006644ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6645 SourceLocation OpLoc,
6646 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006647 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006648 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006649 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006650 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6651 return ExprError();
6652
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006653 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6654 false);
David Blaikie1d578782011-12-16 16:03:09 +00006655
6656 TypeLocBuilder TLB;
6657 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6658 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6659 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6660 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6661
6662 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006663 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006664 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006665}
6666
John Wiegley01296292011-04-08 18:41:53 +00006667ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006668 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006669 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006670 if (Method->getParent()->isLambda() &&
6671 Method->getConversionType()->isBlockPointerType()) {
6672 // This is a lambda coversion to block pointer; check if the argument
6673 // is a LambdaExpr.
6674 Expr *SubE = E;
6675 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6676 if (CE && CE->getCastKind() == CK_NoOp)
6677 SubE = CE->getSubExpr();
6678 SubE = SubE->IgnoreParens();
6679 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6680 SubE = BE->getSubExpr();
6681 if (isa<LambdaExpr>(SubE)) {
6682 // For the conversion to block pointer on a lambda expression, we
6683 // construct a special BlockLiteral instead; this doesn't really make
6684 // a difference in ARC, but outside of ARC the resulting block literal
6685 // follows the normal lifetime rules for block literals instead of being
6686 // autoreleased.
6687 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006688 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006689 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6690 E->getExprLoc(),
6691 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006692 PopExpressionEvaluationContext();
6693
Eli Friedman98b01ed2012-03-01 04:01:32 +00006694 if (Exp.isInvalid())
6695 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6696 return Exp;
6697 }
6698 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006699
Craig Topperc3ec1492014-05-26 06:22:03 +00006700 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006701 FoundDecl, Method);
6702 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006703 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006704
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006705 MemberExpr *ME = new (Context) MemberExpr(
6706 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6707 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006708 if (HadMultipleCandidates)
6709 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006710 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006711
Alp Toker314cc812014-01-25 16:55:45 +00006712 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006713 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6714 ResultType = ResultType.getNonLValueExprType(Context);
6715
Douglas Gregor27381f32009-11-23 12:27:39 +00006716 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006717 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006718 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006719 return CE;
6720}
6721
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006722ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6723 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006724 // If the operand is an unresolved lookup expression, the expression is ill-
6725 // formed per [over.over]p1, because overloaded function names cannot be used
6726 // without arguments except in explicit contexts.
6727 ExprResult R = CheckPlaceholderExpr(Operand);
6728 if (R.isInvalid())
6729 return R;
6730
6731 // The operand may have been modified when checking the placeholder type.
6732 Operand = R.get();
6733
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006734 if (ActiveTemplateInstantiations.empty() &&
6735 Operand->HasSideEffects(Context, false)) {
6736 // The expression operand for noexcept is in an unevaluated expression
6737 // context, so side effects could result in unintended consequences.
6738 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6739 }
6740
Richard Smithf623c962012-04-17 00:58:00 +00006741 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006742 return new (Context)
6743 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006744}
6745
6746ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6747 Expr *Operand, SourceLocation RParen) {
6748 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006749}
6750
Eli Friedmanf798f652012-05-24 22:04:19 +00006751static bool IsSpecialDiscardedValue(Expr *E) {
6752 // In C++11, discarded-value expressions of a certain form are special,
6753 // according to [expr]p10:
6754 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6755 // expression is an lvalue of volatile-qualified type and it has
6756 // one of the following forms:
6757 E = E->IgnoreParens();
6758
Eli Friedmanc49c2262012-05-24 22:36:31 +00006759 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006760 if (isa<DeclRefExpr>(E))
6761 return true;
6762
Eli Friedmanc49c2262012-05-24 22:36:31 +00006763 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006764 if (isa<ArraySubscriptExpr>(E))
6765 return true;
6766
Eli Friedmanc49c2262012-05-24 22:36:31 +00006767 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006768 if (isa<MemberExpr>(E))
6769 return true;
6770
Eli Friedmanc49c2262012-05-24 22:36:31 +00006771 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006772 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6773 if (UO->getOpcode() == UO_Deref)
6774 return true;
6775
6776 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006777 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006778 if (BO->isPtrMemOp())
6779 return true;
6780
Eli Friedmanc49c2262012-05-24 22:36:31 +00006781 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006782 if (BO->getOpcode() == BO_Comma)
6783 return IsSpecialDiscardedValue(BO->getRHS());
6784 }
6785
Eli Friedmanc49c2262012-05-24 22:36:31 +00006786 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006787 // operands are one of the above, or
6788 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6789 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6790 IsSpecialDiscardedValue(CO->getFalseExpr());
6791 // The related edge case of "*x ?: *x".
6792 if (BinaryConditionalOperator *BCO =
6793 dyn_cast<BinaryConditionalOperator>(E)) {
6794 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6795 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6796 IsSpecialDiscardedValue(BCO->getFalseExpr());
6797 }
6798
6799 // Objective-C++ extensions to the rule.
6800 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6801 return true;
6802
6803 return false;
6804}
6805
John McCall34376a62010-12-04 03:47:34 +00006806/// Perform the conversions required for an expression used in a
6807/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006808ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006809 if (E->hasPlaceholderType()) {
6810 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006811 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006812 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006813 }
6814
John McCallfee942d2010-12-02 02:07:15 +00006815 // C99 6.3.2.1:
6816 // [Except in specific positions,] an lvalue that does not have
6817 // array type is converted to the value stored in the
6818 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006819 if (E->isRValue()) {
6820 // In C, function designators (i.e. expressions of function type)
6821 // are r-values, but we still want to do function-to-pointer decay
6822 // on them. This is both technically correct and convenient for
6823 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006824 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006825 return DefaultFunctionArrayConversion(E);
6826
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006827 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006828 }
John McCallfee942d2010-12-02 02:07:15 +00006829
Eli Friedmanf798f652012-05-24 22:04:19 +00006830 if (getLangOpts().CPlusPlus) {
6831 // The C++11 standard defines the notion of a discarded-value expression;
6832 // normally, we don't need to do anything to handle it, but if it is a
6833 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6834 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006835 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006836 E->getType().isVolatileQualified() &&
6837 IsSpecialDiscardedValue(E)) {
6838 ExprResult Res = DefaultLvalueConversion(E);
6839 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006840 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006841 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006842 }
Richard Smith122f88d2016-12-06 23:52:28 +00006843
6844 // C++1z:
6845 // If the expression is a prvalue after this optional conversion, the
6846 // temporary materialization conversion is applied.
6847 //
6848 // We skip this step: IR generation is able to synthesize the storage for
6849 // itself in the aggregate case, and adding the extra node to the AST is
6850 // just clutter.
6851 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6852 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006853 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006854 }
John McCall34376a62010-12-04 03:47:34 +00006855
6856 // GCC seems to also exclude expressions of incomplete enum type.
6857 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6858 if (!T->getDecl()->isComplete()) {
6859 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006860 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006861 return E;
John McCall34376a62010-12-04 03:47:34 +00006862 }
6863 }
6864
John Wiegley01296292011-04-08 18:41:53 +00006865 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6866 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006867 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006868 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006869
John McCallca61b652010-12-04 12:29:11 +00006870 if (!E->getType()->isVoidType())
6871 RequireCompleteType(E->getExprLoc(), E->getType(),
6872 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006873 return E;
John McCall34376a62010-12-04 03:47:34 +00006874}
6875
Faisal Valia17d19f2013-11-07 05:17:06 +00006876// If we can unambiguously determine whether Var can never be used
6877// in a constant expression, return true.
6878// - if the variable and its initializer are non-dependent, then
6879// we can unambiguously check if the variable is a constant expression.
6880// - if the initializer is not value dependent - we can determine whether
6881// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006882// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006883// never be a constant expression.
6884// - FXIME: if the initializer is dependent, we can still do some analysis and
6885// identify certain cases unambiguously as non-const by using a Visitor:
6886// - such as those that involve odr-use of a ParmVarDecl, involve a new
6887// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006888static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006889 ASTContext &Context) {
6890 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006891 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006892
6893 // If there is no initializer - this can not be a constant expression.
6894 if (!Var->getAnyInitializer(DefVD)) return true;
6895 assert(DefVD);
6896 if (DefVD->isWeak()) return false;
6897 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006898
Faisal Valia17d19f2013-11-07 05:17:06 +00006899 Expr *Init = cast<Expr>(Eval->Value);
6900
6901 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006902 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6903 // of value-dependent expressions, and use it here to determine whether the
6904 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006905 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006906 }
6907
Simon Pilgrim75c26882016-09-30 14:25:09 +00006908 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006909}
6910
Simon Pilgrim75c26882016-09-30 14:25:09 +00006911/// \brief Check if the current lambda has any potential captures
6912/// that must be captured by any of its enclosing lambdas that are ready to
6913/// capture. If there is a lambda that can capture a nested
6914/// potential-capture, go ahead and do so. Also, check to see if any
6915/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006916/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006917
Faisal Valiab3d6462013-12-07 20:22:44 +00006918static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6919 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6920
Simon Pilgrim75c26882016-09-30 14:25:09 +00006921 assert(!S.isUnevaluatedContext());
6922 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00006923#ifndef NDEBUG
6924 DeclContext *DC = S.CurContext;
6925 while (DC && isa<CapturedDecl>(DC))
6926 DC = DC->getParent();
6927 assert(
6928 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006929 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00006930#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00006931
6932 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6933
6934 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6935 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006936
Faisal Valiab3d6462013-12-07 20:22:44 +00006937 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006938 // lambda (within a generic outer lambda), must be captured by an
6939 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006940 const unsigned NumPotentialCaptures =
6941 CurrentLSI->getNumPotentialVariableCaptures();
6942 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006943 Expr *VarExpr = nullptr;
6944 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006945 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006946 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00006947 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00006948 // need to check enclosing lambda's for speculative captures.
6949 // For e.g.:
6950 // Even though 'x' is not odr-used, it should be captured.
6951 // int test() {
6952 // const int x = 10;
6953 // auto L = [=](auto a) {
6954 // (void) +x + a;
6955 // };
6956 // }
6957 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006958 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00006959 continue;
6960
6961 // If we have a capture-capable lambda for the variable, go ahead and
6962 // capture the variable in that lambda (and all its enclosing lambdas).
6963 if (const Optional<unsigned> Index =
6964 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6965 FunctionScopesArrayRef, Var, S)) {
6966 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6967 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6968 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006969 }
6970 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00006971 VariableCanNeverBeAConstantExpression(Var, S.Context);
6972 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6973 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00006974 // can not be used in a constant expression - which means
6975 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00006976 // capture violation early, if the variable is un-captureable.
6977 // This is purely for diagnosing errors early. Otherwise, this
6978 // error would get diagnosed when the lambda becomes capture ready.
6979 QualType CaptureType, DeclRefType;
6980 SourceLocation ExprLoc = VarExpr->getExprLoc();
6981 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006982 /*EllipsisLoc*/ SourceLocation(),
6983 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006984 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00006985 // We will never be able to capture this variable, and we need
6986 // to be able to in any and all instantiations, so diagnose it.
6987 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006988 /*EllipsisLoc*/ SourceLocation(),
6989 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006990 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006991 }
6992 }
6993 }
6994
Faisal Valiab3d6462013-12-07 20:22:44 +00006995 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006996 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006997 // If we have a capture-capable lambda for 'this', go ahead and capture
6998 // 'this' in that lambda (and all its enclosing lambdas).
6999 if (const Optional<unsigned> Index =
7000 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007001 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007002 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7003 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7004 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7005 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007006 }
7007 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007008
7009 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007010 CurrentLSI->clearPotentialCaptures();
7011}
7012
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007013static ExprResult attemptRecovery(Sema &SemaRef,
7014 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007015 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007016 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7017 Consumer.getLookupResult().getLookupKind());
7018 const CXXScopeSpec *SS = Consumer.getSS();
7019 CXXScopeSpec NewSS;
7020
7021 // Use an approprate CXXScopeSpec for building the expr.
7022 if (auto *NNS = TC.getCorrectionSpecifier())
7023 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7024 else if (SS && !TC.WillReplaceSpecifier())
7025 NewSS = *SS;
7026
Richard Smithde6d6c42015-12-29 19:43:10 +00007027 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007028 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007029 R.addDecl(ND);
7030 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007031 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007032 CXXRecordDecl *Record = nullptr;
7033 if (auto *NNS = TC.getCorrectionSpecifier())
7034 Record = NNS->getAsType()->getAsCXXRecordDecl();
7035 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007036 Record =
7037 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7038 if (Record)
7039 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007040
7041 // Detect and handle the case where the decl might be an implicit
7042 // member.
7043 bool MightBeImplicitMember;
7044 if (!Consumer.isAddressOfOperand())
7045 MightBeImplicitMember = true;
7046 else if (!NewSS.isEmpty())
7047 MightBeImplicitMember = false;
7048 else if (R.isOverloadedResult())
7049 MightBeImplicitMember = false;
7050 else if (R.isUnresolvableResult())
7051 MightBeImplicitMember = true;
7052 else
7053 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7054 isa<IndirectFieldDecl>(ND) ||
7055 isa<MSPropertyDecl>(ND);
7056
7057 if (MightBeImplicitMember)
7058 return SemaRef.BuildPossibleImplicitMemberExpr(
7059 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007060 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007061 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7062 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7063 Ivar->getIdentifier());
7064 }
7065 }
7066
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007067 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7068 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007069}
7070
Kaelyn Takata6c759512014-10-27 18:07:37 +00007071namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007072class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7073 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7074
7075public:
7076 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7077 : TypoExprs(TypoExprs) {}
7078 bool VisitTypoExpr(TypoExpr *TE) {
7079 TypoExprs.insert(TE);
7080 return true;
7081 }
7082};
7083
Kaelyn Takata6c759512014-10-27 18:07:37 +00007084class TransformTypos : public TreeTransform<TransformTypos> {
7085 typedef TreeTransform<TransformTypos> BaseTransform;
7086
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007087 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7088 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007089 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007090 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007091 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007092 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007093
7094 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7095 /// If the TypoExprs were successfully corrected, then the diagnostics should
7096 /// suggest the corrections. Otherwise the diagnostics will not suggest
7097 /// anything (having been passed an empty TypoCorrection).
7098 void EmitAllDiagnostics() {
7099 for (auto E : TypoExprs) {
7100 TypoExpr *TE = cast<TypoExpr>(E);
7101 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007102 if (State.DiagHandler) {
7103 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7104 ExprResult Replacement = TransformCache[TE];
7105
7106 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7107 // TypoCorrection, replacing the existing decls. This ensures the right
7108 // NamedDecl is used in diagnostics e.g. in the case where overload
7109 // resolution was used to select one from several possible decls that
7110 // had been stored in the TypoCorrection.
7111 if (auto *ND = getDeclFromExpr(
7112 Replacement.isInvalid() ? nullptr : Replacement.get()))
7113 TC.setCorrectionDecl(ND);
7114
7115 State.DiagHandler(TC);
7116 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007117 SemaRef.clearDelayedTypo(TE);
7118 }
7119 }
7120
7121 /// \brief If corrections for the first TypoExpr have been exhausted for a
7122 /// given combination of the other TypoExprs, retry those corrections against
7123 /// the next combination of substitutions for the other TypoExprs by advancing
7124 /// to the next potential correction of the second TypoExpr. For the second
7125 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7126 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7127 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7128 /// TransformCache). Returns true if there is still any untried combinations
7129 /// of corrections.
7130 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7131 for (auto TE : TypoExprs) {
7132 auto &State = SemaRef.getTypoExprState(TE);
7133 TransformCache.erase(TE);
7134 if (!State.Consumer->finished())
7135 return true;
7136 State.Consumer->resetCorrectionStream();
7137 }
7138 return false;
7139 }
7140
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007141 NamedDecl *getDeclFromExpr(Expr *E) {
7142 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7143 E = OverloadResolution[OE];
7144
7145 if (!E)
7146 return nullptr;
7147 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007148 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007149 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007150 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007151 // FIXME: Add any other expr types that could be be seen by the delayed typo
7152 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007153 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007154 return nullptr;
7155 }
7156
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007157 ExprResult TryTransform(Expr *E) {
7158 Sema::SFINAETrap Trap(SemaRef);
7159 ExprResult Res = TransformExpr(E);
7160 if (Trap.hasErrorOccurred() || Res.isInvalid())
7161 return ExprError();
7162
7163 return ExprFilter(Res.get());
7164 }
7165
Kaelyn Takata6c759512014-10-27 18:07:37 +00007166public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007167 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7168 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007169
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007170 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7171 MultiExprArg Args,
7172 SourceLocation RParenLoc,
7173 Expr *ExecConfig = nullptr) {
7174 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7175 RParenLoc, ExecConfig);
7176 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007177 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007178 Expr *ResultCall = Result.get();
7179 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7180 ResultCall = BE->getSubExpr();
7181 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7182 OverloadResolution[OE] = CE->getCallee();
7183 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007184 }
7185 return Result;
7186 }
7187
Kaelyn Takata6c759512014-10-27 18:07:37 +00007188 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7189
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007190 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7191
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007192 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7193 return Owned(E);
7194 }
7195
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007196 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7197 return Owned(E);
7198 }
7199
Kaelyn Takata6c759512014-10-27 18:07:37 +00007200 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007201 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007202 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007203 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007204
Kaelyn Takata6c759512014-10-27 18:07:37 +00007205 // Exit if either the transform was valid or if there were no TypoExprs
7206 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007207 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007208 !CheckAndAdvanceTypoExprCorrectionStreams())
7209 break;
7210 }
7211
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007212 // Ensure none of the TypoExprs have multiple typo correction candidates
7213 // with the same edit length that pass all the checks and filters.
7214 // TODO: Properly handle various permutations of possible corrections when
7215 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007216 // Also, disable typo correction while attempting the transform when
7217 // handling potentially ambiguous typo corrections as any new TypoExprs will
7218 // have been introduced by the application of one of the correction
7219 // candidates and add little to no value if corrected.
7220 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007221 while (!AmbiguousTypoExprs.empty()) {
7222 auto TE = AmbiguousTypoExprs.back();
7223 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007224 auto &State = SemaRef.getTypoExprState(TE);
7225 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007226 TransformCache.erase(TE);
7227 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007228 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007229 TransformCache.erase(TE);
7230 Res = ExprError();
7231 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007232 }
7233 AmbiguousTypoExprs.remove(TE);
7234 State.Consumer->restoreSavedPosition();
7235 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007236 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007237 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007238
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007239 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007240 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007241 FindTypoExprs(TypoExprs).TraverseStmt(E);
7242
Kaelyn Takata6c759512014-10-27 18:07:37 +00007243 EmitAllDiagnostics();
7244
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007245 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007246 }
7247
7248 ExprResult TransformTypoExpr(TypoExpr *E) {
7249 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7250 // cached transformation result if there is one and the TypoExpr isn't the
7251 // first one that was encountered.
7252 auto &CacheEntry = TransformCache[E];
7253 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7254 return CacheEntry;
7255 }
7256
7257 auto &State = SemaRef.getTypoExprState(E);
7258 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7259
7260 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7261 // typo correction and return it.
7262 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007263 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007264 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007265 // FIXME: If we would typo-correct to an invalid declaration, it's
7266 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007267 ExprResult NE = State.RecoveryHandler ?
7268 State.RecoveryHandler(SemaRef, E, TC) :
7269 attemptRecovery(SemaRef, *State.Consumer, TC);
7270 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007271 // Check whether there may be a second viable correction with the same
7272 // edit distance; if so, remember this TypoExpr may have an ambiguous
7273 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007274 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007275 if ((Next = State.Consumer->peekNextCorrection()) &&
7276 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7277 AmbiguousTypoExprs.insert(E);
7278 } else {
7279 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007280 }
7281 assert(!NE.isUnset() &&
7282 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007283 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007284 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007285 }
7286 return CacheEntry = ExprError();
7287 }
7288};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007289}
Faisal Valia17d19f2013-11-07 05:17:06 +00007290
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007291ExprResult
7292Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7293 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007294 // If the current evaluation context indicates there are uncorrected typos
7295 // and the current expression isn't guaranteed to not have typos, try to
7296 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007297 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007298 (E->isTypeDependent() || E->isValueDependent() ||
7299 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007300 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7301 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7302 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007303 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007304 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007305 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007306 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007307 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007308 ExprEvalContexts.back().NumTypos -= TyposResolved;
7309 return Result;
7310 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007311 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007312 }
7313 return E;
7314}
7315
Richard Smith945f8d32013-01-14 22:39:08 +00007316ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007317 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007318 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007319 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007320 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007321
7322 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007323 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007324
7325 // If we are an init-expression in a lambdas init-capture, we should not
7326 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007327 // containing full-expression is done).
7328 // template<class ... Ts> void test(Ts ... t) {
7329 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7330 // return a;
7331 // }() ...);
7332 // }
7333 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7334 // when we parse the lambda introducer, and teach capturing (but not
7335 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7336 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7337 // lambda where we've entered the introducer but not the body, or represent a
7338 // lambda where we've entered the body, depending on where the
7339 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007340 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007341 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007342 return ExprError();
7343
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007344 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007345 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007346 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007347 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007348 if (FullExpr.isInvalid())
7349 return ExprError();
7350 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007351
Richard Smith945f8d32013-01-14 22:39:08 +00007352 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007353 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007354 if (FullExpr.isInvalid())
7355 return ExprError();
7356
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007357 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007358 if (FullExpr.isInvalid())
7359 return ExprError();
7360 }
John Wiegley01296292011-04-08 18:41:53 +00007361
Kaelyn Takata49d84322014-11-11 23:26:56 +00007362 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7363 if (FullExpr.isInvalid())
7364 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007365
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007366 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007367
Simon Pilgrim75c26882016-09-30 14:25:09 +00007368 // At the end of this full expression (which could be a deeply nested
7369 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007370 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007371 // Consider the following code:
7372 // void f(int, int);
7373 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007374 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007375 // const int x = 10, y = 20;
7376 // auto L = [=](auto a) {
7377 // auto M = [=](auto b) {
7378 // f(x, b); <-- requires x to be captured by L and M
7379 // f(y, a); <-- requires y to be captured by L, but not all Ms
7380 // };
7381 // };
7382 // }
7383
Simon Pilgrim75c26882016-09-30 14:25:09 +00007384 // FIXME: Also consider what happens for something like this that involves
7385 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007386 // void f() {
7387 // const int n = 0;
7388 // auto L = [&](auto a) {
7389 // +n + ({ 0; a; });
7390 // };
7391 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007392 //
7393 // Here, we see +n, and then the full-expression 0; ends, so we don't
7394 // capture n (and instead remove it from our list of potential captures),
7395 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007396 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007397
Alexey Bataev31939e32016-11-11 12:36:20 +00007398 LambdaScopeInfo *const CurrentLSI =
7399 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007400 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007401 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007402 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007403 // By ensuring we are in the context of a lambda's call operator
7404 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007405 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007406 // PR, a proper fix would entail :
7407 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007408 // - Add to Sema an integer holding the smallest (outermost) scope
7409 // index that we are *lexically* within, and save/restore/set to
7410 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007411 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007412 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007413 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007414 DeclContext *DC = CurContext;
7415 while (DC && isa<CapturedDecl>(DC))
7416 DC = DC->getParent();
7417 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007418 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007419 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007420 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7421 *this);
John McCall5d413782010-12-06 08:20:24 +00007422 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007423}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007424
7425StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7426 if (!FullStmt) return StmtError();
7427
John McCall5d413782010-12-06 08:20:24 +00007428 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007429}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007430
Simon Pilgrim75c26882016-09-30 14:25:09 +00007431Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007432Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7433 CXXScopeSpec &SS,
7434 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007435 DeclarationName TargetName = TargetNameInfo.getName();
7436 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007437 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007438
Douglas Gregor43edb322011-10-24 22:31:10 +00007439 // If the name itself is dependent, then the result is dependent.
7440 if (TargetName.isDependentName())
7441 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007442
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007443 // Do the redeclaration lookup in the current scope.
7444 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7445 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007446 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007447 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007448
Douglas Gregor43edb322011-10-24 22:31:10 +00007449 switch (R.getResultKind()) {
7450 case LookupResult::Found:
7451 case LookupResult::FoundOverloaded:
7452 case LookupResult::FoundUnresolvedValue:
7453 case LookupResult::Ambiguous:
7454 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007455
Douglas Gregor43edb322011-10-24 22:31:10 +00007456 case LookupResult::NotFound:
7457 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007458
Douglas Gregor43edb322011-10-24 22:31:10 +00007459 case LookupResult::NotFoundInCurrentInstantiation:
7460 return IER_Dependent;
7461 }
David Blaikie8a40f702012-01-17 06:56:22 +00007462
7463 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007464}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007465
Simon Pilgrim75c26882016-09-30 14:25:09 +00007466Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007467Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7468 bool IsIfExists, CXXScopeSpec &SS,
7469 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007470 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007471
Richard Smith151c4562016-12-20 21:35:28 +00007472 // Check for an unexpanded parameter pack.
7473 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7474 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7475 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007476 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007477
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007478 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7479}